package cn.net.caoyao.cpzshandset.service.presenter.impl.checkLabelStatus.medicineXY;



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.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
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.common.config.HandsetVersionConstant;
import cn.net.caoyao.cpzshandset.common.config.RequestConstant;
import cn.net.caoyao.cpzshandset.common.util.NetWorkUtils;
import cn.net.caoyao.cpzshandset.common.util.StringUtils;
import cn.net.caoyao.cpzshandset.service.bll.config.ConfigBll;
import cn.net.caoyao.cpzshandset.service.presenter.CheckLabelStatusConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.CheckLabelStatusConstactImpl;
import cn.net.caoyao.cpzshandset.service.thread.ThreadPoolManager;
import cn.net.caoyao.cpzshandset.service.thread.impl.medicineXY.MedicineXYCheckLabelStatusThread;
import cn.net.caoyao.cpzshandset.ui.adapter.CheckLabelStatusListAdapter;
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.req.Prot20042ReqBean;
import cn.net.cpzslibs.prot.handset.bean.res.ProtCheckLabelStatusResBean;
import cn.net.handsetlib.utils.ReadDeviceIDUtil;

public class MedicineXYCheckLabelStatusPresenter extends CheckLabelStatusConstactImpl implements OnClickListener{
	private final CheckLabelStatusConstact.View cView;
	private Context context;
	private ProgressDialog bProgressDialog = null;
	private int currentHansetVersion = HandsetVersionConstant.HANDSET_MEDICINE_XY_VERSION_MODE;
	private ConfigBll configBll;
	private TextWatcher labelT;
	private List<ProtCheckLabelStatusResBean> labels = new ArrayList<>();
	private CheckLabelStatusListAdapter adapter;
	private EditText et_check_label_adapter,et_check_code_adapter;
	private TipsDialog tipsDialog;
	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()) {
					cView.showMsgToast("取消扫描", Toast.LENGTH_SHORT);
				}
				break;
			case RequestConstant.REQUEST_FAIL:
				// 请求失败
				if (!checkViewAvailable())
					return;
				dismissProgress();
//				cView.showMsgToast("请求失败！", Toast.LENGTH_SHORT);
				ProtCheckLabelStatusResBean labelResBean = new ProtCheckLabelStatusResBean();
				labelResBean.setType(1);
				labelResBean.setErrmsg("请求失败！");
				setLabelStatusResult(labelResBean);
//				setLabelStatusResult("请求失败！");
				break;
			case RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT:
				// 超时
				if (!checkViewAvailable())
					return;
				dismissProgress();
//				cView.showMsgToast("请求超时！", Toast.LENGTH_SHORT);
				ProtCheckLabelStatusResBean labelResBean1 = new ProtCheckLabelStatusResBean();
				labelResBean1.setType(1);
				labelResBean1.setErrmsg("请求超时！");
				setLabelStatusResult(labelResBean1);
				break;
			case RequestConstant.REQUEST_PROT01_LOGIN_FAIL:
				// 登录失败
				if (!checkViewAvailable())
					return;
				dismissProgress();
				String errorMsg = msg.obj.toString();
				int errorCode = msg.arg1;
//				cView.showMsgToast(errorMsg + errorCode, Toast.LENGTH_SHORT);
//				setLabelStatusResult(errorMsg + errorCode );
				ProtCheckLabelStatusResBean labelResBean2 = new ProtCheckLabelStatusResBean();
				labelResBean2.setType(1);
				labelResBean2.setErrmsg(errorMsg + errorCode );
				setLabelStatusResult(labelResBean2);
				break;
			case RequestConstant.PROT_CHECK_LABEL_SUCCESS:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				ProtCheckLabelStatusResBean resBean = (ProtCheckLabelStatusResBean) msg.obj;
				if (resBean == null) {
//					setLabelStatusResult("未解析到返回结果");
					ProtCheckLabelStatusResBean labelResBean3 = new ProtCheckLabelStatusResBean();
					labelResBean3.setType(1);
					labelResBean3.setErrmsg("未解析到返回结果");
					setLabelStatusResult(labelResBean3);
				}
				setLabelStatusResult(resBean);
//				if (resBean.getResult() == 0) {
//					setLabelStatusResult("标签和验证码均合法！");
//				} else {
//					String errorMsgTips = "验证不匹配 \n错误原因：" + ThreadReqTools.getErrorMsg(resBean.getErrcode()) +"\n错误码：" + resBean.getErrcode();
//					setLabelStatusResult(errorMsgTips);
//				}
				break;
			}

		}

	};

	public MedicineXYCheckLabelStatusPresenter(CheckLabelStatusConstact.View cView, Context context) {
		super(cView);
		this.cView = cView;
		this.context = context;
		start();
	}



	protected void setLabelStatusResult(ProtCheckLabelStatusResBean labelResBean) {
		labels.add(labelResBean);
		adapter.refreshData(labels);
	}


	@Override
	public void start() {
		if (!checkViewAvailable()) return;
		cView.setPageTitle("标签检测");
		configBll = new ConfigBll(context);
		labelT = 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;
				clearCheckCodeStr();
//				clearResultStr();
			}
		};
