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 CounterDBHelper extends SQLiteOpenHelper {
	private static final int VERSION = 1;// 提交状态增加一个生产功能
	public final static String db_name = "counterHandset.db";
	/**
	 * 单标操作表
	 */
	public static final String tb_single_label_option = "singleLabelOption";
	/**
	 * 上传记录
	 */
	public static final String tb_upload_status = "uploadStatus";


	public CounterDBHelper(Context context) {
		super(context, db_name, null, VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		createSingleLabelOption(db);
		createUploadStatus(db);
	}
	

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


	/**
	 * id：表ID,主键自增
	 * option_type：操作类型（其中的插入值对应于HansetOperationConstant类中的值）
	 * label_count：上传的标签数量
	 * status：提交状态  0：上传成功 1：上传失败
	 * error_code：服务器返回的错误码
	 * upload_date：创建时间
	 * @param db
	 */
	private void createUploadStatus(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + tb_upload_status + " (id INTEGER PRIMARY KEY AUTOINCREMENT,option_type INTEGER,label_count INTEGER,status INTEGER,error_code INTEGER,upload_date DATE DEFAULT (date('now','localtime')))";
		db.execSQL(sql);
	}


	/**
	 * label_id：扫描的标签id   
	 * option_type：操作类型（其中的插入值对应于HansetOperationConstant类中的值）
	 * option_id：关联的表的id
	 * labelStatus：当前标签的状态   0:默认值    1:不合法标签    2:重复激活标签     3:未激活标签
	 * @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,labelStatus INTEGER default 0,create_date DATE DEFAULT (datetime('now','localtime')),update_date DATE DEFAULT (datetime('now','localtime')))";
		db.execSQL(sql);	
	}
	
	/**
	 * 检测数据库中是否存在某一列
	 * @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;
	}

}
