package cn.net.caoyao.cpzshandset.service.thread.impl.yth;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import cn.net.caoyao.cpzshandset.bean.InvoiceBean;
import cn.net.caoyao.cpzshandset.bean.OrderFail;
import cn.net.caoyao.cpzshandset.bean.TrainInvoiceBean;
import cn.net.caoyao.cpzshandset.bean.TruckInvoiceBean;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.config.RequestConstant;
import cn.net.caoyao.cpzshandset.common.config.TConfig;
import cn.net.caoyao.cpzshandset.common.util.LogUtil;
import cn.net.caoyao.cpzshandset.service.bll.InvoiceBll;
import cn.net.caoyao.cpzshandset.service.bll.TrainInvoiceBll;
import cn.net.caoyao.cpzshandset.service.bll.TruckInvoiceBll;
import cn.net.cpzslibs.prot.Prot02Logout;
import cn.net.cpzslibs.prot.SocketCreate;
import cn.net.cpzslibs.prot.bean.req.Prot10051InvoiceBean;
import cn.net.cpzslibs.prot.bean.req.Prot10051ReqBean;
import cn.net.cpzslibs.prot.bean.res.Prot10051ResBean;
import cn.net.cpzslibs.prot.handset.newProt.Prot20010SubmitInvoice;

public class YthSubmitInvoiceRunable implements Runnable {
	private Handler mHandler;
	private long deveicedId; 
	private TrainInvoiceBll trainBll;
	private TruckInvoiceBll truckBll;
	private InvoiceBll invoiceBll;
	private int trainFail = 0;
	private int truckFail = 0;
	private List<OrderFail> orderFails = new ArrayList<OrderFail>();
	private int transMode = 1;//提交火车运单
	public YthSubmitInvoiceRunable(Handler mHandler, long deveicedId,TrainInvoiceBll trainBll,TruckInvoiceBll truckBll,InvoiceBll invoiceBll,int transMode) {
		this.mHandler = mHandler;
		this.deveicedId = deveicedId;
		this.trainBll = trainBll;
		this.truckBll = truckBll;
		this.invoiceBll = invoiceBll;
		this.transMode = transMode;
	}

