package cn.net.caoyao.cpzshandset.service.presenter.impl.shipment.train;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.PopupWindow.OnDismissListener;
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.InvoiceBean;
import cn.net.caoyao.cpzshandset.bean.TrainInvoiceBean;
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.LabelHelper;
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.ConsigneeBll;
import cn.net.caoyao.cpzshandset.service.bll.InvoiceBll;
import cn.net.caoyao.cpzshandset.service.bll.TrainInvoiceBll;
import cn.net.caoyao.cpzshandset.service.bll.TrainStationBll;
import cn.net.caoyao.cpzshandset.service.bll.config.ConfigBll;
import cn.net.caoyao.cpzshandset.service.presenter.ShipmentScannerConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.ShipmentScannerConstactImpl;
import cn.net.caoyao.cpzshandset.service.thread.ThreadPoolManager;
import cn.net.caoyao.cpzshandset.service.thread.ThreadReqTools;
import cn.net.caoyao.cpzshandset.service.thread.impl.yth.CheckPackageIdRunable;
import cn.net.caoyao.cpzshandset.ui.adapter.ListTextAdapter;
import cn.net.caoyao.cpzshandset.ui.adapter.ListTextAdapter.IOnItemSelectListener;
import cn.net.caoyao.cpzshandset.ui.adapter.SpinnerTextPopWindow;
import cn.net.caoyao.cpzshandset.ui.adapter.TrayPresentAdapter;
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.ConsigneeBean;
import cn.net.cpzslibs.prot.handset.bean.req.Prot10061ReqBean;
import cn.net.cpzslibs.prot.handset.bean.res.Prot10061ResBean;
import cn.net.cpzslibs.prot.handset.bean.res.TrainStationBean;
import cn.net.handsetlib.utils.ReadDeviceIDUtil;

public class YthTrainShipmentScannerPresenter extends ShipmentScannerConstactImpl {
	private final ShipmentScannerConstact.View sView;
	private Context context;
	private final int OFFLINE_MODE = 1;
	private final int ONLINE_MODE = 2;
	private List<String> shipmentModes = new ArrayList<>();
	private Map<String, Integer> shipmentModeMap = new HashMap<>();
	private int currentShipment = OFFLINE_MODE;
	private SpinnerTextPopWindow mshipmentModesPopWindow;
	private ProgressDialog bProgressDialog = null;
	private TipsDialog tipsDialog;

	private InvoiceBll invoiceBll;
	private TrainInvoiceBll trainBll;
	private TrainStationBll stationBll;
	private ConsigneeBll consigneeBll;
	private ConfigBll configBll;
	private TrainInvoiceBean trainInvoice;

	private int bagPerTray = 40;// 每托盘的袋数
	private float weightPerBag = 0.04f;// 每袋的重量 40kg
	private boolean isTray = true;// 表示托盘包含信息,还没有单独标签的码
	DecimalFormat decimalFormat = new DecimalFormat("0.00");

	private int defaultFailCount = 5;// 默认不可用次数
	private int currentFailCount = 0;
	private TrayPresentAdapter adapter;
	private List<InvoiceBean> invoices = new ArrayList<InvoiceBean>();
	private int currentHansetVersion = HandsetVersionConstant.HANDSET_YTH_VERSION_MODE;
	
	Handler mHandler = new Handler() {
		public void handleMessage(android.os.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.PROT_CHECK_PACKAGEID_10061_SUCCESS:
				// 请求检测数据成功
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.setScannerBtnEnabled(true);

				Prot10061ResBean resBean = (Prot10061ResBean) msg.obj;
				parseResData(resBean);
				break;
			case RequestConstant.PROT_CHECK_PACKAGEID_10061_FAIL:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.setScannerBtnEnabled(true);
				showIKnowTipsDialog("请求时遇到异常情况");
				// showIKnowDialog("请求时遇到异常情况");
				break;
			case RequestConstant.REQUEST_PROT01_LOGIN_FAIL:
				// 登录失败
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.setScannerBtnEnabled(true);
				sView.showMsgToast("登录失败" + msg.obj.toString(), Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT:
				// 连接超时
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.setScannerBtnEnabled(true);

				if (!NetWorkUtils.isNetworkConnected(context)) {
					// showToast("当前设备无网络连接，请使用离线模式发货");
					LogUtil.d(TConfig.Echo, "无网络连接提示");
					showChoiceOffLineDialog();
				} else {
					// showToast("连接超时!可以尝试使用离线模式发货");
					sView.showMsgToast("连接超时!可以尝试使用离线模式发货", Toast.LENGTH_SHORT);
				}

				break;
			case RequestConstant.REQUEST_FAIL:
				// 请求失败
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.setScannerBtnEnabled(true);
				if (!NetWorkUtils.isNetworkConnected(context)) {
					// showToast("当前设备无网络连接，请使用离线模式发货");
					showChoiceOffLineDialog();
				} else {
					// showToast("连接超时!可以尝试使用离线模式发货");
					sView.showMsgToast("连接失败!可以尝试使用离线模式发货", Toast.LENGTH_SHORT);
				}

				break;
			}

		};
	};

