package cn.net.caoyao.cpzshandset.service.presenter.impl.warehouse.out.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.view.View;
import android.widget.Toast;

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.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.YunCarLingLiaoDal;
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.YunCarUpAllLingLiaoThread;
import cn.net.caoyao.cpzshandset.service.tools.TruckNoTools;
import cn.net.caoyao.cpzshandset.ui.adapter.CarLingLiaoAdapter;
import cn.net.caoyao.cpzshandset.ui.adapter.ListTextAdapter;
import cn.net.caoyao.cpzshandset.ui.adapter.ListTextAdapter.IOnItemSelectListener;
import cn.net.caoyao.cpzshandset.ui.adapter.SpinnerTextPopWindow;
import cn.net.caoyao.cpzshandset.ui.dialog.DateTimePickDialogUtil;
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;



public class YunCarOutWarehouseConfigPresenter extends CarSaleConfigConstactImpl{
	private final CarSaleConfigConstact.View cView;
	private Context context;
	private List<String> carNoLiscense = Arrays.asList(TruckNoTools.truckLetterAllSort);
	private SpinnerTextPopWindow carNoLiscensePopWindow;//车牌前缀
	CarNoBean carNoBean;
	private ConfigBll configBll; 
	private YunCarLingLiaoDal lingLiaoDal;
	private UploadStatusBll uploadStatusBll;//提交状态表
	private ProgressDialog bProgressDialog = null;
	
	private List<Map<String, String>> saleInfo = new ArrayList<Map<String, String>>();//展示用数据
	private CarLingLiaoAdapter carSaleAda;//展示用适配器
	
	String strTou, strNo,Engine;
	int countPicture = 0;
	private TipsDialog tipsDialog;
	private int currentHansetVersion = HandsetVersionConstant.HANDSET_YUN_CAR_VERSION_MODE;
	
	
	public YunCarOutWarehouseConfigPresenter(CarSaleConfigConstact.View cView,
			Context context, Intent intent) {
		super(cView);
		this.cView = cView;
		this.context = context;
		start();
	}
	
	@Override
	public void start() {
		initCarNoLiscenseSpinnerView();
		
		configBll = new ConfigBll(context);
		lingLiaoDal = new YunCarLingLiaoDal(context);
		
		carSaleAda = new CarLingLiaoAdapter(saleInfo);
		cView.setPageTitle("出库配置");
		cView.setMoreOptionBtnVisiable(View.VISIBLE);
		cView.setMoreOptionBtnStr("上传");
		cView.setCarNoButton(View.GONE);
		cView.setEngineNumberText("领料日期  : ");
		cView.setEngineNumberHint("请输入领料日期");
		cView.setVinNumberVisiable(View.GONE);
		cView.setClientTelVisiable(View.GONE);
		cView.setPackageVisiable(View.GONE);
		cView.setEngineNumberEnabled(false);
	
		cView.setSaleAdapter(carSaleAda);
		getDataSaleInfo();
		//车牌号前缀 
		cView.setCarNoLiscense(carNoLiscense.get(0));
	}
	/**
	 * 每次添加或者删数据后刷新最新数据 
	 */
	private void getDataSaleInfo(){ 
		
		saleInfo = lingLiaoDal.queryLingLiaoInfo();
		
		carSaleAda.refreshData(saleInfo);
		getDataSaleInfoPictrue();
	}
	
	/**
	 * 初始化车皮号前面字母的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 onActivityResult(int requestCode, int resultCode, Intent data) {
		if (!checkViewAvailable())
			return;
		if (resultCode == Config.CROP_IMAGE_RESULT_CODE && data != null) {
			String path = data.getStringExtra("selectedImage");
			
			LogUtil.e(TConfig.Echo, "path:" + path);
			lingLiaoDal.insertLingLiaoInfo(strTou + strNo, Engine, path);
		
			getDataSaleInfo();
		}

		
		// cView.setBillImageCount(billPictures.size()); 
	}
	
	/**
	 * 每次添加或者删数据后刷新最新图片
	 */
	private void getDataSaleInfoPictrue() {
		countPicture = lingLiaoDal.queryLingLiaoInfoCount() ? 0 : 1;
		cView.setBillImageCount(countPicture);// 设置图片
		if (countPicture == 0) {
			cView.setPictureVisible(true);
		} else {
			cView.setPictureVisible(false);
		}
	}
	@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 (lingLiaoDal.queryLingLiaoInfoCount()) {
			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 YunCarUpAllLingLiaoThread(mHandler, deviceId, lingLiaoDal,getUploadStatusBll()));
		} else {
			cView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id",
					Toast.LENGTH_SHORT);
		}
	}

	@Override
	public void choiceCarNoLiscense() {

		if (!checkViewAvailable())
			return;
		showCarNoLiscenseSpinnerWindow();

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

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

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

	@Override
	public void choicePictureClick() {
		if (!checkViewAvailable())
			return;
		
		strTou = cView.getCarNoLiscense();
		strNo = cView.getCarNo();
		Engine = cView.getEngineNumber();
		
		if ("".equals(strNo) || null == strNo) {
			cView.showMsgToast("车牌号不能为空", 1);
			return;
		}
		
		if ("".equals(Engine) || null == Engine) {
			cView.showMsgToast("日期不能为空", 1);
			return;
		}
		
		if(!lingLiaoDal.queryLingLiaoInfoCount()){
			cView.showMsgToast("每次能上传一个领料清单,请上传或删除本地领料清单", 1);
			return;
		}
		
		Intent intent = new Intent(context, ContractImageActivity.class);
		cView.startAcForResult(10001, intent);
	}

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

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

	

	@Override
	public boolean checkViewAvailable() {

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

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

	@Override
	public void dataClick() {
		if(!checkViewAvailable()) return;
//		configView.showMsgToast("选择生产日期", Toast.LENGTH_SHORT);
		String initEndDateTime = "2016年11月17日 13:30";
		DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                context, initEndDateTime,true);
        dateTimePicKDialog.dateTimePicKDialog(cView.getDateTextView());
	}

	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;
				lingLiaoDal.deleteAllLingLiaoInfo();
				getDataSaleInfo();
			}
		});

	}
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			
			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_YUNCAR_LIST_FAIL:

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

			case RequestConstant.REQUEST_YUNCAR_LIST__SUCCESS:

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

		}

	};
	
	public void dismissProgress() {
		if (bProgressDialog != null) {
			try {
				DialogUtils.dismissProgressDialog(bProgressDialog);
			} catch (Exception e) {
			
			}
		}
	}
	
	private UploadStatusBll getUploadStatusBll(){
		if (uploadStatusBll == null) {
			uploadStatusBll = new UploadStatusBll(context);
		}
		return uploadStatusBll;
	}
}
