package cn.net.caoyao.cpzshandset.service.presenter.impl.shipment.truck.ythScanner;

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

import com.google.gson.Gson;

import android.annotation.SuppressLint;
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.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.DriverInfoBean;
import cn.net.caoyao.cpzshandset.bean.HandsetParameterBean;
import cn.net.caoyao.cpzshandset.bean.InvoiceBean;
import cn.net.caoyao.cpzshandset.bean.ShipmentOnlineOrderBean;
import cn.net.caoyao.cpzshandset.common.config.Config;
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.PhoneParameterUtils;
import cn.net.caoyao.cpzshandset.common.util.StringUtils;
import cn.net.caoyao.cpzshandset.service.bll.CityBll;
import cn.net.caoyao.cpzshandset.service.bll.DriverInfoBll;
import cn.net.caoyao.cpzshandset.service.bll.InvoiceBll;
import cn.net.caoyao.cpzshandset.service.bll.OnlineTruckInvoiceBll;
import cn.net.caoyao.cpzshandset.service.bll.ShipmentUploadStatusBll;
import cn.net.caoyao.cpzshandset.service.bll.config.ConfigBll;
import cn.net.caoyao.cpzshandset.service.presenter.ShipmentSingleScannerConstact;
import cn.net.caoyao.cpzshandset.service.thread.ThreadPoolManager;
import cn.net.caoyao.cpzshandset.service.thread.ThreadReqTools;
import cn.net.caoyao.cpzshandset.service.thread.impl.ythScanner.YthScannerSubmitInvoiceRunable;
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.dialog.TipsDialog.IKnow;
import cn.net.caoyao.cpzshandset.ui.weight.DialogUtils;
import cn.net.cpzslibs.prot.bean.res.ProtStatusResBean;
import cn.net.cpzslibs.prot.handset.bean.req.Prot20025ReqBean;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20030ResBean;
import cn.net.cpzslibs.prot.handset.bean.res.ResponsibleUserInfoBean;
import cn.net.handsetlib.utils.ReadDeviceIDUtil;

@SuppressLint("ResourceAsColor")
public class YthScannerTruckShipmentScannerPresenter implements ShipmentSingleScannerConstact.Presenter {
	private TextView tv_scanner_text_identify6;
	private final ShipmentSingleScannerConstact.View sView;
	private Context context;
	private ProgressDialog bProgressDialog = null;
	private TipsDialog tipsDialog;

	private InvoiceBll invoiceBll;
//	private TruckInvoiceBll truckBll;
	private OnlineTruckInvoiceBll truckBll;
	private CityBll cityBll;
	private ConfigBll configBll;
	private DriverInfoBll driverInfoBll;
	private ShipmentUploadStatusBll uploadStatusBll;
	private int currentHansetVersion = HandsetVersionConstant.HANDSET_YTH_SCANNER_SHIPMENT_VERSION_MODE;
//	private YthOrderBean truckInvoice;
	private DriverInfoBean driverInfoBean;
	private int bagPerTray = 40;// 每托盘的袋数
	private float weightPerBag = 0.04f;// 每袋的重量 40kg
	DecimalFormat decimalFormat = new DecimalFormat("0.00");

	private TrayPresentAdapter adapter;
	private List<InvoiceBean> invoices = new ArrayList<InvoiceBean>();
//	private int submitLabelCount = 0;
	private Gson gson;
	private ResponsibleUserInfoBean uInfoBean;
	private ShipmentOnlineOrderBean orderBean;
	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_SUBMIT_INVOICE_10051_OVER_COUNT_FAIL:
				//超过该司机的计划量
				if (!checkViewAvailable())
					return;
				dismissProgress();
				driverInfoBean = driverInfoBll.queryDriverInfoById(driverInfoBean.getId());
				setOrderStatusData();
				Prot20030ResBean resBean2 = (Prot20030ResBean) msg.obj;
				String tipsContent2 = "上传订单失败" +
						"\n错误码：" + resBean2.getErrcode()+
						"\n原    因：" + ThreadReqTools.getErrorMsg(resBean2.getErrcode())+
						"\n超过数： " + resBean2.getCount() +" 个";
				showSubmitOrderSuccessTipsDialog(tipsContent2, false);
				break;
			case RequestConstant.PROT_SUBMIT_INVOICE_10051_REPEAT_FAIL:
				//重复发货
				if (!checkViewAvailable())
					return;
				dismissProgress();
				driverInfoBean = driverInfoBll.queryDriverInfoById(driverInfoBean.getId());
				invoices = invoiceBll.queryOnlineTruckInvoicesBylId(driverInfoBean.getId());
				adapter.refreshData(invoices);
				setOrderStatusData();
				Prot20030ResBean resBean1 = (Prot20030ResBean) msg.obj;
				String tipsContent1 = "上传订单失败" +
						"\n错误码：" + resBean1.getErrcode()+
						"\n原    因：" + ThreadReqTools.getErrorMsg(resBean1.getErrcode())+
						"\n重复数： " + resBean1.getCount() +" 个";
				showSubmitOrderSuccessTipsDialog(tipsContent1, false);
				break;
			case RequestConstant.PROT_SUBMIT_INVOICE_10051_FAIL:
				if (!checkViewAvailable())
					return;
				dismissProgress();
//				truckInvoice = truckBll.queryYthOrderById(truckInvoice.getId());
				driverInfoBean = driverInfoBll.queryDriverInfoById(driverInfoBean.getId());
				ProtStatusResBean resBean = (ProtStatusResBean) msg.obj;
				String tipsContent = "上传订单失败" +
						"\n错误码：" + resBean.getErrcode()+
						"\n原    因：" + ThreadReqTools.getErrorMsg(resBean.getErrcode());
						showSubmitOrderSuccessTipsDialog(tipsContent, false);
				break;
			case RequestConstant.PROT_SUBMIT_INVOICE_10051_SUCCESS:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				int labelCount = msg.arg1;

