package cn.net.caoyao.cpzshandset.db.dal.yth;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import cn.net.caoyao.cpzshandset.bean.TrainInvoiceBean;
import cn.net.caoyao.cpzshandset.common.config.TConfig;
import cn.net.caoyao.cpzshandset.common.util.LogUtil;
import cn.net.caoyao.cpzshandset.db.YthDBHelper;
import cn.net.caoyao.cpzshandset.db.presenter.base.TrainInvoiceDalImpl;

public class YthTrainInvoiceDal extends TrainInvoiceDalImpl{
	private SQLiteDatabase db;
	private YthDBHelper helper;

	public YthTrainInvoiceDal(Context context) {
		helper = new YthDBHelper(context);
	}

	/**
	 * 生成火车订单信息
	 * 
	 * @param trainInvoice
	 */
	public int insertTrainInvoice(TrainInvoiceBean trainInvoice) {
		int key = -1;
		db = helper.getWritableDatabase();//select @@identity
		String sql = "insert into " + YthDBHelper.tb_train_invoice
				+ " (carriageno,startingstation,terminalstation,consigneeId,orderno,timestamp,labelMode,status,expand1,expand2) values (?,?,?,?,?,?,?,?,?,?)";
		db.execSQL(sql,
				new Object[] { trainInvoice.getCarriageno(), trainInvoice.getStartingstation(),
						trainInvoice.getTerminalstation(), trainInvoice.getConsigneeId(),trainInvoice.getOrderno(), trainInvoice.getTimestamp(),
						trainInvoice.getLabelMode(),trainInvoice.getStatus() , trainInvoice.getExpand1(), trainInvoice.getExpand2() });
//		String querySql = "SELECT MAX(id) from " + YthDBHelper.tb_train_invoice;//返回当表中
		String querySql = "select last_insert_rowid() from " + YthDBHelper.tb_train_invoice;
		
//		String querySql = "select @@identity";
		Cursor cursor = db.rawQuery(querySql, null);
		if (cursor.moveToNext()) {
			key = cursor.getInt(0);
			LogUtil.e(TConfig.Echo, "key:"+key);
		}
		closeDB(db, cursor);
		return key;
	}
	/**
	 * 插入时检测已经数据库中已经存在该订单
	 * @param trainInvoice
	 * @return
	 */
	public boolean insertHasExist(TrainInvoiceBean trainInvoice){
		boolean isExist = false;
		db = helper.getReadableDatabase();
		String sql = "select count(*) as count from " + YthDBHelper.tb_train_invoice +" where carriageno=? and orderno=? and status=?";
		Cursor queryCursor = db.rawQuery(sql, new String[]{trainInvoice.getCarriageno(), trainInvoice.getOrderno(), String.valueOf(trainInvoice.getStatus())});
		if (queryCursor.moveToNext()) {
			int count = queryCursor.getInt(0);
			if (count > 0) {
				isExist = true;
			}
		}
		closeDB(db, queryCursor);
		return isExist;
	}
	/**
	 * 修改时检测数据库中已经存在该订单
	 * @param trainInvoice
	 * @return
	 */
	public boolean updateHasExist(TrainInvoiceBean trainInvoice){
		boolean isExist = false;
		db = helper.getReadableDatabase();
		String sql = "select count(*) as count from " + YthDBHelper.tb_train_invoice +" where carriageno=? and orderno=? and id!=?";
		Cursor queryCursor = db.rawQuery(sql, new String[]{trainInvoice.getCarriageno(), trainInvoice.getOrderno(), String.valueOf(trainInvoice.getId())});
		if (queryCursor.moveToNext()) {
			int count = queryCursor.getInt(0);
			if (count > 0) {
				isExist = true;
			}
		}
		closeDB(db, queryCursor);
		return isExist;
	}
	//UPDATE `tbl_label_info_358000000` SET ISPRODUCT=(-1)*ISPRODUCT WHERE label_id=100215130712
	/**
	 * 修改当前订单单个标签的上传类型
	 * @param invoice
	 * @return
	 */
	public TrainInvoiceBean updateTrainLabelMode(TrainInvoiceBean invoice){
		TrainInvoiceBean tInvoice = null;
		db = helper.getReadableDatabase();
		String updateSql = "UPDATE " + YthDBHelper.tb_train_invoice +" SET labelMode=(-1)*labelMode WHERE id=?";
		db.execSQL(updateSql, new Object[]{invoice.getId()});
		String querySql = "SELECT * FROM " + YthDBHelper.tb_train_invoice +" WHERE id=?";
		Cursor cursor = db.rawQuery(querySql, new String[]{String.valueOf(invoice.getId())});
		if (cursor.moveToNext()) {
			tInvoice = getTrainInvoice(cursor);
		}
		closeDB(db, cursor);
		return tInvoice;
	}

