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

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.widget.Toast;
import cn.net.caoyao.cpzshandset.R;
import cn.net.caoyao.cpzshandset.bean.ConfigBean;
import cn.net.caoyao.cpzshandset.bean.HandsetParameterBean;
import cn.net.caoyao.cpzshandset.bean.TruckInvoiceBean;
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.util.PhoneParameterUtils;
import cn.net.caoyao.cpzshandset.service.bll.InvoiceBll;
import cn.net.caoyao.cpzshandset.service.bll.TruckInvoiceBll;
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.ythLogin.YthLoginSubmitInvoiceRunable;
import cn.net.caoyao.cpzshandset.ui.activity.ShipmentScannerActivity;
import cn.net.caoyao.cpzshandset.ui.activity.ShipmentSingleScannerActivity;
import cn.net.caoyao.cpzshandset.ui.activity.TruckInvoiceInputStyleConfigActivity;
import cn.net.caoyao.cpzshandset.ui.adapter.TruckInvoiceListAdapter;
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.res.ResponsibleUserInfoBean;
import cn.net.handsetlib.utils.ReadDeviceIDUtil;

public class YthLoginTruckShipmentListPresenter extends OptionHisListStyleConstactImpl {
	private final OptionHisListStyleConstact.View hisView;
	private Context context;
	 private TruckInvoiceBll truckInvoiceBll;
	private ConfigBll configBll;
	private InvoiceBll invoiceBll;
	private TruckInvoiceListAdapter adapter;
	private List<TruckInvoiceBean> truckInvoices = new ArrayList<>();
	private OperationDialog operationDialog;
	private TipsDialog tipsDialog;
	private ProgressDialog bProgressDialog = null;
	private int currentHansetVersion = HandsetVersionConstant.HANDSET_YTH_LOGIN_SHIPMENT_VERSION_MODE;
	private ResponsibleUserInfoBean uInfoBean;
	private Gson gson;

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			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 YthLoginTruckShipmentListPresenter(OptionHisListStyleConstact.View hisView, Context context, Intent intent) {
		super(hisView, context);
		this.hisView = hisView;
		this.context = context;
		truckInvoiceBll = new TruckInvoiceBll(context);
		configBll = new ConfigBll(context);
		invoiceBll = new InvoiceBll(context);
		uInfoBean = (ResponsibleUserInfoBean) intent.getSerializableExtra("userInfo");
		start();
	}

	@Override
	public void start() {
		if (!checkViewAvailable()) return;
		hisView.setPageTitle(context.getResources().getString(R.string.home_truck_shipment_str));
//		truckInvoices = truckInvoiceBll.queryAllTruckInvoices();
		if (uInfoBean.getUserType() == Config.YTH_USER_TYPE_DEFAULT) {
			truckInvoices = truckInvoiceBll.queryAllTruckInvoicesASCByUsr(uInfoBean.getAccount());
		} else {
			truckInvoices = truckInvoiceBll.queryAllTruckInvoices();
		}
		adapter = new TruckInvoiceListAdapter(truckInvoices,2);
		hisView.setAdapter(adapter);
	}

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

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

	@Override
	public void onItemClickListener(int position) {
		if (!checkViewAvailable())
			return;
		if (truckInvoices.size() > 0) {
//			Intent intent = new Intent(context, ShipmentSingleScannerActivity.class);
			// intent.putExtra("shipmentMode", 2);
			Intent intent = new Intent();
			intent.putExtra("transId", truckInvoices.get(position).getId());
			intent.putExtra("userInfo", uInfoBean);
			if (truckInvoices.get(position).getOption_mode() == Config.BATCH_OPTION_LABEL_TYPE) {
				intent.setClass(context, ShipmentScannerActivity.class);
				intent.putExtra("shipmentMode", 2);
			} else {
				intent.setClass(context, ShipmentSingleScannerActivity.class);
			}
			context.startActivity(intent);
		}
	}

	@Override
	public void onItemLongClickListener(int position) {
		if (!checkViewAvailable())
			return;
		if (truckInvoices.size() > 0) {
			showOptionDialog(position);
		}
	}

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

			@Override
			public void modifyClick() {
				// 修改
				if (!checkViewAvailable())
					return;
				Intent intent = new Intent(context, TruckInvoiceInputStyleConfigActivity.class);
				intent.putExtra("isCreate", false);
				intent.putExtra("userInfo", uInfoBean);
				intent.putExtra("currentHisId", truckInvoices.get(position).getId());
				context.startActivity(intent);
			}

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

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

			}
		});

	}

	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() {
				truckInvoiceBll.deleteTruckInvoiceById(truckInvoices.get(position));
				onResume();
				hisView.showMsgToast("删除成功！", Toast.LENGTH_SHORT);
			}
		});

	}

	@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();
		}
//		LogUtil.e(TConfig.Echo, "truckInvoices:" + truckInvoices.toString());
		adapter.refreshData(truckInvoices);
	}

	@Override
	public void uploadAllHisList() {
		if (!checkViewAvailable())
			return;
		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<TruckInvoiceBean> getVialidTruckInvoice() {
		List<TruckInvoiceBean> vialids = new ArrayList<>();
		// List<TruckInvoiceBean> allData =
		// truckInvoiceBll.queryAllTruckInvoicesASC();
		List<TruckInvoiceBean> allData;
		if (uInfoBean.getUserType() == Config.YTH_USER_TYPE_DEFAULT) {
			allData = truckInvoiceBll.queryAllTruckInvoicesASCByUsr(uInfoBean.getAccount());
		} else {
			allData = truckInvoiceBll.queryAllTruckInvoicesASC();
		}
		for (TruckInvoiceBean truckInvoiceBean : allData) {
			int count = invoiceBll.queryTruckLabelCount(truckInvoiceBean);
			int trayCount = invoiceBll.queryTruckTrayCount(truckInvoiceBean);
			if (count > 0 || trayCount > 0) {
				vialids.add(truckInvoiceBean);
			}
		}

		return vialids;
	}

}