	public YthTrainShipmentScannerPresenter(ShipmentScannerConstact.View sView, Context context, Intent intent) {
		this.sView = sView;
		this.context = context;
		init();
		int transId = intent.getIntExtra("transId", 0);
		trainInvoice = trainBll.queryTrainInvoiceById(transId);
		start();
	}

	private void init() {
		invoiceBll = new InvoiceBll(context);
		trainBll = new TrainInvoiceBll(context);
		stationBll = new TrainStationBll(context);
		configBll = new ConfigBll(context);
		consigneeBll = new ConsigneeBll(context);
	}

	@Override
	public void start() {
		if (!checkViewAvailable())
			return;
		setShipmentModeStr();
		initShipmetModeSpinner();
		initHeadView();
		invoices = invoiceBll.queryTrainInvoices(trainInvoice);
		adapter = new TrayPresentAdapter(context, invoices, trainInvoice.getId(), 1);
		sView.setAdapter(adapter);
		refreshBagCount();
		setLabelMode();
	}

	private void initHeadView() {
		View customeView = LayoutInflater.from(context).inflate(R.layout.scanner_custom_diaplay_layout, null);
		sView.addHeadView(customeView);
		TextView tv_scanner_text_identify1 = (TextView) customeView.findViewById(R.id.tv_scanner_text_identify1);
		tv_scanner_text_identify1.setText("车皮号：" + trainInvoice.getCarriageno());
		TextView tv_scanner_text_identify2 = (TextView) customeView.findViewById(R.id.tv_scanner_text_identify2);
		tv_scanner_text_identify2.setText("订单号：" + trainInvoice.getOrderno());
		TextView tv_scanner_text_identify3 = (TextView) customeView.findViewById(R.id.tv_scanner_text_identify3);
		String startStatiion = trainInvoice.getStartingstation() == 0?"水富" : "云峰";
		tv_scanner_text_identify3.setText("始发站："+startStatiion);
		
		
		TrainStationBean terminalStation = stationBll.queryStationById(trainInvoice.getTerminalstation());
		String endStation = (terminalStation == null ? "无" : terminalStation.getStation());
		TextView tv_scanner_text_identify4 = (TextView) customeView.findViewById(R.id.tv_scanner_text_identify4);
		tv_scanner_text_identify4.setText("到达站：" + endStation);
		
		TextView tv_scanner_text_identify5 = (TextView) customeView.findViewById(R.id.tv_scanner_text_identify5);
		ConsigneeBean consigneeBean = consigneeBll.queryConsigeeById(trainInvoice.getConsigneeId());
		String conguee = (consigneeBean == null ? "无" : consigneeBean.getConsignee());
		tv_scanner_text_identify5.setVisibility(View.VISIBLE);
		tv_scanner_text_identify5.setText("收货人：" +conguee);
		
	}

	public void scannerSuccess(String labelId) {
		if (!checkViewAvailable()) {
			return;
		}

		String numberLabel = LabelHelper.getLabelSplits(labelId);
		sView.vibrate(100);// 震动100ms
		if (StringUtils.isEmpty(numberLabel)) {
			sView.showMsgToast("扫描结果为空", Toast.LENGTH_SHORT);
			return;
		}
		// || numberLabel.length() == 22 目前必须是16位
		if (!(StringUtils.isNumber(numberLabel) && (numberLabel.length() == 16))) {
			sView.showMsgToast("扫描标签不合法", Toast.LENGTH_SHORT);
			return;
		}

		if (invoiceBll.hasExistLabel(numberLabel)) {
			sView.showMsgToast("标签库中已存在该标签", Toast.LENGTH_SHORT);
			return;
		}

		if (!invoiceBll.hasExistLabel(numberLabel)) {

			if (currentShipment == ONLINE_MODE) {
				checkedPackageId(numberLabel);
				return;
			}
			invoiceBll.insertInvoice(createInvoice(numberLabel, ""));
			refreshAdapter();
			refreshBagCount();
		} else {
			sView.showMsgToast("标签库中已存在该标签:" + numberLabel, Toast.LENGTH_SHORT);
		}

	}

