package cn.net.caoyao.cpzshandset.service.presenter.impl.sale.yunCar;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import cilico.tools.barcode.PhoneScanner;
import cn.net.caoyao.cpzshandset.bean.CarNoBean;
import cn.net.caoyao.cpzshandset.bean.ConfigBean;
import cn.net.caoyao.cpzshandset.common.bitmap.crop.ContractImageActivity;
import cn.net.caoyao.cpzshandset.common.config.Config;
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.ScreenManager;
import cn.net.caoyao.cpzshandset.db.dal.yunCar.YunCarConfigDal;
import cn.net.caoyao.cpzshandset.service.bll.UploadStatusBll;
import cn.net.caoyao.cpzshandset.service.bll.config.ConfigBll;
import cn.net.caoyao.cpzshandset.service.presenter.CarSaleConfigConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.CarSaleConfigConstactImpl;
import cn.net.caoyao.cpzshandset.service.thread.ThreadPoolManager;
import cn.net.caoyao.cpzshandset.service.thread.impl.yunCar.GetCarNo;
import cn.net.caoyao.cpzshandset.service.thread.impl.yunCar.YunCarUpAllSaleInFo;
import cn.net.caoyao.cpzshandset.service.tools.TruckNoTools;
import cn.net.caoyao.cpzshandset.ui.adapter.CarSaleAdapter;
import cn.net.caoyao.cpzshandset.ui.adapter.ListTextAdapter;
import cn.net.caoyao.cpzshandset.ui.adapter.SpinnerTextPopWindow;
import cn.net.cpzslibs.label.LabelUtils;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20063ResBean;
import cn.net.caoyao.cpzshandset.ui.adapter.ListTextAdapter.IOnItemSelectListener;
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.handsetlib.utils.ReadDeviceIDUtil;
/**
 * 第二版仅销售啥都不带
 * @author Administrator
 *
 */
public class YunCarSaleOnlyPresenter extends CarSaleConfigConstactImpl {
	private final CarSaleConfigConstact.View cView;
	private Context context;
	private List<String> carNoLiscense = Arrays.asList(TruckNoTools.truckLetterAllSort);
	private SpinnerTextPopWindow carNoLiscensePopWindow;
	private List<String> billPictures = new ArrayList<>();
	private boolean isCreate = true;
	CarNoBean carNoBean;
	private ConfigBll configBll;
	private ProgressDialog bProgressDialog = null;
	private YunCarConfigDal canConfigDal;
	private UploadStatusBll uploadStatusBll;
	private int currentHansetVersion = HandsetVersionConstant.HANDSET_YUN_CAR_VERSION_MODE;
	private HandsetOperation option_type = HandsetOperation.OPERATION_SALE_CONSTANT;
	private TipsDialog tipsDialog;
	String strTou, strNo, Engine, vin, ClientTel,carDate;
	private CarSaleAdapter carSaleAda;
	private List<Map<String, String>> saleInfo = new ArrayList<Map<String, String>>();
	int countPicture = 0;
	int flag = 1 ;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case PhoneScanner.BARCODE_ERR_LABEL:
				cView.showMsgToast("非16位码", 1);
				break;
			case PhoneScanner.BARCODE_READ:
				scannerSuccess(msg.obj.toString());
				break;
			case PhoneScanner.BARCODE_NOREAD:
				break;
			case RequestConstant.REQUEST_FAIL:
				// 请求失败
				if (!checkViewAvailable()) 
					return;
				dismissProgress();
				cView.showMsgToast("请求失败！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT:
				// 超时 
				if (!checkViewAvailable())
					return;
				dismissProgress();
				cView.showMsgToast("请求超时！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_PROT01_LOGIN_FAIL:
				// 登录失败
				if (!checkViewAvailable())
					return;
				dismissProgress();
				String errorMsg = msg.obj.toString();
				int errorCode = msg.arg1;
				cView.showMsgToast(errorMsg + errorCode, Toast.LENGTH_SHORT);
				break;

			case RequestConstant.REQUEST_PRODUCT_LIST_SUCCESS:
				
				if (!checkViewAvailable())
					return;
				dismissProgress();
				Prot20063ResBean resBean = (Prot20063ResBean) msg.obj;
				cView.setEngineNumber("");
				cView.setVinNumber("");
				cView.setEngineNumber(resBean.getEngine_number());
				cView.setVinNumber(resBean.getVin());
				// cView.showMsgToast(errorMsg + errorCode, Toast.LENGTH_SHORT); 
				break;
			case RequestConstant.REQUEST_PRODUCT_LIST_IS_EMPTY:
				// 请求失败 
				if (!checkViewAvailable()) 
					return;
				dismissProgress();
				cView.showMsgToast("没有车牌号信息,请手动添加", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_YUNCAR_LIST_FAIL:

				if (!checkViewAvailable())
					return;
				dismissProgress();
				cView.showMsgToast("上传完成", 1);
				getDataSaleInfo();
				getDataSaleInfoPictrue();
				break;

			case RequestConstant.REQUEST_YUNCAR_LIST__SUCCESS:

				if (!checkViewAvailable())
					return;
				dismissProgress();
				cView.setCarNo("");
				cView.setEngineNumber("");
				cView.setVinNumber("");
				cView.setClientTel("");
				cView.setPackageLabel("");
				cView.showMsgToast("上传完成", 1);
				getDataSaleInfo();
				getDataSaleInfoPictrue();
				break;
			}

		}

	};

