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

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.TruckInvoiceBean;
import cn.net.caoyao.cpzshandset.db.YthImageDBHelper;
import cn.net.caoyao.cpzshandset.db.presenter.base.TruckInvoiceDalImpl;

public class YthImageTruckInvoiceDal extends TruckInvoiceDalImpl{
	private SQLiteDatabase db;
	private YthImageDBHelper helper;
	public YthImageTruckInvoiceDal(Context context) {
		helper = new YthImageDBHelper(context);
	}
	/**
	 * 插入汽车运单信息
	 * @param invoice
	 */
	public int insertTruckInvoice(TruckInvoiceBean invoice){
		int key = -1;
		db = helper.getWritableDatabase();
		String sql = "insert into " + YthImageDBHelper.tb_truck_invoice +" (truckNo,driverName,driverPhone,orderNo,gruopInfo,startStation,terminalStationCode,detailAddress,consignee,timestamp,labelMode,status,error_code) values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
		db.execSQL(sql, new Object[]{invoice.getTruckno(),invoice.getDrivername(),invoice.getDriverphone(),invoice.getOrderno(),invoice.getGruopInfo(),invoice.getStartingstation(),invoice.getTerminalStationCode(),invoice.getDetailAddress(),invoice.getConsignee(),invoice.getTimestamp(),invoice.getLabelMode(),invoice.getStartingstation(),invoice.getError_code()});
//		String querySql = "SELECT MAX(id) from " + YthImageDBHelper.tb_truck_invoice;
		String querySql = "select last_insert_rowid() from "+YthImageDBHelper.tb_truck_invoice;
		Cursor cursor = db.rawQuery(querySql, null);
		if (cursor.moveToNext()) {
//			LogUtil.e(TConfig.Echo, "key:"+cursor.getInt(0));
			key = cursor.getInt(0);
		}
		closeDB(db,cursor);
		return key;
	}
	
	/**
	 * 插入时检测已经数据库中已经存在该订单
	 * @param trainInvoice
	 * @return
	 */
	public boolean insertHasExist(TruckInvoiceBean truckInvoice){
		boolean isExist = false;
		db = helper.getReadableDatabase();
		String sql = "select count(*) as count from " + YthImageDBHelper.tb_truck_invoice +" where truckno=? and orderno=? and status=?";
		Cursor queryCursor = db.rawQuery(sql, new String[]{truckInvoice.getTruckno(), truckInvoice.getOrderno(), String.valueOf(truckInvoice.getStatus())});
		if (queryCursor.moveToNext()) {
			int count = queryCursor.getInt(0);
			if (count > 0) {
				isExist = true;
			}
		}
		closeDB(db, queryCursor);
		return isExist;
	}
	
	/**
	 * 修改当前订单单个标签的上传类型
	 * @param invoice
	 * @return
	 */
	public TruckInvoiceBean updateTruckLabelMode(TruckInvoiceBean invoice){
		TruckInvoiceBean tInvoice = null;
		db = helper.getWritableDatabase();
		String updateSql = "UPDATE " + YthImageDBHelper.tb_truck_invoice +" SET labelMode=(-1)*labelMode WHERE id=?";
		db.execSQL(updateSql, new Object[]{invoice.getId()});
		String querySql = "SELECT * FROM " + YthImageDBHelper.tb_truck_invoice +" WHERE id=?";
		Cursor cursor = db.rawQuery(querySql, new String[]{String.valueOf(invoice.getId())});
		if (cursor.moveToNext()) {
			tInvoice = getTruckInvoice(cursor);
		}
		closeDB(db, cursor);
		return tInvoice;
	}
	/**
	 * 修改时检测数据库中已经存在该订单
	 * @param trainInvoice
	 * @return
	 */
	public boolean updateHasExist(TruckInvoiceBean truckInvoice){
		boolean isExist = false;
		db = helper.getReadableDatabase();
		String sql = "select count(*) as count from " + YthImageDBHelper.tb_truck_invoice +" where truckNo=? and orderNo=? and id!=?";
		Cursor queryCursor = db.rawQuery(sql, new String[]{truckInvoice.getTruckno(), truckInvoice.getOrderno(), String.valueOf(truckInvoice.getId())});
		if (queryCursor.moveToNext()) {
			int count = queryCursor.getInt(0);
			if (count > 0) {
				isExist = true;
			}
		}
		closeDB(db, queryCursor);
		return isExist;
	}
	/**
	 * 修改汽车运单信息
	 * @param invoice
	 */
	public void updateTruckInvoice(TruckInvoiceBean invoice){
		db = helper.getWritableDatabase();
		String sql = "update "+YthImageDBHelper.tb_truck_invoice+" set truckNo=?,driverName=?,driverPhone=?,orderNo=?,gruopInfo=?,startStation=?,terminalStationCode=?,detailAddress=?,consignee=?,timestamp=?,labelMode=?,status=?,error_code=? where id=?";
		db.execSQL(sql, new Object[]{invoice.getTruckno(),invoice.getDrivername(),invoice.getDriverphone(),invoice.getOrderno(),invoice.getGruopInfo(),invoice.getStartingstation(),invoice.getTerminalStationCode(),invoice.getDetailAddress(),invoice.getConsignee(),invoice.getTimestamp(),invoice.getLabelMode(),invoice.getStatus(),invoice.getError_code(),invoice.getId()});
		closeDB(db, null);
	}
	/**
	 * 根据修单号，修改汽车运单信息
	 * @param status 0:有效   1:无效
	 * @param id
	 */
	public void updateTruckInvoiceStatus(int status,int errorCode, int id){
		db = helper.getWritableDatabase();
		String sql = "update " + YthImageDBHelper.tb_truck_invoice +" set status=?,error_code=? where id=?";
		db.execSQL(sql, new Object[]{status,errorCode,id});
		closeDB(db, null);
	}
	/**
	 * 通过运单ID，查询运单信息
	 * @param id
	 * @return
	 */
	public TruckInvoiceBean queryTruckInvoiceById(int id){
		db = helper.getReadableDatabase();
		String sql = "select * from " + YthImageDBHelper.tb_truck_invoice+" where id=?";
		Cursor cursor = db.rawQuery(sql, new String[]{String.valueOf(id)});
		TruckInvoiceBean invoice = null;
		if (cursor.moveToNext()) {
			invoice = getTruckInvoice(cursor);
		}
		closeDB(db, cursor);
		return invoice;
	}
	/**
	 * 通过运单状态，查询运单信息
	 * @param status 0:有效  1:无效
	 * @return
	 */
	public List<TruckInvoiceBean> queryAllTruckInvoices(){
		db = helper.getReadableDatabase();
		String sql = "select * from " + YthImageDBHelper.tb_truck_invoice+" order by id desc";
		Cursor cursor = db.rawQuery(sql, null);
		List<TruckInvoiceBean> invoices = new ArrayList<TruckInvoiceBean>();
		while (cursor.moveToNext()) {
			TruckInvoiceBean invoice = getTruckInvoice(cursor);
			invoices.add(invoice);
		}
		closeDB(db, cursor);
		return invoices;
	}
	