	private void checkedPackageId(String numberLabel) {
		if (isTray) {
			// 托盘标签时，检测packageID 只有得到检测反馈结果后，扫码按钮可用时，才对该标签进行操作
			if (!NetWorkUtils.isNetworkConnected(context)) {
				showChoiceOffLineDialog();
				return;
			}
			// 在线模式时，检测PackageID的可用性
			sView.setScannerBtnEnabled(false);
			
			ConfigBean configBean = configBll.queryConfigByHandsetMode(currentHansetVersion);
			if (configBll == null) {
				sView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
				return;
			}
			long deviceId = Long.parseLong(ReadDeviceIDUtil.readScanDecrypt(configBean.getDeviceId()));
			ThreadPoolManager.getThreadPool().execute(new CheckPackageIdRunable(mHandler,
					deviceId, new Prot10061ReqBean(numberLabel)));
			showProgressDialog("提示", "正在检测该标签");

		} else {
			// 单个标签时，不检测packageID
			insertLabelToDB(numberLabel, null);
		}

	}

	private void setLabelMode() {
		int labelMode = trainInvoice.getLabelMode();

		if (labelMode == 1) {
			sView.changeAddIcon(R.drawable.scanner_label_addition);
		} else {
			sView.changeAddIcon(R.drawable.scanner_label_subtraction);
		}

	}

	private void parseResData(Prot10061ResBean resBean) {
		if (resBean.getResult() == 0) {
			// 请求成功的情况
			if (resBean.getFlag() == 0) {
				// packageID不为空
				if (!invoiceBll.hasExistPackageId(resBean.getPackage_id())) {
					currentFailCount = 0;
					insertLabelToDB(resBean.getLabel_id(), resBean.getPackage_id());
				} else {
					if (currentFailCount < defaultFailCount) {
						currentFailCount++;
						// 该托盘已经发货
						if (checkViewAvailable())
							showIKnowTipsDialog("标签库中已存在该标签所属托盘\n\n不能再作为托盘发货");// 标签库中已存在该标签所属托盘
					} else {
						currentFailCount = 0;
						insertLabelToDB(resBean.getLabel_id(), resBean.getPackage_id());
					}
				}

			} else {
				// packageID为空
				if (currentFailCount < defaultFailCount) {
					currentFailCount++;
					// showIKnowDialog("未找到该标签对应的包信息\n请重新更换个标签尝试");
					if (checkViewAvailable())
						showIKnowTipsDialog("未找到该标签对应的托盘信息\n\n请更换标签尝试");
				} else {
					currentFailCount = 0;
					insertLabelToDB(resBean.getLabel_id(), resBean.getPackage_id());
				}

			}
		} else {
			if (checkViewAvailable())
				showIKnowTipsDialog(ThreadReqTools.getErrorMsg(resBean.getErrcode()));

		}

	}

	private void refreshBagCount() {
		if (!checkViewAvailable())
			return;
		int trayCount = invoiceBll.queryTrainTrayCount(trainInvoice);
		int labelCountDB = invoiceBll.queryTrainLabelCount(trainInvoice);
		int labelCount = 0;
		if (trainInvoice.getLabelMode() == -1 && labelCountDB > 0) {
			labelCount = bagPerTray - labelCountDB;
		} else {
			labelCount = labelCountDB;
		}

		int bagCount = trayCount * bagPerTray + labelCount;
		String weightCount = decimalFormat.format(bagCount * weightPerBag);

		if (checkViewAvailable()) {
			sView.setPackageCount("预计总包数：" + bagCount + "袋");
			sView.setWeightCount("预计总吨数：" + weightCount + "吨");// 目前精确到小数点后两位
		}

		if (labelCount > 0) {
			isTray = false;
		}
		if (!isTray) {
			sView.changeLastTrayEnabled(false);
		}
	}

	private void insertLabelToDB(String numberLabel, String packageId) {
		invoiceBll.insertInvoice(createInvoice(numberLabel, packageId));
		refreshAdapter();
		refreshBagCount();
	}

	private void refreshAdapter() {
		invoices = invoiceBll.queryTrainInvoices(trainInvoice);
		if (checkViewAvailable() && adapter != null) {
			adapter.refreshData(invoices);
		}
	}

	/**
	 * 生成运单信息
	 * 
	 * @param labelId
	 * @return
	 */
	private InvoiceBean createInvoice(String labelId, String packageId) {
		InvoiceBean invoice = new InvoiceBean();
		invoice.setLabelid(labelId);
		if (!StringUtils.isEmpty(packageId)) {
			invoice.setPackage_id(packageId);
		}
		// invoice.setTimestamp(trainInvoice.getTimestamp());//暂时不需要
		invoice.setTransid(trainInvoice.getId());
		invoice.setTransmode(1);// 1:火车发货 2:汽车发货
		if (isTray) {
			invoice.setElemtype(1);// 1:托盘包含标签 2:单个产品标签
		} else {
			invoice.setElemtype(2);
		}
		return invoice;
	}

