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

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
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.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.LogUtil;
import cn.net.caoyao.cpzshandset.common.util.NetWorkUtils;
import cn.net.caoyao.cpzshandset.common.util.PhoneParameterUtils;
import cn.net.caoyao.cpzshandset.common.util.StringUtils;
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.ShipmentProductBll;
import cn.net.caoyao.cpzshandset.service.bll.config.ConfigBll;
import cn.net.caoyao.cpzshandset.service.presenter.OptionHisListStyleConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.OptionHisListStyleConstactImpl;
import cn.net.caoyao.cpzshandset.service.thread.ThreadPoolManager;
import cn.net.caoyao.cpzshandset.service.thread.ThreadReqTools;
import cn.net.caoyao.cpzshandset.service.thread.impl.ythPunit.YthPunitReqOrderByIdRunable;
import cn.net.caoyao.cpzshandset.ui.activity.OptionSubListStyleActivity;
import cn.net.caoyao.cpzshandset.ui.activity.TruckInvoiceInputStyleConfigActivity;
import cn.net.caoyao.cpzshandset.ui.adapter.TruckOnlineInvoiceListAdapter;
import cn.net.caoyao.cpzshandset.ui.dialog.OperationDialog;
import cn.net.caoyao.cpzshandset.ui.dialog.OperationDialog.DClick;
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.Prot20025ReqBean;
import cn.net.cpzslibs.prot.handset.bean.req.Prot20032ReqBean;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20046ResBean;
import cn.net.cpzslibs.prot.handset.bean.res.ResponsibleUserInfoBean;
import cn.net.cpzslibs.prot.handset.bean.res.YthOrderBean;
import cn.net.handsetlib.utils.ReadDeviceIDUtil;

