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

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.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.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.Prot20043ReqBean;
import cn.net.cpzslibs.prot.handset.bean.req.SingleLabelWithOptBean;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20017LabelBean;
import cn.net.cpzslibs.prot.handset.newProt.Prot20017CheckLabelStatus;
import cn.net.cpzslibs.prot.handset.newProt.Prot20043SubmitCounter;

public class CounterSubmitSaleAndReturnedThread implements Runnable {
	private long deviceId;
	private String imei;
	private SingleLabelBll labelBll;
	private UploadStatusBll uploadStatusBll;
	private List<SingleLabelWithOptBean> beans;
	private Handler mHandler;
	private HandsetOperation saleOption=HandsetOperation.OPERATION_COUNTER_SALE_CONSTANT;
	private HandsetOperation returnedOption=HandsetOperation.OPERATION_RETURNED_GOODS_CONSTANT;
	

	public CounterSubmitSaleAndReturnedThread(Handler mHandler,long deviceId,String imei,SingleLabelBll labelBll,UploadStatusBll uploadStatusBll,List<SingleLabelWithOptBean> beans) {
		this.mHandler = mHandler;
		this.deviceId = deviceId;
		this.imei = imei;
		this.labelBll = labelBll;
		this.uploadStatusBll = uploadStatusBll;
		this.beans = beans;
		LogUtil.e(TConfig.Echo, "提交的数据：" + beans.size() +"\n" + beans.toString());
	}

	@Override
	public void run() {
		SocketCreate create = new SocketCreate(Config.ip, Config.port, "");
		try {
//			LogUtil.d(TConfig.Echo, "登录");
			create.createLoginCpzsHandset(deviceId);
			if (create.isResult()) {
				submitCounterLabelInfo(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 submitCounterLabelInfo(SocketCreate create) throws IOException,SocketTimeoutException{
		Prot20043SubmitCounter submitCounter = new Prot20043SubmitCounter();
		submitCounter.submitCounterInfo(create, getProt20043ReqBean());
		ProtStatusResBean resBean = submitCounter.getResBean();
		if (resBean != null ) {
			uploadStatusBll.deleteErrorUploadStatusByOptionType(saleOption.getOption());
			uploadStatusBll.deleteErrorUploadStatusByOptionType(returnedOption.getOption());
			if (resBean.getResult() == 0) {
				uploadStatusBll.insertUploadStatus(getUploadBean(saleOption));
				uploadStatusBll.insertUploadStatus(getUploadBean(returnedOption));
				labelBll.deleteLabelByOptionType(saleOption.getOption());
				labelBll.deleteLabelByOptionType(returnedOption.getOption());
			} else {
				checkLabel(create);
				
				int sale_count = labelBll.queryLabelCountById(saleOption.getOption(), 0);
				if (sale_count > 0) {
					uploadStatusBll.insertErrorUploadStatus(saleOption.getOption(), resBean.getErrcode());
				}
				
				int return_count = labelBll.queryLabelCountById(returnedOption.getOption(), 0);
				if (return_count > 0) {
					uploadStatusBll.insertErrorUploadStatus(returnedOption.getOption(), resBean.getErrcode());
				}
			}
		}
		Message msg = mHandler.obtainMessage(RequestConstant.PROT_SUBMIT_COUNTER_LABEL_20043_COMPLETE);
		msg.obj = resBean;
		mHandler.sendMessage(msg);
	}
	private void checkLabel(SocketCreate create) throws IOException {
		Prot20017CheckLabelStatus prot20017 = new Prot20017CheckLabelStatus();
		prot20017.checkLabel(create, getProt20017ReqBean());
//		LogUtil.e(TConfig.Echo, "返回的标签检测信息：" + prot20017.getResBean().toString());
		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.updateLableStatusInSaleAndReturned(inviladLabel, InternalOptionConstant.SINGLE_LABEL_STATUS_INVALID);
			}
			
			List<Prot20017LabelBean> noActivate = prot20017.getResBean().getLabel_not_active();
			if (noActivate != null) {
				List<String> noActivateLabel = new ArrayList<>();
				for (Prot20017LabelBean prot20017LabelBean : noActivate) {
					noActivateLabel.add(prot20017LabelBean.getLabel_id());
				}
				labelBll.updateLableStatusInSaleAndReturned(noActivateLabel, InternalOptionConstant.SINGLE_LABEL_STATUS_NO_ACTIVATE);
			}
		}
		
	}

	private Prot20017ReqBean getProt20017ReqBean() {
		Prot20017ReqBean reqBean = new Prot20017ReqBean();
		List<String> labels = labelBll.queryAllLabelStrDistinctSaleAndReturned();
		reqBean.setLabels(labels);
		reqBean.setOpt(11);
//		LogUtil.e(TConfig.Echo, "提交的标签检测信息：" + reqBean.toString());
		return reqBean;
	}

	private Prot20043ReqBean getProt20043ReqBean() {
		Prot20043ReqBean reqBean = new Prot20043ReqBean();
		reqBean.setImei(imei);
		reqBean.setSingle(beans);
		return reqBean;
	}


	private UploadBean getUploadBean(HandsetOperation option_type) {
		UploadBean b = new UploadBean();
		int count = labelBll.queryLabelCountById(option_type.getOption(), 0);
		b.setLabel_count(count);
		b.setOption_type(option_type.getOption());
		return b;
	}

}
