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.ActivateBean;
import cn.net.caoyao.cpzshandset.bean.PackPackageInfoBean;
import cn.net.caoyao.cpzshandset.bean.PackSubLabelInfoBean;
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.common.config.TConfig;
import cn.net.caoyao.cpzshandset.common.util.LogUtil;
import cn.net.caoyao.cpzshandset.service.bll.PackPackageBll;
import cn.net.caoyao.cpzshandset.service.bll.PackSubLabelBll;
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.Prot20002ReqBean;
import cn.net.cpzslibs.prot.handset.bean.req.Prot20017ReqBean;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20017LabelBean;
import cn.net.cpzslibs.prot.handset.newProt.Prot20017CheckLabelStatus;
import cn.net.cpzslibs.prot.handset.newProt.Prot20040ActivateWithPack;

public class CommonSubmitSingleActivateWithPackThread implements Runnable {
	private long deviceId;
//	private ActivateWithPackBll bll;
	private PackSubLabelBll labelBll;
	private PackPackageBll packageBll;
	private UploadStatusBll uploadStatusBll;
	private ActivateBean activateBean;
	private int option_type = HandsetOperation.OPERATION_ACTIVATE_WITH_PACK_CONSTANT.getOption();
	private Handler mHandler;

	public CommonSubmitSingleActivateWithPackThread(Handler mHandler, long deviceId, PackPackageBll packageBll,PackSubLabelBll labelBll,
			UploadStatusBll uploadStatusBll, ActivateBean activateBean) {
		this.mHandler = mHandler;
		this.deviceId = deviceId;
//		this.bll = bll;
		this.uploadStatusBll = uploadStatusBll;
		this.activateBean = activateBean;
		this.labelBll = labelBll;
		this.packageBll = packageBll;
	}

	@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 {
		List<PackPackageInfoBean> pBeans = packageBll.queryAllPackPackageASC(activateBean.getId(), option_type);
		for (PackPackageInfoBean pB : pBeans) {
			List<PackSubLabelInfoBean> subLabels = labelBll.queryAllSubLabelByPackageId(pB.getId(), activateBean.getId(), option_type);
			if (subLabels != null && subLabels.size() > 0) {
				Prot20040ActivateWithPack activate = new Prot20040ActivateWithPack();
				activate.submitActivateInfo(create, getReqBean(pB,subLabels));
				ProtStatusResBean resBean = activate.getResBean();
				if (resBean == null) {
					continue;
				}
				

				if (resBean.getResult() == 0) {
					// 上传成功，插入记录到提交状态表
					uploadStatusBll.insertUploadStatus(getUploadBean(pB));
//					bll.delActivateById(activateBean);
//					bll.delActivatePackById(activateBean);
					packageBll.deletePackPackageById(pB.getId());
				} else {
//					bll.updateActivateErrorById(resBean.getErrcode(), activateBean.getId());
//					bll.updateActivatePackErrorStatusById(Config.SUBMIT_STATUS_SUBMIT_FAIL, resBean.getErrcode(), activateBean.getId());
					packageBll.updatePackPackageSubmitStatus(pB.getId(), Config.SUBMIT_STATUS_SUBMIT_FAIL, resBean.getErrcode());
					checkLabel(create,pB);
				}
				
			}
			
		}
		
		mHandler.sendEmptyMessage(RequestConstant.SUBMIT_ALL_ACTIVATE_COMPLETE);

	}
	
	private void checkLabel(SocketCreate create,PackPackageInfoBean pB) throws IOException{
		Prot20017CheckLabelStatus prot20017 = new Prot20017CheckLabelStatus();
		prot20017.checkLabel(create, getProt20017ReqBean(pB));
		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, activateBean.getId(), InternalOptionConstant.SINGLE_LABEL_STATUS_INVALID);
				labelBll.updateLabelListStatus(inviladLabel, pB.getId(), activateBean.getId(), option_type, 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.updateLabelListStatus(repeatLabel, pB.getId(), activateBean.getId(), option_type, InternalOptionConstant.SINGLE_LABEL_STATUS_REPEAT_ACTIVATE);
//				labelBll.updateLableStatusById(repeatLabel, option_type, activateBean.getId(), InternalOptionConstant.SINGLE_LABEL_STATUS_REPEAT_ACTIVATE);
			}
		}
		
	}

	private Prot20017ReqBean getProt20017ReqBean(PackPackageInfoBean pB) {
		Prot20017ReqBean reqBean = new Prot20017ReqBean();
		reqBean.setLabels(getLabelsByPackageId(pB));
		reqBean.setOpt(8);
		return reqBean;
	}


	private List<String> getLabelsByPackageId(PackPackageInfoBean pB) {
		return labelBll.queryAllSubLabelStrByPackageId(pB.getId(), activateBean.getId(), option_type);
	}

	private UploadBean getUploadBean(PackPackageInfoBean pB) {
		UploadBean b = new UploadBean();
//		b.setLabel_count(labelBll.queryLabelCountById(option_type, activateBean.getId()));
		b.setLabel_count(labelBll.queryLabelCountByPackageId(pB.getId()));
		b.setOption_type(option_type);
		return b;
	}

	private Prot20002ReqBean getReqBean(PackPackageInfoBean packageInfoBean,List<PackSubLabelInfoBean> labelInfoBeans) {
		Prot20002ReqBean reqBean = new Prot20002ReqBean();
		reqBean.setProduct_id(activateBean.getProduct_id());
		reqBean.setProduce_date(activateBean.getProduct_date());
		reqBean.setProduce_batch(activateBean.getProduct_batch_number());
//		reqBean.setTeam(String.valueOf(activateBean.getGroup_number_id()));
		reqBean.setProducer(activateBean.getProducer());
		reqBean.setType(Config.SINGLE_OPTION_LABEL_TYPE);
		reqBean.setSingle(getLabels(labelInfoBeans));
		reqBean.setPackage_id(String.valueOf(packageInfoBean.getPackage_label_id()));
		LogUtil.i(TConfig.Echo, "提交的数据：" + reqBean.toString());
		return reqBean;
	}

	private List<String> getLabels(List<PackSubLabelInfoBean> labelInfoBeans) {
		List<String> singles = new ArrayList<>();
		for (PackSubLabelInfoBean sLBean : labelInfoBeans) {
			singles.add(String.valueOf(sLBean.getLabel_id()));
		}
		return singles;
	}

}
