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

import java.io.IOException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import android.os.Handler;
import android.os.Message;

import cn.net.caoyao.cpzshandset.bean.SaleBean;
import cn.net.caoyao.cpzshandset.bean.SingleLabelOptionBean;
import cn.net.caoyao.cpzshandset.bean.UploadBean;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.config.HandsetOperation;
import cn.net.caoyao.cpzshandset.common.config.InternalOptionConstant;
import cn.net.caoyao.cpzshandset.common.config.RequestConstant;
import cn.net.caoyao.cpzshandset.service.bll.BatchLabelBll;
import cn.net.caoyao.cpzshandset.service.bll.DealerOutBll;
import cn.net.caoyao.cpzshandset.service.bll.SingleLabelBll;
import cn.net.caoyao.cpzshandset.service.bll.UploadStatusBll;
import cn.net.cpzslibs.prot.Prot02Logout;
import cn.net.cpzslibs.prot.SocketCreate;
import cn.net.cpzslibs.prot.bean.res.ProtStatusResBean;
import cn.net.cpzslibs.prot.handset.bean.req.Prot20017ReqBean;
import cn.net.cpzslibs.prot.handset.bean.req.Prot20027ReqBean;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20017LabelBean;
import cn.net.cpzslibs.prot.handset.newProt.Prot20017CheckLabelStatus;
import cn.net.cpzslibs.prot.handset.newProt.Prot20076SubmitDealerOut;

public class CommonSubmitAllDealerOutThread implements Runnable {
	private long deviceId;
	private DealerOutBll bll;
	private SingleLabelBll labelBll;
	private BatchLabelBll batchBll;
	private UploadStatusBll uploadStatusBll;
	private List<SaleBean> aBeans;
	private Handler mHandler;
	private HandsetOperation option_type = HandsetOperation.OPERATION_DEALER_OUT_CONSTANT;

	public CommonSubmitAllDealerOutThread(Handler mHandler,long deviceId,DealerOutBll bll,SingleLabelBll labelBll,BatchLabelBll batchBll,UploadStatusBll uploadStatusBll,List<SaleBean> aBeans) {
		this.mHandler = mHandler;
		this.deviceId = deviceId;
		this.bll = bll;
		this.labelBll = labelBll;
		this.batchBll = batchBll;
		this.uploadStatusBll = uploadStatusBll;
		this.aBeans = aBeans;
	}

	@Override
	public void run() {
		SocketCreate create = new SocketCreate(Config.ip, Config.port, "");
		try {
//			LogUtil.d(TConfig.Echo, "登录");
			create.createLoginCpzsHandset(deviceId);
			if (create.isResult()) {
				submitActivateInfo(create);
			} else {
				Message msg = new Message();
				msg.what = RequestConstant.REQUEST_PROT01_LOGIN_FAIL;
				msg.arg1 = create.getiErrCode();
				msg.obj = create.getErrMsg();
				mHandler.sendMessage(msg);
			}
			
		} catch (BindException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
		} catch (ConnectException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
		} catch (IOException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
		}finally {
			new Prot02Logout().dealLogout(create);
		}
	}

	private void submitActivateInfo(SocketCreate create) throws IOException,SocketTimeoutException{
		for (SaleBean saleBean : aBeans) {
			if (saleBean.getOption_mode() == Config.SINGLE_OPTION_LABEL_TYPE) {
				//单标
				submitSingleDealerOutInfo(create,saleBean);
			} else if (saleBean.getOption_mode() == Config.BATCH_OPTION_LABEL_TYPE) {
				//批量
				submitBatchDealerInfo(create,saleBean);
			}
		}
		mHandler.sendEmptyMessage(RequestConstant.SUBMIT_ALL_ACTIVATE_COMPLETE);
	}
	private void submitBatchDealerInfo(SocketCreate create, SaleBean saleBean) throws IOException{
		int count = batchBll.queryBatchCountById(option_type.getOption(), saleBean.getId());
		if (count > 0) {
			Prot20076SubmitDealerOut activate = new Prot20076SubmitDealerOut();
			activate.submitDealerOut(create, getBatchReqBean(saleBean));
			ProtStatusResBean resBean = activate.getResBean();
			if (resBean == null) {
				return;
			}
			if (resBean.getResult() == 0) {
				//上传成功，插入记录到提交状态表
				uploadStatusBll.insertUploadStatus(getUploadBean(saleBean));
//				LogUtil.i(TConfig.Echo, "插入批量激活提交状态：" + getUploadBean(saleBean).toString());
				bll.deleteSalesById(saleBean);
//				bll.delActivateById(saleBean.getId());
//				batchBll.deleteBatchById(option_type, saleBean.getId());
			} else {
				bll.updateSalesSubmitStatus(Config.SUBMIT_STATUS_SUBMIT_FAIL, resBean.getErrcode(), saleBean.getId());
			}
			
		}
		
	}

	private UploadBean getUploadBean(SaleBean saleBean) {
		UploadBean b = new UploadBean();
		if (saleBean.getOption_mode() == Config.SINGLE_OPTION_LABEL_TYPE) {
			b.setLabel_count(labelBll.queryLabelCountById(option_type.getOption(), saleBean.getId()));
		} else {
			b.setLabel_count(batchBll.queryBatchCountById(option_type.getOption(), saleBean.getId()));
		}
		b.setOption_type(option_type.getOption());
		return b;
	}