	/**
	 * 修改火车订单信息
	 * 
	 * @param trainInvoice
	 */
	public void updateTrainInvoice(TrainInvoiceBean trainInvoice) {
		db = helper.getWritableDatabase();
		String sql = "update " + YthDBHelper.tb_train_invoice
				+ " set carriageno=?,startingstation=?,terminalstation=?,consigneeId=?,orderno=?,timestamp=?,labelMode=?,expand1=?,expand2=? where id=?";
		db.execSQL(sql,
				new Object[] { trainInvoice.getCarriageno(), trainInvoice.getStartingstation(),
						trainInvoice.getTerminalstation(),trainInvoice.getConsigneeId(), trainInvoice.getOrderno(), trainInvoice.getTimestamp(),
						trainInvoice.getLabelMode(),trainInvoice.getExpand1(),trainInvoice.getExpand2(), trainInvoice.getId() });
		closeDB(db, null);
	}

	/**
	 * 根据订单Id,修改火车订单状态
	 * 
	 * @param status
	 *            0:有效 1:无效
	 * @param id
	 */
	public void updateTrainErrorStatus(int status,int errorCode, int id) {
		db = helper.getWritableDatabase();
		String sql = "update " + YthDBHelper.tb_train_invoice + " set status=?,error_code=? where id=?";
		db.execSQL(sql, new Object[] { status,errorCode, id });
		closeDB(db, null);
	}

	/**
	 * 根据运单ID获取订单信息
	 * @param id
	 * @return
	 */
	public TrainInvoiceBean queryTrainInvoiceById(int id) {
		db = helper.getReadableDatabase();
		String sql = "select * from " + YthDBHelper.tb_train_invoice + " where id=?";
		Cursor cursor = db.rawQuery(sql, new String[] { String.valueOf(id) });
		TrainInvoiceBean trainInvoice = null;
		if (cursor.moveToNext()) {
			trainInvoice = getTrainInvoice(cursor);
		}
		closeDB(db, cursor);
		return trainInvoice;
	}

	/**
	 * 根据订单状态获取订单列表
	 * @param status 0:有效    1:无效
	 * @return
	 */
	public List<TrainInvoiceBean> queryAllTrainInvoices() {
		List<TrainInvoiceBean> trainInvoices = new ArrayList<TrainInvoiceBean>();
		db = helper.getReadableDatabase();
		String sql = "select * from " + YthDBHelper.tb_train_invoice + " order by id desc";
		Cursor cursor = db.rawQuery(sql, null);
//		String sql = "select * from " + YthDBHelper.tb_train_invoice + " order by id desc";
//		Cursor cursor = db.rawQuery(sql, null);
		while (cursor.moveToNext()) {
			TrainInvoiceBean invoice = getTrainInvoice(cursor);
			trainInvoices.add(invoice);
		}
		closeDB(db, cursor);
		return trainInvoices;
	}
	
	/**
	 * 根据订单状态获取订单列表
	 * @param status 0:有效    1:无效
	 * @return
	 */
	public List<TrainInvoiceBean> queryAllTrainInvoicesASC() {
		List<TrainInvoiceBean> trainInvoices = new ArrayList<TrainInvoiceBean>();
		db = helper.getReadableDatabase();
		String sql = "select * from " + YthDBHelper.tb_train_invoice + " order by id asc";
		Cursor cursor = db.rawQuery(sql, null);
//		String sql = "select * from " + YthDBHelper.tb_train_invoice + " order by id desc";
//		Cursor cursor = db.rawQuery(sql, null);
		while (cursor.moveToNext()) {
			TrainInvoiceBean invoice = getTrainInvoice(cursor);
			trainInvoices.add(invoice);
		}
		closeDB(db, cursor);
		return trainInvoices;
	}
	
