package cn.net.caoyao.cpzshandset.service.presenter.impl.returns.liqueurSFY;

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.ConfigBean;
import cn.net.caoyao.cpzshandset.bean.ReturnedGoodsBean;
import cn.net.caoyao.cpzshandset.bean.SingleLabelOptionBean;
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.AppUtils;
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.ReturnedGoodsBll;
import cn.net.caoyao.cpzshandset.service.bll.SingleLabelBll;
import cn.net.caoyao.cpzshandset.service.bll.UploadStatusBll;
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.ThreadPoolManager;
import cn.net.caoyao.cpzshandset.service.thread.ThreadReqTools;
import cn.net.caoyao.cpzshandset.service.thread.impl.counter.CounterSubmitSaleAndReturnedThread;
import cn.net.caoyao.cpzshandset.service.thread.impl.liqueurSFY.LiqueurSFYSubmitReturnedGoodsThread;
import cn.net.caoyao.cpzshandset.ui.adapter.SingleLabelAdapter;
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.bean.res.ProtStatusResBean;
import cn.net.cpzslibs.prot.handset.bean.req.SingleLabelWithOptBean;
import cn.net.handsetlib.utils.ReadDeviceIDUtil;

public class LiqueurSFYReturnsSingleLSPresenter extends SingleLabelScannerConstactImpl {

	private final SingleLabelScannerConstact.View sView;
	private Context context;
	private SingleLabelBll labelBll;
	private ConfigBll configBll;
	private UploadStatusBll uploadStatusBll;
	private ReturnedGoodsBll returnedGoodsBll;
	private SingleLabelAdapter adapter;
	private List<SingleLabelOptionBean> labels = new ArrayList<>();
	private int currentHansetVersion = HandsetVersionConstant.HANDSET_LIQUEUR_SFY_VERSION_MODE;
	private HandsetOperation option_type = HandsetOperation.OPERATION_RETURNED_GOODS_CONSTANT;
	private int option_id = -1;
	private TextView tv_scanner_text_identify5;
	private TipsDialog tipsDialog;
	private ProgressDialog bProgressDialog = null;
	private ConfigBean configBean;
	private List<SingleLabelWithOptBean> singles;
	private ReturnedGoodsBean currentReturnedBeans;
	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.PROT_SUBMIT_COUNTER_LABEL_20043_COMPLETE:
				// 服务器没有返回值
				if (!checkViewAvailable())
					return;
				dismissProgress();
				
				currentReturnedBeans = returnedGoodsBll.queryReturnedGoodsById(option_id);
				
				ProtStatusResBean resBean = (ProtStatusResBean) msg.obj;
				if (resBean.getResult() == 0) {
					sView.showMsgToast("上传数据成功！", Toast.LENGTH_SHORT);
					sView.finishPage();
				} else {
					labels = labelBll.queryAllLabelById(option_type.getOption(), option_id);
					adapter.refreshData(labels);
					setLabelStatusData();
				}

				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.length(), Toast.LENGTH_SHORT);
			return;
		}
		
		if (labelBll.hasExistSingleLabel(str, option_type.getOption())) {
			sView.showMsgToast("该标签已经存在于本地的未上传退货列表中！" + str.length(), Toast.LENGTH_SHORT);
			return;
		}

		labelBll.insertLabel(new SingleLabelOptionBean(str, option_type.getOption(), option_id));
		labels = labelBll.queryAllLabelById(option_type.getOption(), option_id);
		adapter.refreshData(labels);
	}

	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, final boolean isDel) {
		if (tipsDialog == null) {
			tipsDialog = new TipsDialog(context);
		}
		tipsDialog.show();
		tipsDialog.setDelWarnView("提示", tipContent, position, false, new DSure() {

			@Override
			public void sureClick() {
				if (isDel) {
					SingleLabelOptionBean b = labels.get(position);
					labelBll.deleteLabelByLabelId(b);
					labels = labelBll.queryAllLabelById(option_type.getOption(), option_id);
					if (labels.size() == 0) {
						returnedGoodsBll.updateReturnedGoodsSubmitStatus(Config.SUBMIT_STATUS_NOT_SUBMIT, 0, option_id);
						currentReturnedBeans = returnedGoodsBll.queryReturnedGoodsById(option_id);
						setLabelStatusData();
					}
					adapter.refreshData(labels);
				} else {
					showProgressDialog("提示", "正在提交信息，请稍后……");
					long deviceId = Long.parseLong(ReadDeviceIDUtil.readScanDecrypt(configBean.getDeviceId()));
//					ThreadPoolManager.getThreadPool().execute(new LiqueurSubmitSingleRelationActivateThread(mHandler, deviceId, activateBll,
//							labelBll, uploadStatusBll, currentActivate, labels));
					String imei = AppUtils.getIMEI(context);
					ThreadPoolManager.getThreadPool().execute(new CounterSubmitSaleAndReturnedThread(mHandler, deviceId, imei, labelBll, uploadStatusBll, singles));
				}
			}
		});
	}

	public LiqueurSFYReturnsSingleLSPresenter(SingleLabelScannerConstact.View sView, Context context, Intent intent) {
		super(sView, context);
		this.sView = sView;
		this.context = context;
		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.setMoreOptionStr("上传");
		sView.setPageTitle("退货");
		
		adapter = new SingleLabelAdapter(labels);
		sView.addHeadView(customView);
		sView.setAdapter(adapter);
//		labels = labelBll.queryAllLabelByOptionType(option_type.getOption());
		labels = labelBll.queryAllLabelById(option_type.getOption(), option_id);
		adapter.refreshData(labels);
		setLabelStatusData();
	}


	private void setLabelStatusData() {
		if (currentReturnedBeans.getStatus() == Config.SUBMIT_STATUS_SUBMIT_FAIL) {
			tv_scanner_text_identify5.setVisibility(View.VISIBLE);
			tv_scanner_text_identify5.setText("状态：提交失败  错误码：" + currentReturnedBeans.getError_code() + "\n原因："
						+ ThreadReqTools.getErrorMsg(currentReturnedBeans.getError_code()));
			
		} else {
			tv_scanner_text_identify5.setVisibility(View.GONE);
		}
	}

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

	private void init() {
		labelBll = new SingleLabelBll(context);
		configBll = new ConfigBll(context);
		uploadStatusBll = new UploadStatusBll(context);
		returnedGoodsBll = new ReturnedGoodsBll(context);
		option_id = returnedGoodsBll.insertReturnedGoodsByAccount();
		currentReturnedBeans = returnedGoodsBll.queryReturnedGoodsById(option_id);
		LogUtil.d(TConfig.Echo, "option_id:" + option_id);
	}

	@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 = configBll.queryConfigByHandsetMode(currentHansetVersion);
		if (configBean == null) {
			sView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
			return;
		}
		int count = labelBll.queryLabelCountById(option_type.getOption(), option_id);
		if (count <= 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 LiqueurSFYSubmitReturnedGoodsThread(mHandler, deviceId, returnedGoodsBll,
				labelBll, uploadStatusBll, option_id, ThreadReqTools.getLiqueurAccount()));
	}

	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) {
			SingleLabelOptionBean b = labels.get(position - 1);
			String tipsContent = "确认删除标签：\n" + b.getLabel_id();
			showDelTipsDialog(position - 1, tipsContent,true);
		}

	}

	@Override
	public void onItemLongClickListener(int position) {

	}

}