//		cView.addLabelTextChangedListener(labelT);
		adapter = new CheckLabelStatusListAdapter(labels);
		addCustomView();
		cView.setResultAdapter(adapter);
	}
	
	private void showWarnTipsDialog(String tipContent){
		if (tipsDialog == null) {
			tipsDialog = new TipsDialog(context);
		}
		tipsDialog.show();
		tipsDialog.setDelWarnView("提示", tipContent, 0, false, new DSure() {
			
			@Override
			public void sureClick() {
				if(!checkViewAvailable()) return;
				cView.finishPage();
			}
		});
	}
	
	private void addCustomView() {
		View checkView = LayoutInflater.from(context).inflate(R.layout.adapter_check_label_header, null);
		cView.addHeaderView(checkView);
		et_check_label_adapter = (EditText) checkView.findViewById(R.id.et_check_label_adapter);
		et_check_code_adapter = (EditText) checkView.findViewById(R.id.et_check_code_adapter);
		et_check_label_adapter.addTextChangedListener(labelT);
		View btn_check_label_scanner_adapter = checkView.findViewById(R.id.btn_check_label_scanner_adapter);
		btn_check_label_scanner_adapter.setOnClickListener(this);
		View btn_check_label_status_adapter = checkView.findViewById(R.id.btn_check_label_status_adapter);
		btn_check_label_status_adapter.setOnClickListener(this);
		
	}

	protected void clearCheckCodeStr() {
//		cView.setCheckCodeStr("");
		et_check_code_adapter.setText("");
	}

	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 (cView != 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() {
		if(!checkViewAvailable()) return;
		if (labels.size() == 0) {
			cView.finishPage();
			return;
		}
		String tipContent = "返回后，当前界面的数据将不再保存！是否确认返回？";
		showWarnTipsDialog(tipContent);
	}

	public void btnCheckClick() {
		ConfigBean configBean = configBll
				.queryConfigByHandsetMode(currentHansetVersion);
		if (configBean == null) {
			cView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
			return;
		}
		if (!NetWorkUtils.isNetworkConnected(context)) {
			DialogUtils.showSetNetDialog(context);
			return;
		}
//		String labelStr = cView.getLabelStr();
//		String checkCodeStr = cView.getCheckCodeStr();
		String labelStr = et_check_label_adapter.getText().toString().trim();
		String checkCodeStr = et_check_code_adapter.getText().toString().trim();
		if (!checkLabelStatus(labelStr,checkCodeStr)) {
			return;
		}
		showProgressDialog("提示", "正在请求信息，请稍后……");
		long deviceId = Long.parseLong(ReadDeviceIDUtil.readScanDecrypt(configBean.getDeviceId()));
		ThreadPoolManager.getThreadPool().execute(new MedicineXYCheckLabelStatusThread(mHandler, deviceId, new Prot20042ReqBean(labelStr, Integer.parseInt(checkCodeStr)),checkCodeStr));
	}

	private boolean checkLabelStatus(String labelStr, String checkCodeStr) {
		if (StringUtils.isEmpty(labelStr)) {
			cView.showMsgToast("标签不能为空", Toast.LENGTH_SHORT);
			return false;
		}
		if (labelStr.length() != 16|| (!StringUtils.isNumber(labelStr))) {
			cView.showMsgToast("您所扫描的不是中国追溯的合法标签", Toast.LENGTH_SHORT);
			return false;
		}
		if (StringUtils.isEmpty(checkCodeStr)) {
			cView.showMsgToast("验证码不能为空", Toast.LENGTH_SHORT);
			return false;
		}
		if (checkCodeStr.length() != 4) {
			cView.showMsgToast("请输入正确的四位验证码", Toast.LENGTH_SHORT);
			return false;
		}
		return true;
	}

	@Override
	public void scannerSuccess(String scannerContentStr) {
		super.scannerSuccess(scannerContentStr);
		
		et_check_label_adapter.removeTextChangedListener(labelT);
		et_check_label_adapter.setText(scannerContentStr);
		if (scannerContentStr.length() != 16|| (!StringUtils.isNumber(scannerContentStr))) {
			cView.showMsgToast("您所扫描的不是中国追溯的合法标签", Toast.LENGTH_SHORT);
		}
		clearCheckCodeStr();
		et_check_label_adapter.addTextChangedListener(labelT);
		
	}
	@Override
	public void onBackPressed() {
		if(!checkViewAvailable()) return;
		backClick();
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_check_label_status_adapter:
			if(!checkViewAvailable()) return;
			btnCheckClick();
			break;

		case R.id.btn_check_label_scanner_adapter:
			if(!checkViewAvailable()) return;
			cView.readQRCode();
			break;
		}
		
	}


}