	/**
	 * 查询火车发运单的有效订单数
	 * @return  status 0:有效    1:无效
	 */
	public int queryValidTrainNumber(){
		int count = 0;
		db = helper.getReadableDatabase();
		String sql = "select count(*) as count from " + YthDBHelper.tb_train_invoice + " where status=0";
		Cursor cursor = db.rawQuery(sql, null);
		if (cursor.moveToNext()) {
			count = cursor.getInt(0);
		}
		closeDB(db, cursor);
		return count;
	}
	/**
	 * 根据订单状态删除订单
	 * @param status
	 */
	public void deleteInvalidInvoice(int status){
		db = helper.getWritableDatabase();
		String sql = "delete from " + YthDBHelper.tb_train_invoice +" where status=?";
		db.execSQL(sql, new Object[]{status});
		closeDB(db, null);
	}
	
	/**
	 * 删除数据表中所有的无效订单
	 * @param status
	 */
	public void deleteAllInvalidInvoice(){
		db = helper.getWritableDatabase();
		String queryValidSql = "select * from " + YthDBHelper.tb_train_invoice +" where status=1";
		Cursor cursor = db.rawQuery(queryValidSql, null);
		while (cursor.moveToNext()) {
			TrainInvoiceBean invoice = getTrainInvoice(cursor);
			String delInvoiceSql = "delete from " + YthDBHelper.tb_invoice +" where transmode=1 and transid=?";
			db.execSQL(delInvoiceSql, new Object[]{invoice.getId()});
		}
		String delTrainSql = "delete from " + YthDBHelper.tb_train_invoice +" where status=1";
		db.execSQL(delTrainSql);
		closeDB(db, cursor);
	}
	
	/**
	 * 根据火车订单信息，删除本地订单及其对应的标签
	 * @param trainInvoice
	 */
	public void deleteTrainInvoiceById(TrainInvoiceBean trainInvoice){
		db = helper.getWritableDatabase();
		String delInvoiceSql = "delete from " + YthDBHelper.tb_invoice +" where transmode=1 and transid=?";
		db.execSQL(delInvoiceSql, new Object[]{trainInvoice.getId()});
		String delTrainSql = "delete from " + YthDBHelper.tb_train_invoice +" where id=?";
		db.execSQL(delTrainSql, new Object[]{trainInvoice.getId()});
		closeDB(db, null);
	}

	public TrainInvoiceBean getTrainInvoice(Cursor cursor) {
		TrainInvoiceBean invoice = new TrainInvoiceBean();
		invoice.setId(cursor.getInt(cursor.getColumnIndex("id")));
		invoice.setCarriageno(cursor.getString(cursor.getColumnIndex("carriageno")));
		invoice.setStartingstation(cursor.getInt(cursor.getColumnIndex("startingstation")));
		invoice.setTerminalstation(cursor.getInt(cursor.getColumnIndex("terminalstation")));
		invoice.setConsigneeId(cursor.getInt(cursor.getColumnIndex("consigneeId")));
		invoice.setOrderno(cursor.getString(cursor.getColumnIndex("orderno")));
		invoice.setTimestamp(cursor.getString(cursor.getColumnIndex("timestamp")));
		invoice.setLabelMode(cursor.getInt(cursor.getColumnIndex("labelMode")));
		invoice.setStatus(cursor.getInt(cursor.getColumnIndex("status")));
		invoice.setError_code(cursor.getInt(cursor.getColumnIndex("error_code")));
		invoice.setExpand1(cursor.getString(cursor.getColumnIndex("expand1")));
		invoice.setExpand2(cursor.getString(cursor.getColumnIndex("expand2")));
		return invoice;
	}

	private void closeDB(SQLiteDatabase db, Cursor cursor) {
		if (cursor != null) {
			cursor.close();
		}
		if (db != null) {
			db.close();
		}
	}
}