	/**
	 * 初始化选择发货模式的数据
	 */
	private void initShipmetModeSpinner() {
		shipmentModes.add("离线模式");
		shipmentModeMap.put("离线模式", OFFLINE_MODE);
		shipmentModes.add("在线模式");
		shipmentModeMap.put("在线模式", ONLINE_MODE);
		ListTextAdapter mAdapter = new ListTextAdapter(shipmentModes);
		mAdapter.refreshData(shipmentModes, 0);
		// 初始化PopWindow
		mshipmentModesPopWindow = new SpinnerTextPopWindow(context);
		mshipmentModesPopWindow.setAdatper(mAdapter);
		mshipmentModesPopWindow.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				if (!checkViewAvailable())
					return;
				sView.showAnimation(sView.getShipmentModeOptionView(), false);
			}
		});
		mshipmentModesPopWindow.setItemListener(new IOnItemSelectListener() {
			@Override
			public void onItemClick(int pos) {
				if (!checkViewAvailable())
					return;
				sView.setCurrentShipmentModeStr(shipmentModes.get(pos));
				currentShipment = shipmentModeMap.get(shipmentModes.get(pos));

			}
		});

	}

	/**
	 * 显示选择车皮号前字母的popWindow
	 */
	private void showShipmetModeSpinnerWindow() {
		mshipmentModesPopWindow.setWidth(sView.getShipmentModeGroupView().getWidth());
		mshipmentModesPopWindow.showAsDropDown(sView.getShipmentModeView());
	}

	private void setShipmentModeStr() {
		if (currentShipment == OFFLINE_MODE) {
			sView.setCurrentShipmentModeStr("离线模式");
		} else {
			sView.setCurrentShipmentModeStr("在线模式");
		}

	}

	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 (sView != null && context != null) {
			b = true;
		}
		return b;
	}

	@Override
	public Handler getHandler() {
		// TODO Auto-generated method stub
		return mHandler;
	}

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

	/**
	 * 显示选择无线模式的对话框
	 */
	public void showChoiceOffLineDialog() {
		String tipsContent = "当前设备无网络连接\n点击确定\n切换到离线模式发货";
		if (tipsDialog == null) {
			tipsDialog = new TipsDialog(context);
		}
		tipsDialog.show();
		tipsDialog.setTipsView(null, tipsContent, 0, false, new DSure() {

			@Override
			public void sureClick() {
				// 检测到无网络，点击确定，跳转到离线发货模式
				if (!checkViewAvailable())
					return;
				sView.setCurrentShipmentModeStr("离线模式");
				currentShipment = OFFLINE_MODE;
			}

		});

	}

	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() {
				// SingleLabelOptionBean b = labels.get(position);
				// labelBll.deleteLabelByLabelId(b);
				// labels = labelBll.queryAllLabelById(option_type, option_id);
				// if (labels.size() == 0) {
				// activateBll.updateActivateNotSubmitStatusById(option_id);
				// setLabelStatusData();
				// }
				// adapter.refreshData(labels);
				// setLabelCountData();
			}
		});
	}

	@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 onItemClickLinstener(int position) {
		if (!checkViewAvailable()) return;
		if (position > 0) {
			int pos = position - 1;
			if (invoices == null || invoices.size() == 0) {
				return;
			}
			if (isTray) {
				showTipsDialog("确定删除托盘码：\n" + invoices.get(pos).getLabelid(), pos, false);
			} else {
				if (invoices.get(pos).getElemtype() == 2) {
					// 表示当前是单个产品的标签
					showTipsDialog("确定删除标签：\n" + invoices.get(pos).getLabelid(), pos, false);
				}
			}
		}
	}
	
	public void showTipsDialog(final String tipsContent, final int position, boolean isIKonw) {
		if (tipsDialog == null) {
			tipsDialog = new TipsDialog(context);
		}
		tipsDialog.show();
		tipsDialog.setTipsView(null, tipsContent, position, isIKonw, new DSure() {

			@Override
			public void sureClick() {
				LogUtil.d(TConfig.Echo, "点击了删除界面的确认按钮：" + tipsContent + "   position:" + position);
				if (!checkViewAvailable()) return;
				invoiceBll.deleteInvoiceById(invoices.get(position));
				refreshAdapter();
				refreshBagCount();
			}
		});
	}

	@Override
	public void onItemLongClickListener(int position) {
		// TODO Auto-generated method stub

	}

	@Override
	public void changeShipmentModeClick() {
		if (!checkViewAvailable())
			return;
		sView.showAnimation(sView.getShipmentModeOptionView(), true);
		showShipmetModeSpinnerWindow();

	}

	@Override
	public void lastTrayClick() {
		if(!checkViewAvailable()) return;
		isTray = false;
		sView.changeLastTrayEnabled(false);
		

	}

	@Override
	public void addOrSubOptionClick() {
		if(!checkViewAvailable()) return;
		trainInvoice = trainBll.updateTrainLabelMode(trainInvoice);
		setLabelMode();
		refreshBagCount();
	}

}
