package cn.net.caoyao.cpzshandset.service.presenter.impl.exchange.sheepEx;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import cilico.tools.barcode.PhoneScanner;
import cn.net.caoyao.cpzshandset.R;
import cn.net.caoyao.cpzshandset.bean.ConfigBean;
import cn.net.caoyao.cpzshandset.bean.ExchangeCargoBean;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.config.HandsetOperation;
import cn.net.caoyao.cpzshandset.common.config.HandsetVersionConstant;
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.common.util.NetWorkUtils;
import cn.net.caoyao.cpzshandset.common.util.StringUtils;
import cn.net.caoyao.cpzshandset.service.bll.BatchLabelBll;
import cn.net.caoyao.cpzshandset.service.bll.SheepDealerBll;
import cn.net.caoyao.cpzshandset.service.bll.ExchangeCargoBll;
import cn.net.caoyao.cpzshandset.service.bll.config.ConfigBll;
import cn.net.caoyao.cpzshandset.service.presenter.BatchLabelScannerConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.BatchLabelScannerConstactImpl;
import cn.net.caoyao.cpzshandset.service.thread.ThreadPoolManager;
import cn.net.caoyao.cpzshandset.service.thread.ThreadReqTools;
import cn.net.caoyao.cpzshandset.service.thread.impl.sheepEx.SheepExSubmitCargo;
import cn.net.caoyao.cpzshandset.ui.dialog.TipsDialog;
import cn.net.caoyao.cpzshandset.ui.weight.DialogUtils;
import cn.net.cpzslibs.prot.handset.bean.req.Prot20002ReqBatchBean;
import cn.net.cpzslibs.prot.handset.bean.res.DealerBean;
import cn.net.handsetlib.utils.ReadDeviceIDUtil;

public class SheepExCargoBatchLSPresenter extends BatchLabelScannerConstactImpl {