	public YunCarSaleOnlyPresenter(CarSaleConfigConstact.View cView,
			Context context, Intent intent) {
		super(cView);
		this.cView = cView;
		this.context = context;
		isCreate = intent.getBooleanExtra("isCreate", true);
		isCreate = true;
		if (!isCreate) {//不是新增就取 
			carNoBean = (CarNoBean) intent.getSerializableExtra("choicedCarNo");
		}
		start();
	}

	@Override
	public void start() {
		initCarNoLiscenseSpinnerView();//初始化车牌前缀弹出框
		configBll = new ConfigBll(context);
		canConfigDal = new YunCarConfigDal(context);
		carSaleAda = new CarSaleAdapter(saleInfo);
		cView.setPageTitle("销售配置");
		cView.setMoreOptionBtnVisiable(View.VISIBLE);
		cView.setMoreOptionBtnStr("上传");
		cView.setSaleAdapter(carSaleAda);
		getDataSaleInfo();
		getDataSaleInfoPictrue();
		
		if (isCreate) {//是新增加的    
			cView.setCarNoLiscense(carNoLiscense.get(0));//默认取出
			
		}
		
		//setDataView();
	}
	/**
	 *   不是新增加的不用赋值数据
	 */
	private void setDataView() {
		if (isCreate)
			return;
		cView.setCarNoLiscense(carNoBean.getCarNo().substring(0, 1));
		cView.setCarNo(carNoBean.getCarNo().substring(1));
		
		/*cView.setEngineNumber(carNoBean.getEngine_number());
		cView.setVinNumber(carNoBean.getVin());*/
		flag = 2;
		carDate = carNoBean.getCarDate();
		cView.setCarNoEnabled(false);
	}

	public void dismissProgress() {
		if (bProgressDialog != null) {
			try {
				DialogUtils.dismissProgressDialog(bProgressDialog);
			} catch (Exception e) {
			
			}
		}
	}

	public void scannerSuccess(String str) {
		if (!checkViewAvailable())
			return;
		super.scannerSuccess(str);

		str = LabelUtils.getLabelSplits(str);// 截取
		cView.setPackageLabel(str);
		Log.d("--==tag","--==tag"+flag);
		
		canConfigDal
				.insertSaleInfo(strTou + strNo, Engine, vin, ClientTel, str,carDate,flag);
		saleInfo = canConfigDal.querySaleInfo();
		carSaleAda.refreshData(saleInfo);
		cView.setBtnCarNoVerifyEnabled(false);
	};

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (!checkViewAvailable())
			return;
		if (resultCode == Config.CROP_IMAGE_RESULT_CODE && data != null) {
			String path = data.getStringExtra("selectedImage");
			billPictures.add(path);
			LogUtil.e(TConfig.Echo, "path:" + path);

			String dataCar = canConfigDal.querySaleInfoLabel();

			canConfigDal.insertSaleInfoPicture(dataCar, path);
		}

