package cn.net.caoyao.cpzshandset.service.presenter.impl.setting.ythPunit;

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.widget.Toast;
import cn.net.caoyao.cpzshandset.bean.ConfigBean;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.config.HandsetSettingOption;
import cn.net.caoyao.cpzshandset.common.config.HandsetVersionConstant;
import cn.net.caoyao.cpzshandset.common.config.RequestConstant;
import cn.net.caoyao.cpzshandset.common.util.CachePut;
import cn.net.caoyao.cpzshandset.common.util.DateUtil;
import cn.net.caoyao.cpzshandset.common.util.NetWorkUtils;
import cn.net.caoyao.cpzshandset.service.bll.InvoiceBll;
import cn.net.caoyao.cpzshandset.service.bll.OnlineTruckInvoiceBll;
import cn.net.caoyao.cpzshandset.service.bll.ProductBll;
import cn.net.caoyao.cpzshandset.service.bll.TruckAddressBll;
import cn.net.caoyao.cpzshandset.service.bll.TruckConsigneeBll;
import cn.net.caoyao.cpzshandset.service.bll.UserLoginBll;
import cn.net.caoyao.cpzshandset.service.bll.config.ConfigBll;
import cn.net.caoyao.cpzshandset.service.presenter.SettingConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.SettingConstactImpl;
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.YthScannerReqOrderListRunable;
import cn.net.caoyao.cpzshandset.service.thread.impl.ythScanner.YthScannerReqUserInfoRunable;
import cn.net.caoyao.cpzshandset.ui.activity.DeviceIdConfigActivity;
import cn.net.caoyao.cpzshandset.ui.activity.ModifyHandsetVersionActivity;
import cn.net.caoyao.cpzshandset.ui.adapter.SettingAdapter;
import cn.net.caoyao.cpzshandset.ui.weight.DialogUtils;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20012ResBean;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20013ResBean;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20020ResBean;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20031ResBean;
import cn.net.handsetlib.utils.ReadDeviceIDUtil;