	@Override
	public void run() {
		SocketCreate create = new SocketCreate(Config.ip, Config.port, String.valueOf(deveicedId));
		try {
			create.createLoginCpzsHandset(deveicedId);
			if (create.isResult()) {
				Prot20010SubmitInvoice prot20010Submit = new Prot20010SubmitInvoice();
				if (transMode == 1) {
					submitTrainInvoice(create, prot20010Submit);//上传火车订单
				} else if (transMode == 2) {
					submitTruckInvoice(create, prot20010Submit);//上传汽车订单
				} else {
					submitTrainInvoice(create, prot20010Submit);//上传火车订单
					submitTruckInvoice(create, prot20010Submit);//上传汽车订单
				}
				handlerToUI();
			} else {
				Message loginFailMsg = mHandler.obtainMessage();
				loginFailMsg.obj = create.getErrMsg();
				loginFailMsg.arg1 = create.getiErrCode();
				loginFailMsg.what = RequestConstant.REQUEST_PROT01_LOGIN_FAIL;
				mHandler.sendMessage(loginFailMsg);
			}
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT);
		} catch (IOException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
		} finally{
			new Prot02Logout().dealLogout(create);
		}
	}

	private void handlerToUI() {
		if (trainFail == 0 && truckFail == 0) {
			mHandler.sendEmptyMessage(RequestConstant.PROT_SUBMIT_INVOICE_10051_SUCCESS);
		} else {
			Message failMsg = mHandler.obtainMessage();
			failMsg.arg1 = trainFail;
			failMsg.arg2 = truckFail;
			failMsg.obj = orderFails;
			failMsg.what = RequestConstant.PROT_SUBMIT_INVOICE_10051_FAIL;
			mHandler.sendMessage(failMsg);
		}
	}


	private void submitTruckInvoice(SocketCreate create, Prot20010SubmitInvoice prot20010Submit) throws SocketTimeoutException, IOException{
		List<TruckInvoiceBean> invoices = truckBll.queryAllTruckInvoicesASC();
		if (invoices != null) {
			for (TruckInvoiceBean truckInvoice : invoices) {
				if (truckInvoice != null) {
					List<String> via = getTruckViaList(truckInvoice);
					List<String> label = getTruckLabelList(truckInvoice);
					if (via.size() == 0 && label.size() == 0) {
						//当前订单里面无数据
					} else {
						 prot20010Submit.submitInvoice(create, getTruckReqBean(truckInvoice, via,label));
						Prot10051ResBean resBean =  prot20010Submit.getResponse();
						if (resBean.getResult() == 0) {
							//请求成功时,删除当前订单
							truckBll.deleteTruckInvoiceById(truckInvoice);
						} else {
							truckBll.updateTruckSubmitStatus(Config.SUBMIT_STATUS_SUBMIT_FAIL, resBean.getErrcode(), truckInvoice.getId());
							truckFail ++;//记录当前货车发货订单上传失败数
							orderFails.add(new OrderFail(truckInvoice.getId(), 2,resBean.getErrcode(), resBean.getResult()));
							
						}
					}
					
				}
			}
		}
	}

	private Prot10051ReqBean getTruckReqBean(TruckInvoiceBean truckInvoice, List<String> via, List<String> label){
		Prot10051ReqBean reqBean = new Prot10051ReqBean();
		reqBean.setType(2);//货车发货
		Prot10051InvoiceBean invoiceBean = new Prot10051InvoiceBean();
		invoiceBean.setTruck_no(truckInvoice.getTruckno());
		invoiceBean.setDriver_name(truckInvoice.getDrivername());
		invoiceBean.setDriver_phone(truckInvoice.getDriverphone());
		invoiceBean.setStarting_station(truckInvoice.getStartingstation());
		invoiceBean.setTerminal_station(truckInvoice.getTerminalstation());
		invoiceBean.setOrder_no(truckInvoice.getOrderno());
		invoiceBean.setTimestamp(truckInvoice.getTimestamp());
		invoiceBean.setVid(via);
		invoiceBean.setLabel_id(label);
		invoiceBean.setOpt(truckInvoice.getLabelMode());
		reqBean.setOrder(invoiceBean);
		return reqBean;
	}

	private List<String> getTruckLabelList(TruckInvoiceBean truckInvoice) {
		List<String> labels = new ArrayList<String>();
		List<InvoiceBean> invoices = invoiceBll.queryTruckLabelInvoices(truckInvoice);
		for (InvoiceBean invoice : invoices) {
			labels.add(invoice.getLabelid());
		}
		return labels;
	}

	private List<String> getTruckViaList(TruckInvoiceBean truckInvoice) {
		List<String> vias = new ArrayList<String>();
		List<InvoiceBean> invoices = invoiceBll.queryTruckTrayInvoices(truckInvoice);
		for (InvoiceBean invoice : invoices) {
			vias.add(invoice.getLabelid());
		}
		return vias;
	}

	private void submitTrainInvoice(SocketCreate create, Prot20010SubmitInvoice prot20010Submit) throws IOException, SocketTimeoutException{
		List<TrainInvoiceBean> invoices = trainBll.queryAllTrainInvoicesASC();
		if (invoices != null) {
			for (TrainInvoiceBean trainInvoice : invoices) {
				if (trainInvoice != null) {
					List<String> via = getViaList(trainInvoice);
					List<String> label = getLabelList(trainInvoice);
					if (via.size() == 0 && label.size() == 0) {
						//当前订单没有任何数据，不提交
					} else {
						prot20010Submit.submitInvoice(create, getTrainReqBean(trainInvoice, via,label));
						Prot10051ResBean resBean = prot20010Submit.getResponse();
//						LogUtil.e(TConfig.Echo, "----" + resBean.toString());
						if (resBean.getResult() == 0) {
							//请求成功时,将当前的火车订单置为无效订单
							trainBll.deleteTrainInvoiceById(trainInvoice);
						} else {
							trainBll.updateTrainErrorStatus(Config.SUBMIT_STATUS_SUBMIT_FAIL, resBean.getErrcode(), trainInvoice.getId());
							trainFail ++;
							orderFails.add(new OrderFail(trainInvoice.getId(), 1,resBean.getErrcode(), resBean.getResult()));
						}
					}
					
				}
				
				
			}
			
		}
	}

	/**
	 * 构建火车发货单列表
	 * @param trainInvoice
	 * @param via
	 * @param label
	 * @return
	 */
	private Prot10051ReqBean getTrainReqBean(TrainInvoiceBean trainInvoice, List<String> via, List<String> label) {
		Prot10051ReqBean reqBean = new Prot10051ReqBean();
		reqBean.setType(1);//火车发货
		Prot10051InvoiceBean invoiceBean = new Prot10051InvoiceBean();
		invoiceBean.setCarriage_no(trainInvoice.getCarriageno());
		invoiceBean.setStarting_station(trainInvoice.getStartingstation());
		invoiceBean.setTerminal_station(trainInvoice.getTerminalstation());
		invoiceBean.setCustomer_id(trainInvoice.getConsigneeId());
		invoiceBean.setOrder_no(trainInvoice.getOrderno());
		invoiceBean.setTimestamp(trainInvoice.getTimestamp());
		invoiceBean.setVid(via);
		invoiceBean.setLabel_id(label);
		invoiceBean.setOpt(trainInvoice.getLabelMode());
//		LogUtil.e(TConfig.Echo, "====" + trainInvoice.getLabelMode());
		reqBean.setOrder(invoiceBean);
		LogUtil.d(TConfig.Echo, "--reqBean--" + reqBean);
		Log.d(TConfig.Echo, "--reqBean--" + reqBean);

//		[type=1, order=Prot10051InvoiceBean [truck_no=null, driver_name=null, driver_phone=null, order_no=54545, starting_station=0, terminal_station=24, timestamp=2016-08-16 02:42, opt=-1, vid=[1000020993487124], label_id=[1000020993522746], carriage_no=P1551545]]
		// [type=1, order=Prot10051InvoiceBean [truck_no=null, driver_name=null, driver_phone=null, order_no=1112, starting_station=0, terminal_station=23, timestamp=2016-08-16 02:29, opt=-1, vid=[1002183451943842], label_id=[1002183445163549, 1002183451934284], carriage_no=P1111144]]
		return reqBean;
	}

	private List<String> getLabelList(TrainInvoiceBean trainInvoice) {
		List<InvoiceBean> Labels = invoiceBll.queryTrainLabelInvoices(trainInvoice);
		List<String> labelStrs = new ArrayList<String>();
		for (InvoiceBean invoice : Labels) {
			labelStrs.add(invoice.getLabelid());
		}
		
		return labelStrs;
	}

	private List<String> getViaList(TrainInvoiceBean trainInvoice) {
		List<InvoiceBean> trays = invoiceBll.queryTrainTrayInvoices(trainInvoice);
		List<String> vias = new ArrayList<String>();
		for (InvoiceBean invoice : trays) {
			vias.add(invoice.getLabelid());
		}
		
		return vias;
	}

}
