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

import java.text.DecimalFormat;
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.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.City;
import cn.net.caoyao.cpzshandset.bean.InvoiceBean;
import cn.net.caoyao.cpzshandset.bean.TruckInvoiceBean;
import cn.net.caoyao.cpzshandset.common.config.Config;
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.StringUtils;
import cn.net.caoyao.cpzshandset.service.bll.CityBll;
import cn.net.caoyao.cpzshandset.service.bll.InvoiceBll;
import cn.net.caoyao.cpzshandset.service.bll.TruckInvoiceBll;
import cn.net.caoyao.cpzshandset.service.presenter.ShipmentSingleScannerConstact;
import cn.net.caoyao.cpzshandset.service.tools.SaleAddressUtil;
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;

public class YthLoginTruckShipmentSingleScannerPresenter implements ShipmentSingleScannerConstact.Presenter {
	private final ShipmentSingleScannerConstact.View sView;
	private Context context;
	private ProgressDialog bProgressDialog = null;
	private TipsDialog tipsDialog;

	private InvoiceBll invoiceBll;
	private TruckInvoiceBll truckBll;
	private CityBll cityBll;
	private TruckInvoiceBean truckInvoice;

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

		};
	};

	public YthLoginTruckShipmentSingleScannerPresenter(ShipmentSingleScannerConstact.View sView, Context context, Intent intent) {
		this.sView = sView;
		this.context = context;
		init();
		int transId = intent.getIntExtra("transId", 0);
		truckInvoice = truckBll.queryTruckInvoiceById(transId);
//		LogUtil.e(TConfig.Echo, transId+"  truckInvoice:" + truckInvoice.toString());
		start();
	}

	private void init() {
		invoiceBll = new InvoiceBll(context);
		truckBll = new TruckInvoiceBll(context);
		cityBll = new CityBll(context);
	}

	@Override
	public void start() {
		if (!checkViewAvailable())
			return;
		initHeadView();
		sView.setPageTitle("汽车发运");
		invoices = invoiceBll.queryTruckInvoices(truckInvoice);
//		LogUtil.d(TConfig.Echo, "invoices:" + invoices.toString());
		adapter = new TrayPresentAdapter(context, invoices, truckInvoice.getId(), 2);
		sView.setAdapter(adapter);
		refreshBagCount();
	}

	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("车  牌  号：" + truckInvoice.getTruckno());
		TextView tv_scanner_text_identify2 = (TextView) customeView.findViewById(R.id.tv_scanner_text_identify2);
		tv_scanner_text_identify2.setText("发运班组：" + truckInvoice.getGruopInfo());
		TextView tv_scanner_text_identify3 = (TextView) customeView.findViewById(R.id.tv_scanner_text_identify3);
		City city = cityBll.queryCityByCode(truckInvoice.getTerminalStationCode());
		String saleArea = "";
		if (city != null) {
			saleArea = SaleAddressUtil.getAddressStrByCity(city);
		}
		
		tv_scanner_text_identify3.setText("收货地址：" + saleArea +"  "+truckInvoice.getDetailAddress());
		TextView tv_scanner_text_identify4 = (TextView) customeView.findViewById(R.id.tv_scanner_text_identify4);
		tv_scanner_text_identify4.setText("收货单位：" +truckInvoice.getConsignee());
		
		if (truckInvoice.getOption_mode() == Config.BATCH_OPTION_LABEL_TYPE) {
			sView.setMoreOptionBtnVisibility(View.VISIBLE);
//			sView.setMoreOptionStr(moreOptionStr);
		}
	}

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

	}


	private void refreshBagCount() {
		if (!checkViewAvailable())
			return;
		
		int labelCount = invoiceBll.queryTruckLabelCount(truckInvoice);

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

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

	}


	private void refreshAdapter() {
		invoices = invoiceBll.queryTruckInvoices(truckInvoice);
		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(truckInvoice.getId());
		invoice.setTransmode(2);// 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));
				refreshAdapter();
				refreshBagCount();
			}
		});
	}

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

	}

	@Override
	public void moreOptionClick() {
		// TODO Auto-generated method stub
		
	}



}