	private Prot20027ReqBean getBatchReqBean(SaleBean saleBean) {
		Prot20027ReqBean reqBean = new Prot20027ReqBean();
		reqBean.setOpt(1);//1是出库 2是返库
		reqBean.setFlag(saleBean.getOption_mode());
		reqBean.setArea_id(saleBean.getSales_area());
		reqBean.setDealer_id((int)saleBean.getDealer_id());
		reqBean.setActual_num(saleBean.getPlan_num());
		reqBean.setRemark(saleBean.getDescribe());
		reqBean.setBatcher(batchBll.queryBatchBeanById(option_type.getOption(), saleBean.getId()));
		reqBean.setCreate_time(saleBean.getCreateDate());
		return reqBean;
	}
	private void submitSingleDealerOutInfo(SocketCreate create,SaleBean saleBean) throws IOException{
		int count = labelBll.queryLabelCountById(option_type.getOption(), saleBean.getId());
		if (count > 0) {
			Prot20076SubmitDealerOut activate = new Prot20076SubmitDealerOut();
			activate.submitDealerOut(create, getSingleReqBean(saleBean));
			ProtStatusResBean resBean = activate.getResBean();
			if (resBean == null) {
				return;
			}
			if (resBean.getResult() == 0) {
				uploadStatusBll.insertUploadStatus(getUploadBean(saleBean));
				bll.deleteSalesById(saleBean);
//				bll.delActivateById(saleBean.getId());
//				labelBll.deleteLabelById(option_type, saleBean.getId());
			} else {
//				bll.updateActivateErrorById(resBean.getErrcode(), saleBean.getId());
				checkLabel(create,saleBean);
				bll.updateSalesSubmitStatus(Config.SUBMIT_STATUS_SUBMIT_FAIL, resBean.getErrcode(), saleBean.getId());
			}
		}
		
	}

	private void checkLabel(SocketCreate create,SaleBean saleBean) throws IOException{
		Prot20017CheckLabelStatus prot20017 = new Prot20017CheckLabelStatus();
		prot20017.checkLabel(create, getProt20017ReqBean(saleBean));
		if (prot20017.getResBean() != null && prot20017.getResBean().getResult() == 0) {
			List<Prot20017LabelBean> invilad = prot20017.getResBean().getLabel_invalid();
			if (invilad != null) {
				List<String> inviladLabel = new ArrayList<>();
				for (Prot20017LabelBean prot20017LabelBean : invilad) {
					inviladLabel.add(prot20017LabelBean.getLabel_id());
				}
				labelBll.updateLableStatusById(inviladLabel, option_type.getOption(), saleBean.getId(), InternalOptionConstant.SINGLE_LABEL_STATUS_INVALID);
			}
			
			List<Prot20017LabelBean> repeat = prot20017.getResBean().getLabel_double_active();
			if (repeat != null) {
				List<String> repeatLabel = new ArrayList<>();
				for (Prot20017LabelBean prot20017LabelBean : repeat) {
					repeatLabel.add(prot20017LabelBean.getLabel_id());
				}
				labelBll.updateLableStatusById(repeatLabel, option_type.getOption(), saleBean.getId(), InternalOptionConstant.SINGLE_LABEL_STATUS_REPEAT_ACTIVATE);
			}
		}
		
	}

	private Prot20017ReqBean getProt20017ReqBean(SaleBean saleBean) {
		Prot20017ReqBean reqBean = new Prot20017ReqBean();
		reqBean.setLabels(getLabels(saleBean.getId()));
		reqBean.setOpt(getOptType());
		return reqBean;
	}
	//操作类型1-出库 2-入库 3-销售 4-返库 6-打包 8-激活
		private int getOptType() {
				int opt = 0;
				switch (option_type) {
				case OPERATION_ACTIVATE_CONSTANT:
					opt = 8;
					break;
				case OPERATION_DEALER_OUT_CONSTANT:
				case OPERATION_OUT_WAREHOUSE_CONSTANT:
					opt = 1;
					break;
				case OPERATION_IN_WAREHOUSE_CONSTANT:
					opt = 2;
					break;
				case OPERATION_SALE_CONSTANT:
					opt = 3;
					break;
				case OPERATION_BACK_WAREHOUSE_CONSTANT:
					opt = 4;
					break;
				case OPERATION_PACK_CONSTANT:
					opt = 6;
					break;
				}
				return opt;
			}
	private Prot20027ReqBean getSingleReqBean(SaleBean saleBean) {
		Prot20027ReqBean reqBean = new Prot20027ReqBean();
		reqBean.setOpt(1);//1是出库 2是返库
		reqBean.setFlag(saleBean.getOption_mode());
		reqBean.setArea_id(saleBean.getSales_area());
		reqBean.setDealer_id((int)saleBean.getDealer_id());
		reqBean.setActual_num(saleBean.getPlan_num());
		reqBean.setRemark(saleBean.getDescribe());
		reqBean.setSingle(getLabels(saleBean.getId()));
		reqBean.setCreate_time(saleBean.getCreateDate());
		return reqBean;
	}

	private List<String> getLabels(int id) {
		List<String> singles = new ArrayList<>();
		List<SingleLabelOptionBean> singleOptions = labelBll.queryAllLabelById(option_type.getOption(), id);
		for (SingleLabelOptionBean sLBean : singleOptions) {
			singles.add(sLBean.getLabel_id());
		}
		return singles;
	}


}