		getDataSaleInfoPictrue();
		// cView.setBillImageCount(billPictures.size()); 
	}

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

	}

	@Override
	public void backClick() {
		if (!checkViewAvailable())
			return;
		cView.finishPage();

	}

	@Override
	public void moreOptionClick() {
		if (!checkViewAvailable())
			return;
		if (canConfigDal.querySaleInfoCount()) {
			cView.showMsgToast("没有数据,请不要上传", 1);
			return;
		}
		if (canConfigDal.querySaleInfoPictrueCount()) {
			cView.showMsgToast("请选择清单图片再上传", 1);
			return;
		}
		
		ConfigBean configBean = configBll
				.queryConfigByHandsetMode(currentHansetVersion);
		if (configBean != null) {
			showProgressDialog("提示", "正在上传数据，请稍后……");
			long deviceId = Long.parseLong(ReadDeviceIDUtil
					.readScanDecrypt(configBean.getDeviceId()));
			ThreadPoolManager.getThreadPool().execute(
					new YunCarUpAllSaleInFo(mHandler, deviceId, canConfigDal,getUploadStatusBll()));
		} else {
			cView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id",
					Toast.LENGTH_SHORT);
		}
	}

	@Override
	public void choiceCarNoLiscense() {
		if (!checkViewAvailable())
			return;
		/**
		 * 弹出popwindow就是车牌的
		 */
		showCarNoLiscenseSpinnerWindow();

	}

	@Override
	public void carNoVerifyClick() {
		if (!checkViewAvailable())
			return;
		String strTou = cView.getCarNoLiscense();
		String strNo = cView.getCarNo();
		String carNo = strTou + strNo;
		if ("".equals(strNo) || null == strNo) {
			cView.showMsgToast("当前车牌号为空", Toast.LENGTH_SHORT);
			return;
		}
		ConfigBean configBean = configBll
				.queryConfigByHandsetMode(currentHansetVersion);
		if (configBean != null) {
			showProgressDialog("提示", "正在请求车牌号信息，请稍后……");
			long deviceId = Long.parseLong(ReadDeviceIDUtil
					.readScanDecrypt(configBean.getDeviceId()));
			ThreadPoolManager.getThreadPool().execute(
					new GetCarNo(mHandler, carNo, deviceId));
		} else {
			cView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id",
					Toast.LENGTH_SHORT);
		}

	}

	/**
	 * 提示正在更新数据
	 */
	protected void showProgressDialog(String titleStr, String tipsMsg) {
		bProgressDialog = DialogUtils.showProgressDialog(bProgressDialog,
				titleStr, tipsMsg, context);
	}

	@Override
	public void scannerClick() {
		if (!checkViewAvailable())
			return;
		if (!canConfigDal.querySaleInfoCount()) {// true 无数据
			cView.showMsgToast("每次能上传一个维修单,请上传或删除本地维修单", 1);
			return;
		}

		strTou = cView.getCarNoLiscense();
		strNo = cView.getCarNo();
		Engine = cView.getEngineNumber();
		vin = cView.getVinNumber();
		ClientTel = cView.getClientTel();

		if ("".equals(strNo) || null == strNo) {
			cView.showMsgToast("车牌号不能为空", 1);
			return;
		}
		if ("".equals(Engine) || null == Engine) {
			cView.showMsgToast("发动机号不能为空", 1);
			return;
		}
		if ("".equals(vin) || null == vin) {
			cView.showMsgToast("车架号不能为空", 1);
			return;
		}

		cView.readQRCode();

	}

	@Override
	public void choicePictureClick() {
		if (!checkViewAvailable())
			return;
		String dataCar = canConfigDal.querySaleInfoLabel();
		if ("".equals(dataCar) || null == dataCar) {
			cView.showMsgToast("请先扫描标签确保有标签数据", 1);
			return;
		}

		Intent intent = new Intent(context, ContractImageActivity.class);
		cView.startAcForResult(10001, intent);

	}

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

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

	/**
	 * 初始化车皮号前面字母的Spinner
	 */
	private void initCarNoLiscenseSpinnerView() {
		ListTextAdapter mAdapter = new ListTextAdapter(carNoLiscense);
		mAdapter.refreshData(carNoLiscense, 0);
		// 初始化PopWindow
		carNoLiscensePopWindow = new SpinnerTextPopWindow(context);
		carNoLiscensePopWindow.setAdatper(mAdapter);
		carNoLiscensePopWindow.setItemListener(new IOnItemSelectListener() {
			@Override
			public void onItemClick(int pos) {
				if (!checkViewAvailable())
					return;
				cView.setCarNoLiscense(carNoLiscense.get(pos) + "");
			}
		});

	}

	/**
	 * 显示选择车皮号前字母的popWindow
	 */
	private void showCarNoLiscenseSpinnerWindow() {
		ScreenManager sm = new ScreenManager(context);
		carNoLiscensePopWindow
				.setWidth(cView.getCarNoLiscenseView().getWidth());
		carNoLiscensePopWindow.setHeight(sm.changeDipHeight(225));
		carNoLiscensePopWindow.showAsDropDown(cView.getCarNoLiscenseTextView());
	}

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

	}

	@Override
	public void listLongItemClick() {
		// TODO Auto-generated method stub
		showTipsDialog("确定删除该订单吗？");
	}

	/**
	 * 每次添加或者删数据后刷新最新数据
	 */
	private void getDataSaleInfo() {
		saleInfo = canConfigDal.querySaleInfo();

		carSaleAda.refreshData(saleInfo);

	}

	/**
	 * 每次添加或者删数据后刷新最新图片
	 */
	private void getDataSaleInfoPictrue() {
		countPicture = canConfigDal.querySaleInfoPictrueCount() ? 0 : 1;
		cView.setBillImageCount(countPicture);// 设置图片
		if (countPicture == 0) {
			cView.setPictureVisible(true);
		} else {
			cView.setPictureVisible(false);
		}
	}

	protected void showTipsDialog(String msg) {
		if (tipsDialog == null) {
			tipsDialog = new TipsDialog(context);
		}
		tipsDialog.show();
		tipsDialog.setTipsView("提示", msg, 0, false, new DSure() {

			@Override
			public void sureClick() {
				if (!checkViewAvailable())
					return;
				canConfigDal.deleteAllSaleInfo();
				canConfigDal.deleteAllSaleInfoPicture();
				getDataSaleInfo();
				getDataSaleInfoPictrue();

			}
		});

	}
	private UploadStatusBll getUploadStatusBll(){
		if (uploadStatusBll == null) {
			uploadStatusBll = new UploadStatusBll(context);
		}
		return uploadStatusBll;
	}

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

}