				String weightCount = decimalFormat.format(labelCount * weightPerBag);

				String tipsContent3 = "上传订单成功" +
				"\n本次上传总包数：" + labelCount +"袋"+
				"\n本次上传总吨数：" + weightCount +"吨";
				showSubmitOrderSuccessTipsDialog(tipsContent3,true);
				break;
			case RequestConstant.REQUEST_PROT01_LOGIN_FAIL:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.showMsgToast("登录失败！" + "\n错误码：" + msg.arg1 + "\n原因：" + ThreadReqTools.getErrorMsg(msg.arg1),
						Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.showMsgToast("连接超时", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_FAIL:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.showMsgToast("请求失败!", Toast.LENGTH_SHORT);
				break; 
			}

		};
	};

	public YthScannerTruckShipmentScannerPresenter(ShipmentSingleScannerConstact.View sView, Context context, Intent intent) {
		this.sView = sView;
		this.context = context;
		init();
		long transId = intent.getLongExtra("transId", 0);
		uInfoBean = (ResponsibleUserInfoBean) intent.getSerializableExtra("userInfo");
		driverInfoBean = driverInfoBll.queryDriverInfoById(transId);
		
		start();
	}

	private void init() {
		invoiceBll = new InvoiceBll(context);
		truckBll = new OnlineTruckInvoiceBll(context);
		cityBll = new CityBll(context);
		configBll = new ConfigBll(context);
		driverInfoBll = new DriverInfoBll(context);
		uploadStatusBll = new ShipmentUploadStatusBll(context);
	}

	@Override
	public void start() {
		if (!checkViewAvailable())
			return;
		initHeadView();
		sView.setPageTitle("汽车发运");
		sView.setMoreOptionBtnVisibility(View.VISIBLE);
		sView.setMoreOptionStr("上传");
		sView.setRealBagCountVisibility(View.VISIBLE);
//		invoices = invoiceBll.queryTruckInvoicesBylId(truckInvoice);
		invoices = invoiceBll.queryOnlineTruckInvoicesBylId(driverInfoBean.getId());
		adapter = new TrayPresentAdapter(context, invoices, driverInfoBean.getId());
		sView.setAdapter(adapter);
		refreshBagCount();
		
		sView.setRealPackageCount("预计总包数：" + driverInfoBean.getPack_num() + "袋");
		sView.setRealWeightCount("预计总吨数：" + driverInfoBean.getNum() + "吨");
		sView.setScannerPackageCountColor(R.color.tv_yth_real_count_text_color);
		sView.setScannerWeightCountColor(R.color.tv_yth_real_count_text_color);
	}

	private void initHeadView() {
		View customeView = LayoutInflater.from(context).inflate(R.layout.scanner_custom_diaplay_layout, null);
		sView.addHeadView(customeView);
		orderBean = truckBll.queryYthOrderById(driverInfoBean.getOrder_id());
		TextView tv_scanner_text_identify1 = (TextView) customeView.findViewById(R.id.tv_scanner_text_identify1);
		String orderNo = (orderBean == null ? "无":orderBean.getOrderId());
		tv_scanner_text_identify1.setText("订  单  号："+orderNo);
		TextView tv_scanner_text_identify2 = (TextView) customeView.findViewById(R.id.tv_scanner_text_identify2);
		tv_scanner_text_identify2.setText("车  牌  号：" + driverInfoBean.getCar_no());
		TextView tv_scanner_text_identify3 = (TextView) customeView.findViewById(R.id.tv_scanner_text_identify3);
		
		tv_scanner_text_identify3.setText("司机名称：" + driverInfoBean.getDriver_name());
		String pName = (orderBean == null ? "无":orderBean.getProductName());
		TextView tv_scanner_text_identify4 = (TextView) customeView.findViewById(R.id.tv_scanner_text_identify4);
		tv_scanner_text_identify4.setText("产品名称：" +pName);
		
		tv_scanner_text_identify6 = (TextView) customeView.findViewById(R.id.tv_scanner_text_identify6);
		tv_scanner_text_identify6.setVisibility(View.VISIBLE);
		setOrderStatusData();
	}
	
	private void setOrderStatusData() {
		if (driverInfoBean.getNative_status() == Config.SUBMIT_STATUS_NOT_SUBMIT) {
			tv_scanner_text_identify6.setText("状态：未提交");
		} else {
			tv_scanner_text_identify6.setText("状态：提交失败  错误码：" + driverInfoBean.getError_code() +"\n原因："+ ThreadReqTools.getErrorMsg(driverInfoBean.getError_code()) );
		}
	}

	
	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 (currentShipment == ONLINE_MODE) {
				checkedPackageId(numberLabel);
				return;
			}*/