	private final BatchLabelScannerConstact.View bView;
	private Context context;
	private int currentScannerType = 0;
	private final int START_LABEL = 1;
	private final int END_LABEL = 2;
	private ExchangeCargoBean currentCargo;
	private BatchLabelBll batchLabelBll;
	private SheepDealerBll dealerBll;
	private ExchangeCargoBll cagroBll;
	private ConfigBll configBll;
	private int option_id;
	private int currentHansetVersion = HandsetVersionConstant.HANDSET_SHEEP_EXCHANGE_CARGO;
	private int option_type = HandsetOperation.OPERATION_EXCHANGE_CARGO_CONSTANT.getOption();
	private TextView tv_scanner_text_identify1, tv_scanner_text_identify2, tv_scanner_text_identify3,
			tv_scanner_text_identify4;
	private TipsDialog tipsDialog;
	private TextWatcher startTW, endTW;
	private Prot20002ReqBatchBean currentBatchBean;
	private Prot20002ReqBatchBean uploadBean;
	private ProgressDialog bProgressDialog = null;
	// private boolean isCreate = true;//是创建还是修改
	private boolean hasUpload = false;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case PhoneScanner.BARCODE_READ:
			case PhoneScanner.BARCODE_ERR_LABEL: // 成功
				scannerRecuess(msg.obj.toString());
				break;
			case PhoneScanner.BARCODE_NOREAD:
				// 数据扫描失败
				if (checkViewAvailable()) {
					bView.showMsgToast("取消扫描", Toast.LENGTH_SHORT);
				}
				break;
			case RequestConstant.REQUEST_FAIL:
				// 请求失败
				if (!checkViewAvailable())
					return;
				dismissProgress();
				bView.showMsgToast("请求失败！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT:
				// 超时
				if (!checkViewAvailable())
					return;
				dismissProgress();
				bView.showMsgToast("请求超时！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_PROT01_LOGIN_FAIL:
				// 登录失败
				if (!checkViewAvailable())
					return;
				dismissProgress();
				String errorMsg = msg.obj.toString();
				int errorCode = msg.arg1;
				bView.showMsgToast(errorMsg + errorCode, Toast.LENGTH_SHORT);
				break;
			case RequestConstant.PROT_SUBMIT_EXCHANGE_CARGO_20029_FAIL:
				if (!checkViewAvailable())return;
				dismissProgress();
				bView.showMsgToast("提交调货信息失败", Toast.LENGTH_SHORT);
//				ProtStatusResBean resBean = (ProtStatusResBean) msg.obj;
				currentCargo = cagroBll.queryExchangeCargoById(currentCargo.getId());
				setLabelStatusData();
				break;
			case RequestConstant.PROT_SUBMIT_EXCHANGE_CARGO_20029_SUCCESS:
				if (!checkViewAvailable())return;
				dismissProgress();
				bView.showMsgToast("提交调货信息成功", Toast.LENGTH_SHORT);
				bView.finishPage();
				break;
			}

		}

	};

	private void scannerRecuess(String str) {
		if (!checkViewAvailable())
			return;
		LogUtil.d(TConfig.Echo, "scannerRecuess：" + str);
		bView.vibrate(100);
		if (StringUtils.isEmpty(str)) {
			bView.showMsgToast("扫描标签不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		if (!StringUtils.isNumber(str)) {
			bView.showMsgToast("不是数字，您所扫描的不是中国追溯的合法标签！", Toast.LENGTH_SHORT);
			return;
		}
		if (!(str.length() == 16 )) {
			bView.showMsgToast("您所扫描的不是中国追溯的合法标签！" + str.length(), Toast.LENGTH_SHORT);
			return;
		}

		if (currentScannerType == START_LABEL) {
			bView.removeStratTextChangedListener(startTW);
			bView.setStartLabel(str);
			checkLabelStatus();
			bView.addStartTextChangedListener(startTW);
		} else if (currentScannerType == END_LABEL) {
			bView.removeEndTextChangedListener(endTW);
			bView.setEndLabel(str);
			checkLabelStatus();
			bView.addEndTextChangedListener(endTW);
		}

	}

	private boolean checkLabelStatus() {
		String startLabel = bView.getStartLabel();
		String endLabel = bView.getEndLabel();
		if ((!StringUtils.isEmpty(startLabel)) && (!StringUtils.isEmpty(endLabel))) {
			if (!StringUtils.isNumber(startLabel) || !(startLabel.length() == 16 || startLabel.length() == 22)) {
				bView.showMsgToast("起始标签不是中国追溯的合法标签", Toast.LENGTH_SHORT);
				setBtnEnable(false);
				setLabelCountDataByInput(0);
				return false;
			}
			if (!StringUtils.isNumber(endLabel) || !(endLabel.length() == 16 || endLabel.length() == 22)) {
				bView.showMsgToast("结束标签不是中国追溯的合法标签", Toast.LENGTH_SHORT);
				setBtnEnable(false);
				setLabelCountDataByInput(0);
				return false;
			}

			long start = Long.parseLong(startLabel) / 10000;
			long end = Long.parseLong(endLabel) / 10000;
			int count = (int) (end - start) + 1;
			if (count <= 0) {
				setLabelCountDataByInput(0);
				bView.showMsgToast("结束标签不能小于起始标签", Toast.LENGTH_SHORT);
				setBtnEnable(false);
				return false;
			}
			if (count == currentCargo.getExchange_count()) {
				setBtnEnable(true);
				setLabelCountDataByInput(count);
				currentBatchBean.setStart(startLabel);
				currentBatchBean.setEnd(endLabel);
				return true;
			}  else {
				setLabelCountDataByInput(count);
				bView.showMsgToast("扫码数量必须与设置的实际数量相同", Toast.LENGTH_SHORT);
				setBtnEnable(false);
				return false;
			}

		} else {
			setLabelCountDataByInput(0);
			setBtnEnable(false);
			return false;
		}
	}

	private void setBtnEnable(boolean b) {
		bView.setBtnSaveEnable(b);
		bView.setBtnUploadEnable(b);
		
	}

	public SheepExCargoBatchLSPresenter(BatchLabelScannerConstact.View bView, Context context, Intent intent) {
		this.bView = bView;
		this.context = context;
		currentCargo = (ExchangeCargoBean) intent.getSerializableExtra("currentCargoBean");
		option_id = currentCargo.getId();
		start();
	}

	@Override
	public void start() {
		if (!checkViewAvailable())
			return;
		init();
		View customView = LayoutInflater.from(context).inflate(R.layout.scanner_custom_diaplay_layout, null);
		initCustomView(customView);
		bView.addCustomDisplayView(customView);
		bView.setPageTitle("批量调货");
		bView.setMoreOptionStr("上传");
		DealerBean fromDealer = dealerBll.queryDealerById(currentCargo.getFrom_dealer_id());
		DealerBean toDealer = dealerBll.queryDealerById(currentCargo.getTo_dealer_id());
		tv_scanner_text_identify1.setText("调货来源：" + fromDealer.getName());
		tv_scanner_text_identify2.setText("调到商家：" + toDealer.getName());
		currentBatchBean = batchLabelBll.queryBatchBeanById(option_type, option_id);
		if (currentBatchBean != null) {
			// isCreate = false;
			bView.setStartLabel(currentBatchBean.getStart());
			bView.setEndLabel(currentBatchBean.getEnd());
			long start = Long.parseLong(currentBatchBean.getStart()) / 10000;
			long end = Long.parseLong(currentBatchBean.getEnd()) / 10000;
			int count = (int) (end - start) + 1;
			if (count > 0) {
//				bView.setBtnSaveEnable(true);
				setBtnEnable(true);
			}
		} else {
			// isCreate = true;
			currentBatchBean = new Prot20002ReqBatchBean();
//			bView.setBtnSaveEnable(false);
			setBtnEnable(false);
		}

		setLabelCountDataBySql();
		setLabelStatusData();
		bView.addStartTextChangedListener(startTW);
		bView.addEndTextChangedListener(endTW);

	}

	private void setLabelCountDataBySql() {
		tv_scanner_text_identify3.setText("标签数量：" + batchLabelBll.queryBatchCountById(option_type, option_id));
	}

	private void setLabelCountDataByInput(int count) {
		tv_scanner_text_identify3.setText("标签数量：" + count);
	}

	private void setLabelStatusData() {
		if (currentCargo.getStatus() == Config.SUBMIT_STATUS_NOT_SUBMIT) {
			tv_scanner_text_identify4.setText("状态：未提交");
		} else {
			tv_scanner_text_identify4.setText("状态：提交失败  错误码：" + currentCargo.getError_code() + "\n原因：" + ThreadReqTools.getErrorMsg(currentCargo.getError_code()));
		}
	}

	private void init() {
		batchLabelBll = new BatchLabelBll(context);
		dealerBll = new SheepDealerBll(context);
		cagroBll = new ExchangeCargoBll(context);
		configBll = new ConfigBll(context);
		startTW = new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (!checkViewAvailable())
					return;
				checkLabelStatus();
			}
		};
		endTW = new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (!checkViewAvailable())
					return;
				checkLabelStatus();
			}
		};
	}

	private void initCustomView(View v) {
		tv_scanner_text_identify1 = (TextView) v.findViewById(R.id.tv_scanner_text_identify1);
		tv_scanner_text_identify2 = (TextView) v.findViewById(R.id.tv_scanner_text_identify2);
		tv_scanner_text_identify3 = (TextView) v.findViewById(R.id.tv_scanner_text_identify3);
		tv_scanner_text_identify4 = (TextView) v.findViewById(R.id.tv_scanner_text_identify4);
	}

	public void dismissProgress() {
		if (bProgressDialog != null) {
			try {
				DialogUtils.dismissProgressDialog(bProgressDialog);
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 提示正在更新数据
	 */
	protected void showProgressDialog(String titleStr, String tipsMsg) {
		bProgressDialog = DialogUtils.showProgressDialog(bProgressDialog, titleStr, tipsMsg, context);
	}

	@Override
	public boolean checkViewAvailable() {
		boolean b = false;
		if (bView != null && context != null) {
			b = true;
		}
		return b;
	}

	@Override
	public Handler getHandler() {
		return mHandler;
	}


	@Override
	public void btnStartLabelScannerClick() {
		if (!checkViewAvailable())
			return;
		currentScannerType = START_LABEL;
		bView.readQRCode();
	}

	@Override
	public void btnEndLabelScannerClick() {
		if (!checkViewAvailable())
			return;
		currentScannerType = END_LABEL;
		bView.readQRCode();
	}

	@Override
	public void uploadClick() {
		if (!checkViewAvailable())
			return;
		ConfigBean configBean = configBll
				.queryConfigByHandsetMode(currentHansetVersion);
		if (configBean == null) {
			bView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
			return;
		}
		if (!NetWorkUtils.isNetworkConnected(context)) {
			DialogUtils.showSetNetDialog(context);
			return;
		}
		
//		Prot20002ReqBatchBean reqBatchBean = batchLabelBll.queryBatchBeanById(option_type, option_id);
		/*if (reqBatchBean == null) {
			bView.showMsgToast("批量调货数据保存之后才能上传", duration);
		}*/
		
		if (!checkLabelStatus()) {
			return;
		}
		if (currentBatchBean != null && batchLabelBll != null) {

			if (batchLabelBll.hasExistBatchLabel(currentBatchBean.getStart(), currentBatchBean.getEnd(), option_type,
					option_id)) {
				bView.showMsgToast("该标签段中包含其他调货列表中未上传的标签，请修改后上传", Toast.LENGTH_SHORT);
			} else {

				showProgressDialog("提示", "正在提交调货信息，请稍后……");
				batchLabelBll.insertBatch(option_type, option_id, currentBatchBean);
				long deviceId = Long.parseLong(ReadDeviceIDUtil.readScanDecrypt(configBean.getDeviceId()));
//				ThreadPoolManager.getThreadPool().execute(new CommonSubmitSingleBatchActivateThread(mHandler, deviceId, activateBll, batchLabelBll, uploadStatusBll,currentActivateBean, currentBatchBean));
				ThreadPoolManager.getThreadPool().execute(new SheepExSubmitCargo(mHandler, deviceId, cagroBll, currentCargo, null, currentBatchBean));
			}

		}
	}

	@Override
	public void saveClick() {
		if (!checkViewAvailable())
			return;
		if (hasUpload && uploadBean != null) {
			if (currentBatchBean != null && uploadBean.getStart().equals(currentBatchBean.getStart()) && uploadBean.getEnd().equals(currentBatchBean.getEnd())) {
				bView.showMsgToast("保存成功", Toast.LENGTH_SHORT);
				bView.finishPage();
				return;
			}
		}
		
		
		if (currentBatchBean != null && batchLabelBll != null) {

			if (batchLabelBll.hasExistBatchLabel(currentBatchBean.getStart(), currentBatchBean.getEnd(), option_type,
					option_id)) {
				bView.showMsgToast("该标签段中包含其他调货列表中未上传的标签", Toast.LENGTH_SHORT);
			} else {
				batchLabelBll.insertBatch(option_type, option_id, currentBatchBean);
				cagroBll.updateExchangeCargoStatusById(0, 0, option_id);
				bView.showMsgToast("保存成功", Toast.LENGTH_SHORT);
				bView.finishPage();
			}

		}
	}

}
