package cn.net.caoyao.cpzshandset.service.presenter.impl.activateWithPack.commonFarmers;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
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.bean.PackPackageInfoBean;
import cn.net.caoyao.cpzshandset.bean.PackSubLabelInfoBean;
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.PackPackageBll;
import cn.net.caoyao.cpzshandset.service.bll.PackSubLabelBll;
import cn.net.caoyao.cpzshandset.service.bll.ProductBll;
import cn.net.caoyao.cpzshandset.service.bll.config.ConfigBll;
import cn.net.caoyao.cpzshandset.service.presenter.SingleLabelScannerConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.SingleLabelScannerConstactImpl;
import cn.net.caoyao.cpzshandset.service.thread.ThreadReqTools;
import cn.net.caoyao.cpzshandset.ui.adapter.PackSubLabelAdapter;
import cn.net.caoyao.cpzshandset.ui.dialog.TipsDialog;
import cn.net.caoyao.cpzshandset.ui.dialog.TipsDialog.DSure;
import cn.net.caoyao.cpzshandset.ui.weight.DialogUtils;
import cn.net.cpzslibs.prot.handset.bean.Product;
import cn.net.handsetlib.utils.ReadDeviceIDUtil;

public class CommonFarmersActivateWithPackSingleLSPresenter extends SingleLabelScannerConstactImpl {