public class YthPunitTruckShipmentListPresenter extends OptionHisListStyleConstactImpl {
	private final OptionHisListStyleConstact.View hisView;
	private Context context;
	private OnlineTruckInvoiceBll truckInvoiceBll;
	private ConfigBll configBll;
	private InvoiceBll invoiceBll;
	private DriverInfoBll driverInfoBll;
	private ShipmentProductBll shipProductBll;
	private TruckOnlineInvoiceListAdapter adapter;
	private List<DriverInfoBean> driverInfos = new ArrayList<>();
	private OperationDialog operationDialog;
	private TipsDialog tipsDialog;
	private ProgressDialog bProgressDialog = null;
	private int currentHansetVersion = HandsetVersionConstant.HANDSET_YTH_SCANNER_SHIPMENT_PUNIT_VERSION_MODE;
	private HandsetOperation option_type = HandsetOperation.OPERATION_TRUCK_SHIPMENT_CONSTANT;
	private ResponsibleUserInfoBean uInfoBean;
	private Gson gson;
//	private WebApi webApi;

	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()) {
					hisView.showMsgToast("取消扫描", Toast.LENGTH_SHORT);
				}
				break;
			case RequestConstant.PROT_REQ_YTH_ORDER_INFO_SUCCESS:
				if (!checkViewAvailable())
					return;
				LogUtil.e(TConfig.Echo, "请求订单信息成功：" + msg.obj.toString());
				dismissProgress();
				reqOrderInfoSuccess((Prot20046ResBean) msg.obj);
				break;
			case RequestConstant.PROT_SUBMIT_INVOICE_10051_FAIL:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				onResume();
				break;
			case RequestConstant.PROT_SUBMIT_INVOICE_10051_SUCCESS:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				onResume();
				break;
			case RequestConstant.REQUEST_PROT01_LOGIN_FAIL:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				hisView.showMsgToast("登录失败！" + "\n错误码：" + msg.arg1 + "\n原因：" + ThreadReqTools.getErrorMsg(msg.arg1),
						Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				hisView.showMsgToast("连接超时", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_FAIL:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				hisView.showMsgToast("请求失败!", Toast.LENGTH_SHORT);
				break;
			}

		}
	};

	public YthPunitTruckShipmentListPresenter(OptionHisListStyleConstact.View hisView, Context context, Intent intent) {
		super(hisView,context);
		this.hisView = hisView;
		this.context = context;
		
		truckInvoiceBll = new OnlineTruckInvoiceBll(context);
		configBll = new ConfigBll(context);
		invoiceBll = new InvoiceBll(context);
		driverInfoBll = new DriverInfoBll(context);
		shipProductBll = new ShipmentProductBll(context);
		uInfoBean = (ResponsibleUserInfoBean) intent.getSerializableExtra("userInfo");
		start();
	}

	protected void reqOrderInfoSuccess(Prot20046ResBean resBean) {
		if(!checkViewAvailable()) return;
//		if(StringUtils.isEmpty(orderInfo)){
//			hisView.showMsgToast("未请求到数据，请检查使用的二维码是否正确", Toast.LENGTH_SHORT);
//			return;
//		}
//		YthOrderBean yBean = getGson().fromJson(orderInfo, YthOrderBean.class);
		if (resBean.getResult() == 1) {
			//请求时遇到错误信息
			showReqOrderFailTipsDialog("请求时遇到错误信息，请确认扫描的二维码是否正确\n错误码：" + resBean.getErrcode() +"\n原因：" + ThreadReqTools.getErrorMsg(resBean.getErrcode()));
			return;
			
		}
		if (resBean.getDriver() != null) {
			driverInfoBll.insertLogisticsDriverInfo(resBean.getDriver());
		}
		if (resBean.getOrder() != null) {
			truckInvoiceBll.insertLogisticsOrderInfoBean(resBean.getOrder());
		}
		
		if (resBean.getHuowu() != null) {
			long order_id = (resBean.getDriver() != null ? resBean.getDriver().getOrder_id():0);
			shipProductBll.insertLogisticsProductList(resBean.getHuowu(),order_id);
		}
		
		Intent intent = new Intent(context, OptionSubListStyleActivity.class);
		// intent.putExtra("shipmentMode", 2);
		intent.putExtra("optionMode", option_type);
		intent.putExtra("transId", resBean.getDriver().getId());
		intent.putExtra("userInfo", uInfoBean);
		context.startActivity(intent);
	}
	public void showReqOrderFailTipsDialog(final String tipsContent) {
		if (tipsDialog == null) {
			tipsDialog = new TipsDialog(context);
		}
		tipsDialog.show();
		tipsDialog.setTipsView(null, tipsContent, 0, true, new DSure() {

			@Override
			public void sureClick() {
//				if (!checkViewAvailable()) return;
			}
		});
	}

	@Override
	public void scannerSuccess(String scannerContent) {
		super.scannerSuccess(scannerContent);
		LogUtil.e(TConfig.Echo, "scannerContent:" + scannerContent);
//		hisView.vibrate(100);
		if (StringUtils.isEmpty(scannerContent)) {
			hisView.showMsgToast("未扫描到信息，请确认扫描的二维码是否正确", Toast.LENGTH_SHORT);
			return;
		}
		scannerContent = scannerContent.trim();
		if (!StringUtils.isNumber(scannerContent)) {
			hisView.showMsgToast("扫描到的数据格式不正确，请确认扫描的二维码是否正确", Toast.LENGTH_SHORT);
			return;
		}
		
		//本地校验
		if (driverInfoBll.insertHasExist(Long.parseLong(scannerContent))) {
			Intent intent = new Intent(context, OptionSubListStyleActivity.class);
			intent.putExtra("optionMode", option_type);
			intent.putExtra("transId", Long.parseLong(scannerContent));
			intent.putExtra("userInfo", uInfoBean);
			context.startActivity(intent);
			return;
		}
		//本地不存在该订单，从服务器获取
		if (!NetWorkUtils.isNetworkConnected(context)) {
			DialogUtils.showSetNetDialog(context);
			return;
		}
		
		ConfigBean configBean = configBll.queryConfigByHandsetMode(currentHansetVersion);
		if (configBean == null) {
			hisView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
			return;
		}
		long deviceId = Long.parseLong(ReadDeviceIDUtil.readScanDecrypt(configBean.getDeviceId()));
		showProgressDialog("提示", "正在请求订单信息，请稍后……");
		ThreadPoolManager.getThreadPool().execute(new YthPunitReqOrderByIdRunable(mHandler, deviceId, new Prot20032ReqBean(scannerContent)));
	}

	@Override
	public void start() {
		if (!checkViewAvailable()) return;
		hisView.setPageTitle(context.getResources().getString(R.string.home_truck_shipment_str));
//		truckInvoices = truckInvoiceBll.queryAllTruckInvoices();
		hisView.setMoreOptionVisibility(View.GONE);
		hisView.setBottomText("扫码");
//		truckInvoices = truckInvoiceBll.queryAllTruckInvoices();
//		truckInvoices = truckInvoiceBll.queryAllYthOrderDESC();
		driverInfos = driverInfoBll.queryAllDriverInfoDESC();
//		LogUtil.e(TConfig.Echo, "本地订单：" + truckInvoices.toString());
		adapter = new TruckOnlineInvoiceListAdapter(driverInfos,truckInvoiceBll,driverInfoBll,uInfoBean.getRepertory_id());
		hisView.setAdapter(adapter);
	}

	@Override
	public boolean checkViewAvailable() {
		boolean b = false;
		if (hisView != null && context != null) {
			b = true;
		}
		return b;
	}

	@Override
	public Handler getHandler() {
		return mHandler;
	}

	@Override
	public void onItemClickListener(int position) {
		if (!checkViewAvailable())
			return;
		if (driverInfos.size() > 0) {
			Intent intent = new Intent(context, OptionSubListStyleActivity.class);
			// intent.putExtra("shipmentMode", 2);
			intent.putExtra("optionMode", option_type);
			intent.putExtra("transId", driverInfos.get(position).getId());
			intent.putExtra("userInfo", uInfoBean);
			context.startActivity(intent);
		}
	}

	@Override
	public void onItemLongClickListener(int position) {
		if (!checkViewAvailable())
			return;
		if (driverInfos.size() > 0) {
//			showOptionDialog(position);
			int labelCount = driverInfoBll.queryLabelCountByDriverId(driverInfos.get(position).getId());
			if (labelCount <= 0) {
				showOptionDialog(position);
			}
		}
	}

	private void showOptionDialog(final int position) {
		if (operationDialog == null) {
			operationDialog = new OperationDialog(context);
		}
		operationDialog.show();
		operationDialog.setSearchViewVisiable(View.GONE);
		operationDialog.setModifyViewVisiable(View.GONE);
		operationDialog.setDClick(position, new DClick() {

			@Override
			public void modifyClick() {
				// 修改
			}

			@Override
			public void delClick() {
				// 删除
				if (!checkViewAvailable())
					return;
				String msg = "本条数据还未上传\n\n是否确定删除汽车发货数据？\n\n确定删除后\n\n该数据对应的所有信息都会被删除";
				showWarnTipDialog(msg, position);
			}

			@Override
			public void searckClick() {}
		});

	}

	protected void showWarnTipDialog(String msg, final int position) {
		if (tipsDialog == null) {
			tipsDialog = new TipsDialog(context);
		}
		tipsDialog.show();
		tipsDialog.setDelWarnView("警告", msg, position, false, new DSure() {

			@Override
			public void sureClick() {
				driverInfoBll.deleteDriverInfoById(driverInfos.get(position));
				hisView.showMsgToast("删除成功！", Toast.LENGTH_SHORT);
				onResume();
				
			}
		});

	}

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

	}

	@Override
	public void moreOptionClick() {
		if (!checkViewAvailable())
			return;
		Intent intent = new Intent(context, TruckInvoiceInputStyleConfigActivity.class);
		intent.putExtra("isCreate", true);
		intent.putExtra("userInfo", uInfoBean);
		context.startActivity(intent);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub

	}

	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 onResume() {
		if (!checkViewAvailable())
			return;
		// truckInvoices = truckInvoiceBll.queryAllTruckInvoices();
//		if (uInfoBean.getUserType() == Config.YTH_USER_TYPE_DEFAULT) {
//			truckInvoices = truckInvoiceBll.queryAllTruckInvoicesByUsr(uInfoBean.getAccount());
//		} else {
//			truckInvoices = truckInvoiceBll.queryAllTruckInvoices();
//		}
//		truckInvoices = truckInvoiceBll.queryAllTruckInvoices();
//		truckInvoices = truckInvoiceBll.queryAllYthOrderDESC();
		driverInfos = driverInfoBll.queryAllDriverInfoDESC();
		adapter.refreshData(driverInfos);
	}

	@Override
	public void uploadAllHisList() {
		if (!checkViewAvailable())
			return;
		hisView.readQRCode();
//		ConfigBean configBean = configBll.queryConfigByHandsetMode(currentHansetVersion);
//		if (configBean == null) {
//			hisView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
//			return;
//		}
//		if (truckInvoices == null || truckInvoices.size() == 0) {
//			hisView.showMsgToast("抱歉，当前还没有未上传发货列表，不可上传", Toast.LENGTH_SHORT);
//			return;
//		}
//
//		List<TruckInvoiceBean> vialids = getVialidTruckInvoice();
//
//		if (vialids == null || vialids.size() <= 0) {
//			hisView.showMsgToast("抱歉，当前的订单中都没有标签，不可上传", Toast.LENGTH_SHORT);
//			return;
//		}
//
//		showProgressDialog("提示", "正在上传发货信息，请稍后……");
//		long deviceId = Long.parseLong(ReadDeviceIDUtil.readScanDecrypt(configBean.getDeviceId()));
//		 ThreadPoolManager.getThreadPool().execute(new
//		 YthLoginSubmitInvoiceRunable(mHandler, deviceId, truckInvoiceBll,
//		 invoiceBll, vialids,getProt20025Bean()));
	}
	
	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;
	}

	private List<YthOrderBean> getVialidTruckInvoice() {
		List<YthOrderBean> vialids = new ArrayList<>();
		// List<TruckInvoiceBean> allData =
		// truckInvoiceBll.queryAllTruckInvoicesASC();
		List<YthOrderBean> allData;
//		if (uInfoBean.getUserType() == Config.YTH_USER_TYPE_DEFAULT) {
//			allData = truckInvoiceBll.queryAllTruckInvoicesASCByUsr(uInfoBean.getAccount());
//		} else {
//			allData = truckInvoiceBll.queryAllTruckInvoicesASC();
//		}
		
		/*allData = truckInvoiceBll.queryAllYthOrderASC();
		for (YthOrderBean truckInvoiceBean : allData) {
			int count = invoiceBll.queryOnlineTruckLabelCountByLId(truckInvoiceBean);
			if (count > 0) {
				vialids.add(truckInvoiceBean);
			}
		}*/

		return vialids;
	}

}