	/**
	 * 通过运单状态，查询运单信息
	 * @param status 0:有效  1:无效
	 * @return
	 */
	public List<TruckInvoiceBean> queryAllTruckInvoicesASC(){
		db = helper.getReadableDatabase();
		String sql = "select * from " + YthImageDBHelper.tb_truck_invoice+" order by id ASC";
		Cursor cursor = db.rawQuery(sql, null);
		List<TruckInvoiceBean> invoices = new ArrayList<TruckInvoiceBean>();
		while (cursor.moveToNext()) {
			TruckInvoiceBean invoice = getTruckInvoice(cursor);
			invoices.add(invoice);
		}
		closeDB(db, cursor);
		return invoices;
	}
	
	
	/**
	 * 删除所有的汽车发货无效订单
	 */
	public void deleteTruckInvoiceById(TruckInvoiceBean invoice){
		db = helper.getWritableDatabase();
//		LogUtil.d(TConfig.Echo, "deleteTruckInvoiceById:" + invoice.getId());
		String delInvoiceSql = "delete from " + YthImageDBHelper.tb_invoice +" where transmode=? and transid=?";
		db.execSQL(delInvoiceSql, new Object[]{2,invoice.getId()});
		
		String delTruckSql = "delete from " + YthImageDBHelper.tb_truck_invoice +" where id=?";
		db.execSQL(delTruckSql, new Object[]{invoice.getId()});
		
		closeDB(db, null);
	}
	
	public TruckInvoiceBean getTruckInvoice(Cursor cursor) {
		TruckInvoiceBean invoice = new TruckInvoiceBean();
		invoice.setId(cursor.getInt(cursor.getColumnIndex("id")));
		invoice.setTruckno(cursor.getString(cursor.getColumnIndex("truckNo")));
		invoice.setDrivername(cursor.getString(cursor.getColumnIndex("driverName")));
		invoice.setDriverphone(cursor.getString(cursor.getColumnIndex("driverPhone")));
		invoice.setOrderno(cursor.getString(cursor.getColumnIndex("orderNo")));
		invoice.setGruopInfo(cursor.getString(cursor.getColumnIndex("gruopInfo")));
		invoice.setStartingstation(cursor.getInt(cursor.getColumnIndex("startStation")));
		invoice.setTerminalStationCode(cursor.getInt(cursor.getColumnIndex("terminalStationCode")));
		invoice.setDetailAddress(cursor.getString(cursor.getColumnIndex("detailAddress")));
		invoice.setConsignee(cursor.getString(cursor.getColumnIndex("consignee")));
		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")));
		return invoice;
	}
	private void closeDB(SQLiteDatabase db, Cursor cursor) {
		if (cursor != null) {
			cursor.close();
		}
		if (db != null) {
			db.close();
		}
	}
	

}
