package cn.net.caoyao.cpzshandset.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class YthScannerShipmentDBHelper extends SQLiteOpenHelper {
	private static final int VERSION = 1;// 提交状态增加一个生产功能
	public final static String db_name = "ythScannerShipmentHandset.db";
	/**
	 * 产品信息表
	 */
	public static final String tb_product_info = "productInfo";

	/**
	 * 激活信息表
	 */
	public static final String tb_activate_info = "activateInfo";
	/**
	 * 单标操作表
	 */
	public static final String tb_single_label_option = "singleLabelOption";
	/**
	 * 批量标签操作表
	 */
	public static final String tb_batch_label_option = "batchLabelOption";
	/**
	 * 产品的点击次数表
	 */
	public static final String tb_product_choice_count = "productChoiceCount";
	/**
	 * 汽车客户信息表
	 */
	public static final String tb_truck_consignee_info = "truckConsigneeInfo";
	/**
	 * 汽车客户信息表 中的索引
	 */
//	public static final String tb_truck_consignee_index_name = "truckConsigneeIndex";
	/**
	 * 汽车收货地址的详细信息表
	 */
	public static final String tb_truck_shipment_address_info = "truckShipmentAddress";
	/**
	 * 汽车收货地址的详细信息表 索引
	 */
//	public static final String tb_truck_shipment_addres_index_name = "truckShipmentAddressIndex";
	/**
	 * 汽车发运单
	 */
	public static final String tb_truck_invoice ="truckInvoice";
	/**
	 * 发运单
	 */
	public static final String tb_invoice = "invoice";
	/**
	 * 线上获取的订单列表
	 */
	public static final String tb_online_truck_invoice ="onlineTruckInvoice";
	
	public static final String tb_driver_info = "driverInfo";
	/**
	 * 责任人表 ResponsiblePersonId
	 * @param context
	 */
	public static final String tb_responsible_person = "responsiblePerson";
	/**
	 * 订单上传记录表
	 */
	public static final String tb_shipment_upload_record="shipmentUploadRecord";
	public YthScannerShipmentDBHelper(Context context) {
		super(context, db_name, null, VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		createProductInfo(db);
		createProductChoiceCount(db);
		createActivateInfo(db);
		createSingleLabelOption(db);
		createBatchLabelOption(db);
		createTruckConsigneeInfo(db);
		createTruckShipmentAddressInfo(db);
		createTruckInvoice(db);
		createInvoice(db);
		createResponsiblePerson(db);
		createOnlineTruckInvoice(db);
		createDriverInfo(db);
		createShipmentUploadRecord(db);
	}
	private void createShipmentUploadRecord(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + tb_shipment_upload_record +" (id INTEGER PRIMARY KEY AUTOINCREMENT,option_type INTEGER,account VARCHAR(20),driver_id bigint,order_id bigint,driver_name VARCHAR(20),driver_tel VARCHAR(20),car_no VARCHAR(20),order_no VARCHAR(20),client_user VARCHAR(20),busi_unit VARCHAR(20),product_name VARCHAR(20),label_count INTEGER,status INTEGER,error_code INTEGER,upload_date DATE DEFAULT (date('now','localtime')))";	
		db.execSQL(sql);
	}

	/**
	 * id bigint(20) NOT NULL主键ID
	 * order_id bigint(20) NULL订单ID(关联订单表主键)
	 * driver_name varchar(20) NULL驾驶员姓名
	 * driver_phone varchar(20) NULL驾驶员电话
	 * car_no varchar(20) NULL车牌号
	 * driver_licenseNo varchar(30) NULL驾驶证件号
	 * out_orderId varchar(30) NULL外向交货单号
	 * num varchar(30) NULL数量
	 * over_count：超过数量
	 * can_shipment_count：还可以发货的数量（目前用作已发货包数）
	 * status int(2) NULL状态0:正常1:删除
	 */
	private void createDriverInfo(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + tb_driver_info +" (id bigint PRIMARY KEY,order_id bigint,driver_name VARCHAR(20),driver_phone VARCHAR(20),car_no VARCHAR(20),driver_licenseNo VARCHAR(20),out_orderId VARCHAR(20),num VARCHAR(20),pack_num VARCHAR(20), can_shipment_count VARCHAR(20),online_status INTEGER,native_status INTEGER default 0,error_code INTEGER default 0,over_count INTEGER,createDate DATE DEFAULT (date('now','localtime')),updateDate DATE DEFAULT (date('now','localtime')))";
		db.execSQL(sql);
	}

	/**
	 * 
	 * id bigint(20) NOT NULL订单ID
	 * order_no varchar(25) NULL订单号
	 * client_user varchar(100) NULL客户名称
	 * busi_unit varchar(20) NULL业务单位
	 * take_addr varchar(100) NULL提货地点
	 * product_name varchar(200) NULL产品名称
	 * plan_num varchar(10) NULL计划数量(吨)
	 * pack_num varchar(10) NULL件数
	 * isZhang varchar(20) NULL是否过账,0:未 1:是 2:退单
	 * online_status int(4) NOT NULL发货状态， 0 是未发货，1是已经发货
	 * remark varchar(255) NULL备注
	 * timestamp：订单创建时间
	 * labelMode：
	 * status：提交状态
	 * error_code：错误码
	 * over_count：超过数量
	 * createDate：创建时间
	 * updateDate：更新时间
	 * @param db
	 */
	private void createOnlineTruckInvoice(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + tb_online_truck_invoice + " (id bigint PRIMARY KEY,order_no VARCHAR(20),client_user VARCHAR(20),busi_unit VARCHAR(20),take_addr VARCHAR(20),product_name VARCHAR(20),plan_num VARCHAR(20),pack_num VARCHAR(20),isZhang VARCHAR(20),remark VARCHAR(20),online_status INTEGER,sales_area INTEGER,responsiblePersonId VARCHAR(20),timestamp VARCHAR(20),labelMode INTEGER default 1,native_status INTEGER default 0,error_code INTEGER,over_count INTEGER,createDate DATE DEFAULT (date('now','localtime')),updateDate DATE DEFAULT (date('now','localtime')))";
		db.execSQL(sql);
	}

	/**
	 * account：登录账户
	 * pwd：密码
	 * username：责任人名称
	 * tel：电话
	 * @param db
	 */
	private void createResponsiblePerson(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + tb_responsible_person+" (account VARCHAR(20) PRIMARY KEY, pwd VARCHAR(20),username VARCHAR(20), tel VARCHAR(20), userType integer default 0)";
		db.execSQL(sql);
	}

	/**
	 * id:发运单ID 
	 * transmode:发运方式： 1：火车发运(车皮) 2:汽车发运(货车) 
	 * transid:发运单id(火车发运单/汽车发运单)
	 * elemtype:类型 1：托盘包含的标签 2：单个产品的标签 
	 * labelid:标签ID 
	 * timestamp:时间戳
	 * expand1:目前用作判定invoice是否有效
	 * @param db
	 */
	private void createInvoice(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + tb_invoice
				+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, transmode INTEGER default 3,transid bigint,elemtype INTEGER default 2,labelid VARCHAR(20),labelStatus INTEGER default 0 ,timestamp VARCHAR(20),package_id varchar(32),createDate DATE DEFAULT (date('now','localtime')))";
		db.execSQL(sql);
	}

	/**
	 *id：主键，自增
	 * responsiblePersonId：责任人id
	 * truckno：车牌号
	 * drivername：司机名称
	 * driverPhone：司机电话
	 * orderNo：订单号
	 * gruopInfo：班组信息
	 * startStation：起始站
	 * terminalStationCode：结束站的code码
	 * detailAddress：到达站的详细地址信息
	 * consignee：收货人信息
	 * take_address：提货地址
	 * product_name：产品名称
	 * out_orderId：外向交货单号
	 * plan_num：计划数量
	 * real_num：实际数量
	 * is_zhang：是否过账
	 * timestamp：订单创建时间
	 * labelMode：
	 * status：提交状态
	 * error_code：错误码
	 * createDate：创建时间
	 * updateDate：更新时间
	 * @param db
	 */
	private void createTruckInvoice(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + tb_truck_invoice + " (id INTEGER PRIMARY KEY,responsiblePersonId VARCHAR(20),truckNo VARCHAR(20),driverName VARCHAR(20), driverPhone VARCHAR(20),orderNo VARCHAR(20),gruopInfo VARCHAR(20), startStation INTEGER default 0,terminalStationCode INTEGER,detailAddress VARCHAR(20),consignee VARCHAR(20),timestamp VARCHAR(20),labelMode INTEGER default 1,status INTEGER default 0,error_code INTEGER,createDate DATE DEFAULT (date('now','localtime')),updateDate DATE DEFAULT (date('now','localtime')))";
		db.execSQL(sql);		
	}

	/**
	 * id：主键，自增
	 * cityCode：三级地址信息的Code码
	 * detailAddress：详细地址信息的文字信息
	 * detailAddressPY：详细地址信息的拼音
	 * originType：来源   0：本地生成    1：服务器获取
	 * createDate：创建时间
	 * updateDate：更新日期
	 * @param db
	 */
	private void createTruckShipmentAddressInfo(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + tb_truck_shipment_address_info
				+ " (id INTEGER PRIMARY KEY AUTOINCREMENT,provinceCode INTEGER,cityCode INTEGER,detailAddress VARCHAR(20),detailAddressPY VARCHAR(20),originType INTEGER default 0,createDate DATE DEFAULT (date('now','localtime')),updateDate DATE DEFAULT (date('now','localtime')))";
		db.execSQL(sql);
		// 给detailAddress列建立索引 CREATE UNIQUE INDEX unique_index_url ON http_cache
		// (url);
//		String createIndexSql = "CREATE UNIQUE INDEX truckShipmentAddressIndex ON " + tb_truck_shipment_address_info
//				+ " (detailAddress)";
//		db.execSQL(createIndexSql);
		String createIndexSql = "CREATE UNIQUE INDEX truckShipmentAddressIndex ON " + tb_truck_shipment_address_info + "(cityCode, detailAddress)";
		db.execSQL(createIndexSql);
	}

	/**
	 * id：自增主键 
	 * consigneeName：客户名称 
	 * consigneeNamePY：客户名称的首字母拼音 
	 * originType：来源   0：本地生成    1：服务器获取
	 * createDate：创建时间
	 * updateDate：更新日期
	 * @param db
	 */
	private void createTruckConsigneeInfo(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + tb_truck_consignee_info
				+ " (id INTEGER PRIMARY KEY AUTOINCREMENT,consigneeName VARCHAR(20),consigneeNamePY VARCHAR(20),originType INTEGER default 0,createDate DATE DEFAULT (date('now','localtime')),updateDate DATE DEFAULT (date('now','localtime')))";
		db.execSQL(sql);
		// 给consigneeName列建立索引 CREATE UNIQUE INDEX unique_index_url ON http_cache
		// (url);
		String createIndexSql = "CREATE UNIQUE INDEX truckConsigneeIndex ON " + tb_truck_consignee_info
				+ " (consigneeName)";
		db.execSQL(createIndexSql);
	}

	/**
	 * start_label_id：起始标签 end_label_id：结束标签
	 * option_type：操作类型（其中的插入值对应于HansetOperationConstant类中的值） option_id：关联的表的id
	 * 
	 * @param db
	 */
	private void createBatchLabelOption(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + tb_batch_label_option
				+ " (id INTEGER PRIMARY KEY AUTOINCREMENT,start_label_id bigint,end_label_id bigint,option_type INTEGER,option_id INTEGER)";
		db.execSQL(sql);
	}

	/**
	 * label_id：扫描的标签id option_type：操作类型（其中的插入值对应于HansetOperationConstant类中的值）
	 * option_id：关联的表的id
	 * 
	 * @param db
	 */
	private void createSingleLabelOption(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + tb_single_label_option
				+ " (id INTEGER PRIMARY KEY AUTOINCREMENT,label_id bigint,option_type INTEGER,option_id INTEGER)";
		db.execSQL(sql);
	}

	/**
	 * id:激活表ID,主键自增 product_id：对应的产品表中的产品ID product_date：生产日期
	 * product_batch_number：生产批号 group_number:班组号 factory_code:厂区 producer：生产者
	 * option_mode：操作方式 0：单标激活 1：批量激活 status：提交状态 0：未提交 1：提交失败
	 * error_code：服务器返回的错误码 createDate：创建时间
	 * 
	 * @param db
	 */
	private void createActivateInfo(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + tb_activate_info
				+ " (id INTEGER PRIMARY KEY AUTOINCREMENT,product_id VARCHAR(20),product_date VARCHAR(20),product_batch_number VARCHAR(20),group_number VARCHAR(20),factory_code VARCHAR(20) DEFAULT '358000000_6',producer VARCHAR(20),option_mode INTEGER DEFAULT 0 ,status INTEGER DEFAULT 0 ,error_code INTEGER,createDate DATE DEFAULT (date('now','localtime')))";
		db.execSQL(sql);
	}

	/**
	 * id:产品id，服务器返回的数据直接插入 name：产品名称 pNamePy: nid：产品编号（即，商品条码）
	 * p_image_url:图片的URL choiceCount:选择次数
	 * 
	 * @param db
	 */
	private void createProductInfo(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + tb_product_info
				+ " (id INTEGER,name VARCHAR(20),pNamePy VARCHAR(20),nid VARCHAR(20),p_image_url VARCHAR(20),choiceCount INTEGER)";
		db.execSQL(sql);
	}

	/**
	 * id:产品id，服务器返回的数据直接插入 name：产品名称 nid：产品编号（即，商品条码） p_image_url:图片的URL
	 * choiceCount:选择次数
	 * 
	 * @param db
	 */
	private void createProductChoiceCount(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + tb_product_choice_count + " (id INTEGER PRIMARY KEY,choiceCount INTEGER)";
		db.execSQL(sql);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}

	/**
	 * 检测数据库中是否存在某一列
	 * 
	 * @param db
	 * @param tableName
	 * @param primaryKeyName
	 * @param columnName
	 * @return true:存在 false:不存在
	 */
	private boolean checkColumnExists(SQLiteDatabase db, String tableName, String primaryKeyName, String columnName) {
		boolean b = true;
		String sql = "SELECT * from " + tableName + " where " + primaryKeyName + "=0";
		Cursor cursor = db.rawQuery(sql, null);
		int columnIndex = cursor.getColumnIndex(columnName);
		cursor.close();
		if (columnIndex < 0) {
			b = false;
		}
		return b;
	}

}
