package cn.net.caoyao.cpzshandset.service.presenter.impl.activate.commonfarmers;

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.ActivateBean;
import cn.net.caoyao.cpzshandset.bean.ConfigBean;
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.ActivateBll;
import cn.net.caoyao.cpzshandset.service.bll.ActivateWithPackBll;
import cn.net.caoyao.cpzshandset.service.bll.BatchLabelBll;
import cn.net.caoyao.cpzshandset.service.bll.ProductBll;
import cn.net.caoyao.cpzshandset.service.bll.UploadStatusBll;
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.commonfarmers.CommonFarmersSubmitSingleBatchActivateThread;
import cn.net.caoyao.cpzshandset.ui.dialog.TipsDialog;
import cn.net.caoyao.cpzshandset.ui.weight.DialogUtils;
import cn.net.cpzslibs.prot.bean.res.ProtStatusResBean;
import cn.net.cpzslibs.prot.handset.bean.Product;
import cn.net.cpzslibs.prot.handset.bean.req.Prot20002ReqBatchBean;
import cn.net.handsetlib.utils.ReadDeviceIDUtil;

public class CommonFarmersActivateBatchLSPresenter 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 ActivateBean currentActivateBean;
	private BatchLabelBll batchLabelBll;
	private ProductBll productBll;
	private ActivateBll activateBll;
	private ConfigBll configBll;
	private UploadStatusBll uploadStatusBll;
	private ActivateWithPackBll packBll;
	private int option_id;
	private int currentHansetVersion = HandsetVersionConstant.HANDSET_UNIVERSAL_VERSION_MODE_FARMERS;
	private int option_type = HandsetOperation.OPERATION_ACTIVATE_CONSTANT.getOption();
	private int other_option_type = HandsetOperation.OPERATION_ACTIVATE_WITH_PACK_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.SUBMIT_ACTIVATE_WITHOUT_RES:
				// 服务器没有返回值
				if (!checkViewAvailable())
					return;
				dismissProgress();
				bView.showMsgToast("抱歉，服务器没有反馈，请重试或者联系工作人员", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.SUBMIT_ACTIVATE_WITH_RES:
				// 服务器没有返回值
				if (!checkViewAvailable())
					return;
				dismissProgress();
				ProtStatusResBean resBean = (ProtStatusResBean) msg.obj;
				if (resBean.getResult() == 0) {
					bView.showMsgToast("上传数据成功！", Toast.LENGTH_SHORT);
					bView.finishPage();
				} else {
					hasUpload = true;
					String startLabel = bView.getStartLabel();
					String endLabel = bView.getEndLabel();
					uploadBean = new Prot20002ReqBatchBean();
					uploadBean.setStart(startLabel);
					uploadBean.setEnd(endLabel);
					currentActivateBean = activateBll.queryActivateBeanById(option_id);
					setLabelStatusData();
				}

				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 > 50000) {
				setLabelCountDataByInput(50000);
				bView.showMsgToast("批量激活数目不能超过五万条", Toast.LENGTH_SHORT);
				setBtnEnable(false);
				return false;
			} else if (count > 0 && count <= 50000) {
				setBtnEnable(true);
				setLabelCountDataByInput(count);
				currentBatchBean.setStart(startLabel);
				currentBatchBean.setEnd(endLabel);
				return true;
			} else {
				setLabelCountDataByInput(0);
				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 CommonFarmersActivateBatchLSPresenter(BatchLabelScannerConstact.View bView, Context context, Intent intent) {
		this.bView = bView;
		this.context = context;
		currentActivateBean = (ActivateBean) intent.getSerializableExtra("currentActivateBean");
		option_id = currentActivateBean.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("上传");
		Product p = productBll.queryProductById(currentActivateBean.getProduct_id());
		tv_scanner_text_identify1.setText("产品名称：" + p.getName());
		String pDate = StringUtils.isEmpty(currentActivateBean.getProduct_date()) ? "无"
				: currentActivateBean.getProduct_date();
		tv_scanner_text_identify2.setText("生产日期：" + pDate);
		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 (currentActivateBean.getStatus() == Config.SUBMIT_STATUS_NOT_SUBMIT) {
			tv_scanner_text_identify4.setText("状态：未提交");
		} else {
			tv_scanner_text_identify4.setText("状态：提交失败  错误码：" + currentActivateBean.getError_code() + "\n原因：" + ThreadReqTools.getErrorMsg(currentActivateBean.getError_code()));
		}
	}

	private void init() {
		batchLabelBll = new BatchLabelBll(context);
		productBll = new ProductBll(context);
		activateBll = new ActivateBll(context);
		configBll = new ConfigBll(context);
		uploadStatusBll = new UploadStatusBll(context);
		packBll = new ActivateWithPackBll(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 onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub

	}

	@Override
	public void backClick() {
		// TODO Auto-generated method stub

	}

	@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 (packBll.isExitPackageIdInAWithPack(currentBatchBean.getStart(), currentBatchBean.getEnd())) {
				bView.showMsgToast("该标签段中包含生产打包中的标签，请修改后上传", Toast.LENGTH_SHORT);
				return;
			}
			
			if (batchLabelBll.hasExistBatchLabel(currentBatchBean.getStart(), currentBatchBean.getEnd(), option_type,
					option_id)) {
//				bView.showMsgToast("该标签段中包含其他激活列表中未上传的标签，请修改后上传", Toast.LENGTH_SHORT);
				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 CommonFarmersSubmitSingleBatchActivateThread(mHandler, deviceId, activateBll, batchLabelBll, uploadStatusBll,currentActivateBean, 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 (packBll.isExitPackageIdInAWithPack(currentBatchBean.getStart(), currentBatchBean.getEnd())) {
				bView.showMsgToast("该标签段中包含生产打包中的标签，请修改后上传", Toast.LENGTH_SHORT);
				return;
			}
			if (batchLabelBll.hasExistBatchLabel(currentBatchBean.getStart(), currentBatchBean.getEnd(), option_type,
					option_id)) {
				bView.showMsgToast("该标签段中包含其他本地列表中未上传的标签", Toast.LENGTH_SHORT);
			} else {
				batchLabelBll.insertBatch(option_type, option_id, currentBatchBean);
				activateBll.updateActivateNotSubmitStatusById(option_id);
				bView.showMsgToast("保存成功", Toast.LENGTH_SHORT);
				bView.finishPage();
			}

		}
	}

}