//			int labelCount = invoiceBll.queryTruckLabelCountByLId(truckInvoice);
			int labelCount = invoiceBll.queryOnlineTruckLabelCountByLId(driverInfoBean.getId());
//			LogUtil.e(TConfig.Echo, "labelCount:" + labelCount);
			if (labelCount >= 2000) {
				sView.showMsgToast("同一个运单中标签数不能超过两千，请创建新订单扫码^_^", Toast.LENGTH_SHORT);
				return;
			}
			
			invoiceBll.insertInvoice(createInvoice(numberLabel, ""));
			refreshAdapter();
			refreshBagCount();

	}
	public void showSubmitOrderSuccessTipsDialog(final String tipsContent, final boolean isSuccess) {
		if (tipsDialog == null) {
			tipsDialog = new TipsDialog(context);
		}
		tipsDialog.show();
		tipsDialog.setTipsView(null, tipsContent, 0, true, new IKnow() {

			@Override
			public void iKnow() {
				if (!checkViewAvailable()) return;
				LogUtil.e(TConfig.Echo, "上传成功：" + isSuccess);
				if (isSuccess) {
					sView.finishPage();
				}
				
			}
		});
	}

	private void refreshBagCount() {
		if (!checkViewAvailable())
			return;
		
//		int labelCount = invoiceBll.queryTruckLabelCountByLId(truckInvoice);
		int labelCount = invoiceBll.queryOnlineTruckLabelCountByLId(driverInfoBean.getId());
		String weightCount = decimalFormat.format(labelCount * weightPerBag);

		if (checkViewAvailable()) {
			sView.setPackageCount("当前扫码包数：" + labelCount + "袋");
			sView.setWeightCount("当前扫码吨数：" + weightCount + "吨");// 目前精确到小数点后两位
		}

	}


	private void refreshAdapter() {
//		invoices = invoiceBll.queryTruckInvoicesBylId(truckInvoice);
		invoices = invoiceBll.queryOnlineTruckInvoicesBylId(driverInfoBean.getId());
		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.setTransOnlineId(driverInfoBean.getId());
		invoice.setTransmode(3);// 1:火车发货 2:汽车发货
		/*if (isTray) {
			invoice.setElemtype(1);// 1:托盘包含标签 2:单个产品标签
		} else {
			invoice.setElemtype(2);
		}*/
		invoice.setElemtype(2);
		return invoice;
	}


	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;
	}

	@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;
			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));
//				invoices = invoiceBll.queryTruckInvoicesBylId(truckInvoice);
				invoices = invoiceBll.queryOnlineTruckInvoicesBylId(driverInfoBean.getId());
				refreshAdapter();
				refreshBagCount();
			}
		});
	}

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

	}

	@Override
	public void moreOptionClick() {
		if (!checkViewAvailable())
			return;
		ConfigBean configBean = configBll.queryConfigByHandsetMode(currentHansetVersion);
		if (configBean == null) {
			sView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
			return;
		}
//		int submitLabelCount = invoiceBll.queryTruckLabelCountByLId(truckInvoice);
		int submitLabelCount = invoiceBll.queryOnlineTruckLabelCountByLId(driverInfoBean.getId());
		if (submitLabelCount <= 0) {
			sView.showMsgToast("当前订单还未扫描任何数据，不可上传", Toast.LENGTH_SHORT);
			return;
		}
		showProgressDialog("提示", "正在上传发货信息，请稍后……");
		long deviceId = Long.parseLong(ReadDeviceIDUtil.readScanDecrypt(configBean.getDeviceId()));
		String account = (uInfoBean != null ? uInfoBean.getAccount():"");
		 ThreadPoolManager.getThreadPool().execute(new
		 YthScannerSubmitInvoiceRunable(mHandler, account,deviceId, driverInfoBean,driverInfoBll,
		 invoiceBll,getProt20025Bean(),orderBean,uploadStatusBll));
		
	}
	private Prot20025ReqBean getProt20025Bean() {
		HandsetParameterBean parameterBean = PhoneParameterUtils.getHandsetParameter(context);
		Prot20025ReqBean reqBean = new Prot20025ReqBean();
		reqBean.setImei(parameterBean.getImei());
		reqBean.setHandset_parameter(getGson().toJson(parameterBean));
		return reqBean;
	}

	private Gson getGson() {
		if (gson == null) {
			gson = new Gson();
		} 
		return gson;
	}


}