public class YthPunitSettingPresenter extends SettingConstactImpl {
	private final SettingConstact.View sView;
	private Context context;
	private List<HandsetSettingOption> beans = new ArrayList<HandsetSettingOption>();
	private ConfigBll configBll;
	private ProductBll productBll;
	private TruckConsigneeBll consigneeBll;
	private TruckAddressBll addressBll;
	private OnlineTruckInvoiceBll truckInvoiceBll;
	private InvoiceBll invoiceBll;
	private ProgressDialog bProgressDialog = null;
	private int currentHandsetVersion = HandsetVersionConstant.HANDSET_YTH_SCANNER_SHIPMENT_PUNIT_VERSION_MODE;
	private CachePut cacheP;
	private UserLoginBll loginBll;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case RequestConstant.REQUEST_FAIL:
				// 请求失败
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.showMsgToast("请求失败！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT:
				// 超时
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.showMsgToast("请求超时！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_PROT01_LOGIN_FAIL:
				// 登录失败
				if (!checkViewAvailable())
					return;
				dismissProgress();
				String errorMsg = msg.obj.toString();
				int errorCode = msg.arg1;
				sView.showMsgToast(errorMsg + errorCode, Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_PRODUCT_LIST_IS_EMPTY:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				String errorMsg1 = msg.obj.toString();
				int errorCode1 = msg.arg1;
				sView.showMsgToast(errorMsg1 + errorCode1, Toast.LENGTH_SHORT);
				break;
			case RequestConstant.PROT_REQ_ADDRESS_20015_NO_DATA:
				// 无地址信息
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.showMsgToast("请求成功，但未获取到地址信息", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.PROT_REQ_ADDRESS_20015_FAIL:
				// 请求地址信息失败
				if (!checkViewAvailable())
					return;
				dismissProgress();
				Prot20012ResBean resBean2 = (Prot20012ResBean) msg.obj;
				if (resBean2 != null) {
					// res = resBean.getErrmsg()+resBean.getErrcode();
					sView.showMsgToast(
							ThreadReqTools.getErrorMsg(resBean2.getErrcode()) + "错误码：" + resBean2.getErrcode(),
							Toast.LENGTH_SHORT);
				} else {
					sView.showMsgToast("请求地址列表失败!", Toast.LENGTH_SHORT);
				}
				break;
			case RequestConstant.PROT_REQ_ADDRESS_20015_SUCCESS:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.showMsgToast("地址列表更新成功", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.PROT_REQ_CONSIGEE_20013_NO_DATA:
				// 无地址信息
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.showMsgToast("请求成功，但未获取到收货单位信息", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.PROT_REQ_CONSIGEE_20013_FAIL:
				// 请求地址信息失败
				if (!checkViewAvailable())
					return;
				dismissProgress();
				Prot20013ResBean resBean3 = (Prot20013ResBean) msg.obj;
				if (resBean3 != null) {
					// res = resBean.getErrmsg()+resBean.getErrcode();
					sView.showMsgToast(
							ThreadReqTools.getErrorMsg(resBean3.getErrcode()) + "错误码：" + resBean3.getErrcode(),
							Toast.LENGTH_SHORT);
				} else {
					sView.showMsgToast("请求收货单位信息失败!", Toast.LENGTH_SHORT);
				}
				break;
			case RequestConstant.PROT_REQ_CONSIGEE_20013_SUCCESS:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.showMsgToast("收货单位信息更新成功", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.PROT_REQ_USERINFO_20020_NO_DATA:
				// 无用户信息
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.showMsgToast("请求成功，但未获取到用户信息，请确认是否在后台注册过用户数据", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.PROT_REQ_USERINFO_20020_FAIL:
				// 请求用户信息失败
				if (!checkViewAvailable())
					return;
				dismissProgress();
				Prot20020ResBean resBean1 = (Prot20020ResBean) msg.obj;
				if (resBean1 != null) {
					// res = resBean.getErrmsg()+resBean.getErrcode();
					sView.showMsgToast(
							ThreadReqTools.getErrorMsg(resBean1.getErrcode()) + "错误码：" + resBean1.getErrcode(),
							Toast.LENGTH_SHORT);
				} else {
					sView.showMsgToast("请求用户配置信息失败!", Toast.LENGTH_SHORT);
				}
				break;
			case RequestConstant.PROT_REQ_USERINFO_20020_SUCCESS:
				// 请求用户信息成功
				if (!checkViewAvailable())
					return;
				dismissProgress();
				sView.showMsgToast("用户配置信息更新成功", Toast.LENGTH_SHORT);
				String updateDate = DateUtil.getDateTime(System.currentTimeMillis());
				getCacheP().putCacheStringG(context, Config.configSPName, Config.updateUserConfigDate, updateDate);
				break;
			case RequestConstant.PROT_REQ_YTH_ORDER_INFO_SUCCESS:
				if (!checkViewAvailable())
					return;
				dismissProgress();
				Prot20031ResBean orderBean = (Prot20031ResBean) msg.obj;
				if (orderBean == null ) return;
				if (orderBean.getResult() == 0) {
					sView.showMsgToast("请求未发货订单列表成功！", Toast.LENGTH_SHORT);
				} else {
					sView.showMsgToast("请求未发货订单列表失败！\n错误码：" + orderBean.getErrcode() +"\n原因：" + ThreadReqTools.getErrorMsg(orderBean.getErrcode()), Toast.LENGTH_SHORT);
				}
				break;
			}
		}

	};


	protected CachePut getCacheP() {
		if (cacheP == null) {
			cacheP = new CachePut();
		}
		return cacheP;
	}

	public YthPunitSettingPresenter(SettingConstact.View sView, Context context) {
		this.sView = sView;
		this.context = context;
		start();
	}

	@Override
	public void start() {
		if (!checkViewAvailable())
			return;
		configBll = new ConfigBll(context);
		initSettingData();
		SettingAdapter adapter = new SettingAdapter(beans);
		sView.setAdapter(adapter);
	}

	private void initSettingData() {
		beans.add(HandsetSettingOption.SETTING_CONFIG_DEVICE_ID_MODE);
		// beans.add(HandsetSettingOption.SETTING_UPDATE_PRODUCT_LIST_MODE);
//		beans.add(HandsetSettingOption.SETTING_UPDATE_ADDRESS_LIST_MODE);
//		beans.add(HandsetSettingOption.SETTING_UPDATE_CONSIGNEE_LIST_MODE);
		beans.add(HandsetSettingOption.SETTING_UPDATE_USER_CONFIG_LIST_MODE);
//		beans.add(HandsetSettingOption.SETTING_UPDATE_NOT_SHIPMENT_ORDER_LIST_MODE);
		if (Config.canSwitchHandsetVersionMode) {
			beans.add(HandsetSettingOption.SETTING_HANDSET_MODE_SWITCH_MODE);
		}
	}

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

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

	}

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

	@Override
	public void onItemClickListener(int position) {
		swithSettingOption(beans.get(position));
	}

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

	private void swithSettingOption(HandsetSettingOption setOption) {
		switch (setOption) {
		case SETTING_UPDATE_NOT_SHIPMENT_ORDER_LIST_MODE:
			//更新未发货运单
			ConfigBean uBean = configBll.queryConfigByHandsetMode(currentHandsetVersion);
			if (uBean != null) {
				if (!NetWorkUtils.isNetworkConnected(context)) {
					DialogUtils.showSetNetDialog(context);
					return;
				}
				showProgressDialog("提示", "正在未发货运单列表，请稍后……");
				long deviceId = Long.parseLong(ReadDeviceIDUtil.readScanDecrypt(uBean.getDeviceId()));
				ThreadPoolManager.getThreadPool()
						.execute(new YthScannerReqOrderListRunable(mHandler, deviceId, getTruckInvoiceBll(),getInvoiceBll()));
			} else {
				sView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
			}
			break;
		case SETTING_UPDATE_USER_CONFIG_LIST_MODE:
			//更新用户信息
			ConfigBean userConfigBean = configBll.queryConfigByHandsetMode(currentHandsetVersion);
			if (userConfigBean != null) {
				if (!NetWorkUtils.isNetworkConnected(context)) {
					DialogUtils.showSetNetDialog(context);
					return;
				}
				showProgressDialog("提示", "正在请求用户配置信息，请稍后……");
				long deviceId = Long.parseLong(ReadDeviceIDUtil.readScanDecrypt(userConfigBean.getDeviceId()));
				ThreadPoolManager.getThreadPool()
						.execute(new YthScannerReqUserInfoRunable(mHandler, deviceId, getLoginBll()));
			} else {
				sView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
			}
			break;
		case SETTING_HANDSET_MODE_SWITCH_MODE:
			// 修改手持机版本模式
			// sView.showMsgToast("修改手持机版本模式", Toast.LENGTH_SHORT);
			Intent modifyVersionIntent = new Intent(context, ModifyHandsetVersionActivity.class);
			context.startActivity(modifyVersionIntent);
			break;
		case SETTING_CONFIG_DEVICE_ID_MODE:
			// 配置设备ID
			// sView.showMsgToast("配置设备ID", Toast.LENGTH_SHORT);
			Intent intent = new Intent(context, DeviceIdConfigActivity.class);
			context.startActivity(intent);
			break;
		}
	}

	private InvoiceBll getInvoiceBll() {
		// TODO Auto-generated method stub
		if (invoiceBll == null) {
			invoiceBll = new InvoiceBll(context);
		}
		return invoiceBll;
	}

	private UserLoginBll getLoginBll() {
		// TODO Auto-generated method stub
		if (loginBll == null) {
			loginBll = new UserLoginBll(context);
		}
		return loginBll;
	}

	private OnlineTruckInvoiceBll getTruckInvoiceBll() {
		if (truckInvoiceBll == null) {
			truckInvoiceBll = new OnlineTruckInvoiceBll(context);
		}
		return truckInvoiceBll;
	}

	private TruckConsigneeBll getConsigneeBll() {
		if (consigneeBll == null) {
			consigneeBll = new TruckConsigneeBll(context);
		}
		return consigneeBll;
	}

	private TruckAddressBll getAddressBll() {
		if (addressBll == null) {
			addressBll = new TruckAddressBll(context);
		}
		return addressBll;
	}

	private ProductBll getProductBll() {
		if (productBll == null) {
			productBll = new ProductBll(context);
		}
		return productBll;
	}

}