	private final SingleLabelScannerConstact.View sView;
	private Context context;
	private int option_id;
	private ActivateBean currentActivate;
	private int current_package_id;
	private PackPackageInfoBean currentPackageBean;
	private int currentHansetVersion = HandsetVersionConstant.HANDSET_UNIVERSAL_VERSION_MODE_FARMERS;
	private HandsetOperation option_type = HandsetOperation.OPERATION_ACTIVATE_WITH_PACK_CONSTANT;
	private TextView tv_scanner_text_identify1, tv_scanner_text_identify2, tv_scanner_text_identify3,
			tv_scanner_text_identify4;
	private ProductBll productBll;
	private PackPackageBll packageBll;
	private PackSubLabelBll subLabelBll;
	private TipsDialog tipsDialog;
	private ProgressDialog bProgressDialog = null;
	private ConfigBll configBll;
	private PackSubLabelAdapter adapter;
	private List<PackSubLabelInfoBean> subLabels = new ArrayList<>();
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case PhoneScanner.BARCODE_READ:
			case PhoneScanner.BARCODE_ERR_LABEL: // 成功
				scannerSuccess(msg.obj.toString());
				break;
			case PhoneScanner.BARCODE_NOREAD:
				// 数据扫描失败
				if (checkViewAvailable()) {
					sView.showMsgToast("取消扫描", Toast.LENGTH_SHORT);
				}
				break;
			case RequestConstant.REQUEST_FAIL:
				// 请求失败
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.showMsgToast("请求失败！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT:
				// 超时
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.showMsgToast("请求超时！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_PROT01_LOGIN_FAIL:
				// 登录失败
				if (!checkViewAvailable())
					return;
				dismissProgress();
				String errorMsg = msg.obj.toString();
				int errorCode = msg.arg1;
				sView.showMsgToast(errorMsg + errorCode, Toast.LENGTH_SHORT);
				break;
			case RequestConstant.SUBMIT_ACTIVATE_WITHOUT_RES:
				// 服务器没有返回值
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.showMsgToast("抱歉，服务器没有反馈，请重试或者联系工作人员", Toast.LENGTH_SHORT);
				break;
			}

		}

	};

	@Override
	public void scannerSuccess(String str) {
		if (!checkViewAvailable())
			return;
		LogUtil.d(TConfig.Echo, "scannerRecuess：" + str);
//		sView.vibrate(100);
		super.scannerSuccess(str);
		if (StringUtils.isEmpty(str)) {
			sView.showMsgToast("扫描标签不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		if (!StringUtils.isNumber(str)) {
			sView.showMsgToast("您所扫描的不是中国追溯的合法标签！", Toast.LENGTH_SHORT);
			return;
		}
		if (!(str.length() == 16)) {
			sView.showMsgToast("您所扫描的不是中国追溯的合法标签！" + str, Toast.LENGTH_SHORT);
			return;
		}
		//9开头的，表示当前扫描的是包标签
		if (str.startsWith("9")) {
			if (packageBll.hasExisPackageInOtherActivate(str)) {
				String tips = "该标签已经存在于本地列表中，不能再作为本单的包标签使用！" + str;
				showIKnowTipsDialog(tips);
//				sView.showMsgToast("该标签已经存在于其他激活列表中，不能再作为本单的包标签使用！" + str.length(), Toast.LENGTH_SHORT);
				return;
			}
			if (packageBll.hasExisPackageInOtherPack(str, option_type.getOption(), option_id, HandsetOperation.OPERATION_PACK_CONSTANT.getOption())) {
				String tips = "该标签已经在其他打包中作为包标签使用，不能再作为本单的包标签使用！" + str;
				showIKnowTipsDialog(tips);
//				sView.showMsgToast("该标签已经存在于其他激活列表中，不能再作为本单的包标签使用！" + str.length(), Toast.LENGTH_SHORT);
				return;
			}
			
			current_package_id = packageBll.insertPackPackage(getPackageBean(str));
			refreshPackPackageInfo();
			return;
		}
		//当前扫码的是子标签
		if (currentPackageBean == null) {
			sView.showMsgToast("请先扫描包标签", Toast.LENGTH_SHORT);
			return;
		}
		if (currentPackageBean.getCount() == currentActivate.getPackCount()) {
			//打包达到上限
			String tips = "抱歉，该包标签的子标签已达到上限";
			showIKnowTipsDialog(tips);
			return;
		}
		if (subLabelBll.hasExistActivateLabel(str)) {
			String tips = "抱歉，该标签已经存在于本地列表中，不能再存在于本单中";
			showIKnowTipsDialog(tips);
			return;
		}
		if (subLabelBll.hasExistSubPackLabel(str)) {
			String tips = "抱歉，该标签已经存在于其他打包数据中，不能再存在于本单中";
			showIKnowTipsDialog(tips);
			return;
		}
		subLabelBll.insertPackSubLabel(getSubLabelBean(str));
//		subLabels = subLabelBll.queryAllSubLabelByPackageId(current_package_id, option_id, option_type.getOption());
//		adapter.refreshData(subLabels);
//		packageBll.updatePackPackageCountById(current_package_id, subLabels.size());
		refreshPackPackageInfo();
	}

	private PackSubLabelInfoBean getSubLabelBean(String str) {
		PackSubLabelInfoBean subBean = new PackSubLabelInfoBean();
		subBean.setLabel_id(Long.parseLong(str));
		subBean.setPackage_id(current_package_id);
		subBean.setOption_id(option_id);
		subBean.setOption_type(option_type.getOption());
		return subBean;
	}

	private PackPackageInfoBean getPackageBean(String str) {
		PackPackageInfoBean pBean = new PackPackageInfoBean();
		pBean.setOption_id(option_id);
		pBean.setOption_type(option_type.getOption());
		pBean.setPackage_label_id(Long.parseLong(str));
		return pBean;
	}

	private void showIKnowTipsDialog(String tips) {
		if (tipsDialog == null) {
			tipsDialog = new TipsDialog(context);
		}
		tipsDialog.show();
		tipsDialog.setWarnView("提示", tips, true, null);
	}

	private void showDelTipsDialog(final int position, String tipContent) {
		if (tipsDialog == null) {
			tipsDialog = new TipsDialog(context);
		}
		tipsDialog.show();
		tipsDialog.setDelWarnView("提示", tipContent, position, false, new DSure() {

			@Override
			public void sureClick() {
				subLabelBll.deletePackLabelById(subLabels.get(position).getId());
				refreshPackPackageInfo();
			}
		});
	}

	public CommonFarmersActivateWithPackSingleLSPresenter(SingleLabelScannerConstact.View sView, Context context, Intent intent) {
		super(sView, context);
		this.sView = sView;
		this.context = context;
		currentActivate = (ActivateBean) intent.getSerializableExtra("currentActivate");
//		option_id = currentActivate.getId();
		option_id= intent.getIntExtra("option_id", 0);
		current_package_id = intent.getIntExtra("package_id", -1);
		
		start();
	}

	@Override
	public void start() {
		if (!checkViewAvailable())
			return;
		init();
		View customView = LayoutInflater.from(context).inflate(R.layout.scanner_custom_diaplay_layout, null);
		initCustomView(customView);
		sView.setMoreOptionBtnVisiable(View.GONE);
		sView.setPageTitle("生产打包");
		sView.addHeadView(customView);
		adapter = new PackSubLabelAdapter(subLabels);
		sView.setAdapter(adapter);
		refreshPackPackageInfo();
	}



	private void refreshPackPackageInfo() {
		currentPackageBean = packageBll.queryPackPackageById(current_package_id);
		if (currentPackageBean == null) {
			tv_scanner_text_identify2.setText("提交状态：无");
			tv_scanner_text_identify4.setText("包  标  签：");
		} else {
			if (currentPackageBean.getStatus() == Config.SUBMIT_STATUS_NOT_SUBMIT) {
				tv_scanner_text_identify2.setText("状态：未提交");
			} else {
				tv_scanner_text_identify2.setText("状态：提交失败  错误码：" + currentPackageBean.getError_code() +"\n原因："+ ThreadReqTools.getErrorMsg(currentPackageBean.getError_code()) );
			}
			String packageLabel = String.valueOf(currentPackageBean.getPackage_label_id());
			tv_scanner_text_identify4.setText("包  标  签：" + packageLabel.replaceAll("\\d{4}(?!$)", "$0  "));
		}
		subLabels = subLabelBll.queryAllSubLabelByPackageId(current_package_id, option_id, option_type.getOption());
		if (subLabels.size() == 0) {
			packageBll.updatePackPackageSubmitStatus(current_package_id, Config.SUBMIT_STATUS_NOT_SUBMIT, 0);
		}
		adapter.refreshData(subLabels);
		packageBll.updatePackPackageCountById(current_package_id, subLabels.size());
		currentPackageBean = packageBll.queryPackPackageById(current_package_id);
		tv_scanner_text_identify3.setText("打包数量："+subLabels.size()+" / " + currentActivate.getPackCount());
	}

	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);
		if (currentActivate == null) {
			tv_scanner_text_identify1.setText("产品名称：无" );
			return;
		}
		Product p = productBll.queryProductById(currentActivate.getProduct_id());
		if (p == null) {
			tv_scanner_text_identify1.setText("产品名称：无" );
			return;
		}
		tv_scanner_text_identify1.setText("产品名称：" + p.getName() );
	}

	private void init() {
//		uploadStatusBll = new UploadStatusBll(context);
		productBll = new ProductBll(context);
		packageBll = new PackPackageBll(context);
		subLabelBll = new PackSubLabelBll(context);
	}

	@Override
	public boolean checkViewAvailable() {
		boolean b = false;
		if (sView != 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 btnScannerClick() {
		if (!checkViewAvailable())
			return;
		sView.readQRCode();
	}

	@Override
	public void uploadClick() {
		if (!checkViewAvailable())
			return;
		ConfigBean configBean = configBll.queryConfigByHandsetMode(currentHansetVersion);
		if (configBean == null) {
			sView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
			return;
		}
//		if (labels.size() <= 0) {
//			sView.showMsgToast("当前的激活打包单还没有标签，不能上传", Toast.LENGTH_SHORT);
//			return;
//		}
		if (!NetWorkUtils.isNetworkConnected(context)) {
			DialogUtils.showSetNetDialog(context);
			return;
		}

		showProgressDialog("提示", "正在提交激活打包信息，请稍后……");
		long deviceId = Long.parseLong(ReadDeviceIDUtil.readScanDecrypt(configBean.getDeviceId()));
//		ThreadPoolManager.getThreadPool().execute(new CommonSubmitSingleActivateWithPackThread(mHandler, deviceId, activateBll,
//				labelBll, uploadStatusBll, currentActivate, labels));
	}

	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 void onItemClickLinstener(int position) {
		// int currentPos = labels.size() - position - 1;
		if (position > 0) {
			PackSubLabelInfoBean b = subLabels.get(position - 1);
			String tipsContent = "确认删除激活打包标签：\n" + b.getLabel_id();
			showDelTipsDialog(position - 1, tipsContent);
		}

	}

	@Override
	public void onItemLongClickListener(int position) {

	}

}

