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

import java.util.Arrays;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.Toast;
import cn.net.caoyao.cpzshandset.bean.City;
import cn.net.caoyao.cpzshandset.bean.TruckAddressBean;
import cn.net.caoyao.cpzshandset.bean.TruckConsigeeBean;
import cn.net.caoyao.cpzshandset.bean.TruckInvoiceBean;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.config.InternalOptionConstant;
import cn.net.caoyao.cpzshandset.common.util.DateUtil;
import cn.net.caoyao.cpzshandset.common.util.ScreenManager;
import cn.net.caoyao.cpzshandset.common.util.StringUtils;
import cn.net.caoyao.cpzshandset.service.bll.CityBll;
import cn.net.caoyao.cpzshandset.service.bll.TruckAddressBll;
import cn.net.caoyao.cpzshandset.service.bll.TruckConsigneeBll;
import cn.net.caoyao.cpzshandset.service.bll.TruckInvoiceBll;
import cn.net.caoyao.cpzshandset.service.bll.UserLoginBll;
import cn.net.caoyao.cpzshandset.service.presenter.TruckInvoiceInputConfigConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.TruckInvoiceInputConfigConstactImpl;
import cn.net.caoyao.cpzshandset.service.tools.SaleAddressUtil;
import cn.net.caoyao.cpzshandset.service.tools.TruckNoTools;
import cn.net.caoyao.cpzshandset.ui.activity.SearchByInputStyleActivity;
import cn.net.caoyao.cpzshandset.ui.activity.ShipmentScannerActivity;
import cn.net.caoyao.cpzshandset.ui.activity.ShipmentSingleScannerActivity;
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.ChoiceAddressDialog;
import cn.net.caoyao.cpzshandset.ui.dialog.DateTimePickDialogUtil;
import cn.net.cpzslibs.prot.handset.bean.res.ResponsibleUserInfoBean;

public class YthLoginTruckShipmentInputConfigPresenter extends TruckInvoiceInputConfigConstactImpl{
	private final TruckInvoiceInputConfigConstact.View configView;
	private Context context;
//	private String[] truckNoP = { "云", "贵", "川 ", "渝" };// 车牌号选项
	private List<String> truckNoProvinces = Arrays.asList(TruckNoTools.truckSpecialPreLetter);
	private SpinnerTextPopWindow mtruckNoProvincesPopWindow;
	private String[] groupInfos = { "一班", "二班", "三班", "四班" };// 车牌号选项
	private List<String> groups = Arrays.asList(groupInfos);
	private SpinnerTextPopWindow mGroupInfoPopWindow;
	private ChoiceAddressDialog choiceAddressDialog;
	private int salesArea = 0;
	private int reqAddressDetailCode = 1001;
	private int reqConsigneeCode = 1002;
	private CityBll cityBll;
	private TruckAddressBll addressBll;
	private TruckConsigneeBll consigneeBll;
	private TruckInvoiceBll truckInvoiceBll;
	private boolean isCreate = true;
	private TruckInvoiceBean currentTruckInvoice;
	private ResponsibleUserInfoBean uInfoBean;
	private UserLoginBll loginBll;
	
	
	public YthLoginTruckShipmentInputConfigPresenter(TruckInvoiceInputConfigConstact.View configView,Context context,Intent intent) {
		this.configView = configView;
		this.context = context;
		cityBll = new CityBll(context);
		addressBll = new TruckAddressBll(context);
		consigneeBll = new TruckConsigneeBll(context);
		truckInvoiceBll = new TruckInvoiceBll(context);
		isCreate = intent.getBooleanExtra("isCreate", true);
		if (!isCreate) {
			int id = intent.getIntExtra("currentHisId", -1);
			currentTruckInvoice = truckInvoiceBll.queryTruckInvoiceById(id);
			salesArea = currentTruckInvoice.getTerminalStationCode();
			loginBll = new UserLoginBll(context);
			uInfoBean = loginBll.queryUserInfoByAccount(currentTruckInvoice.getResponsiblePersonId());
		}
		if (isCreate) {
			uInfoBean = (ResponsibleUserInfoBean) intent.getSerializableExtra("userInfo");
		} 
//		LogUtil.d(TConfig.Echo, "uinfo:" + uInfoBean.toString());
		
		start();
	}
	
	@Override
	public void start() {
		if(!checkViewAvailable()) return;
		configView.setMoreOptionVisibiliy(View.GONE);
		configView.setBottomViewVisibiliy(View.VISIBLE);
		initDisplayView();
		initTruckNoProvinceSpinnerView();
		initGropInfoSpinnerView();
		if (!isCreate) {
			initDataView();
		}
	}
	
	private void initDataView() {
		String truckNo = currentTruckInvoice.getTruckno().substring(1, currentTruckInvoice.getTruckno().length());
		String truckProvince = currentTruckInvoice.getTruckno().substring(0,1);
		configView.setTruckNoProvince(truckProvince);
		configView.setTruckNo(truckNo);
		City city = cityBll.queryCityByCode(currentTruckInvoice.getTerminalStationCode());
		if (city != null) {
			configView.setEndStation(SaleAddressUtil.getAddressStrByCity(city));
		}
		configView.setEndStationDetail(currentTruckInvoice.getDetailAddress());
		configView.setConsigneeStr(currentTruckInvoice.getConsignee());
		configView.setGroupInfo(currentTruckInvoice.getGruopInfo());
		configView.setDate(currentTruckInvoice.getTimestamp());
		if(currentTruckInvoice == null) return;
		if (currentTruckInvoice.getOption_mode() == Config.BATCH_OPTION_LABEL_TYPE) {
			configView.setSingleBtnVisibiliy(View.GONE);
		} else {
			configView.setPalletBtnVisibiliy(View.GONE);
		}
		
	}

	private void initGropInfoSpinnerView() {
		ListTextAdapter mAdapter = new ListTextAdapter(groups);
		mAdapter.refreshData(groups, 0);
		// 初始化PopWindow
		mGroupInfoPopWindow = new SpinnerTextPopWindow(context);
		mGroupInfoPopWindow.setAdatper(mAdapter);
		mGroupInfoPopWindow.setItemListener(new IOnItemSelectListener() {
			@Override
			public void onItemClick(int pos) {
				if (!checkViewAvailable())
					return;
				configView.setGroupInfo(groups.get(pos)+"");
			}
		});		
	}

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

	}
	
	/**
	 * 显示选择车皮号前字母的popWindow
	 */
	private void showTruckNoProvinceSpinnerWindow() {
		ScreenManager sm = new ScreenManager(context);
		mtruckNoProvincesPopWindow.setWidth(configView.getTruckNoProvinceView().getWidth());
		mtruckNoProvincesPopWindow.setHeight(sm.changeDipHeight(225));
		mtruckNoProvincesPopWindow.showAsDropDown(configView.getTruckNoProvinceTextView());
	}
	/**
	 * 显示选择班组信息的popWindow
	 */
	private void showGroupInfoSpinnerWindow() {
		mGroupInfoPopWindow.setWidth(configView.getGroupInfoView().getWidth());
		mGroupInfoPopWindow.showAsDropDown(configView.getGroupInfoTextView());
	}

	private void initDisplayView() {
		configView.setPageTitle("汽车发运");
		configView.setMoreOptionStr("完成");
		configView.setResponsiblePersonVisibiliy(View.VISIBLE);
		configView.setResponsiblePersonStr(uInfoBean.getUsername()+"");
		configView.setDriverInfoVisiable(View.GONE);
		configView.setStartStationVisiable(View.GONE);
		configView.setOrderNoVisiable(View.GONE);
		configView.setDate(DateUtil.getDateTimeFormat(System.currentTimeMillis()));		
		configView.setGroupInfo(groups.get(0));
		configView.setTruckNoProvince(truckNoProvinces.get(0));
	}

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


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == reqAddressDetailCode) {
			if (data != null) {
				String detailAddress = data.getStringExtra("addressDetail");
//				LogUtil.d(TConfig.Echo, +salesArea+"  detailAddress:" + detailAddress);
				if (!StringUtils.isEmpty(detailAddress)) {
					configView.setEndStationDetail(detailAddress);
					addressBll.insertNativeTruckAddress(getAddressDetailBean(detailAddress));
				}
			}
		} else if (requestCode == reqConsigneeCode) {
			if (data != null) {
				String consigneeStr = data.getStringExtra("consigneeName");
				if (!StringUtils.isEmpty(consigneeStr)) {
					configView.setConsigneeStr(consigneeStr);
					consigneeBll.insertNativeConsignee(getTruckConsigneeBean(consigneeStr));
				}
			}
		}
	}

	private TruckConsigeeBean getTruckConsigneeBean(String consigneeStr) {
		TruckConsigeeBean cBean = new TruckConsigeeBean();
		cBean.setConsigneeName(consigneeStr);
		cBean.setOriginType(0);
		return cBean;
	}

	private TruckAddressBean getAddressDetailBean(String detailAddress) {
		TruckAddressBean b = new TruckAddressBean();
		b.setDetailAddress(detailAddress);
		b.setCityCode(salesArea);
		b.setOriginType(0);
		b.setUpdateDate(DateUtil.getDateTimeFormat(System.currentTimeMillis()));
		return b;
	}


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

	@Override
	public void choiceTruckNoProvince() {
		if (!checkViewAvailable()) return;
		showTruckNoProvinceSpinnerWindow();		
	}


	@Override
	public void choiceDate() {
		if (!checkViewAvailable())
			return;
		String initEndDateTime = "2017年04月01日 13:30";
		DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(context, initEndDateTime, false);
		dateTimePicKDialog.dateTimePicKDialog(configView.getDateTextView());		
	}

	@Override
	public void choiceEndStationCode() {
		if (!checkViewAvailable()) return;
		showChoiceAddressDialog();		
	}
	private void showChoiceAddressDialog() {
		if (choiceAddressDialog == null) {
			choiceAddressDialog = new ChoiceAddressDialog(context,new ChoiceAddressDialog.ChoiceCity() {
				
				@Override
				public void setCity(City city) {
					if (!checkViewAvailable()) return;
					configView.setEndStation(SaleAddressUtil.getAddressStrByCity(city));
					salesArea = city.getCityCode();
				}
			});
			
		}
		choiceAddressDialog.setCountryStatus(false, true);
		choiceAddressDialog.show();
	}
	@Override
	public void inputEndStationDetail() {
		if (!checkViewAvailable()) return;
		if(salesArea <= 0){
			configView.showMsgToast("请先选择收货地区", Toast.LENGTH_SHORT);
			return;
		}
		Intent intent = new Intent(context, SearchByInputStyleActivity.class);
		intent.putExtra("optionMode", InternalOptionConstant.ADDRESS_MODE_TRUCK_DETAIL_STATION);
		intent.putExtra("salesArea", salesArea);
		configView.startAcForResult(reqAddressDetailCode, intent);
	}

	@Override
	public void inputConsignee() {
		if (!checkViewAvailable()) return;
		Intent intent = new Intent(context, SearchByInputStyleActivity.class);
		intent.putExtra("optionMode", InternalOptionConstant.ADDRESS_MODE_TRUCK_CONSIGNEE);
		configView.startAcForResult(reqConsigneeCode, intent);		
	}

	@Override
	public void choiceGroupInfo() {
		if (!checkViewAvailable()) return;
		showGroupInfoSpinnerWindow();		
	}


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

	/**
	 * 提交订单
	 */
	private void submitInvoice(int option_mode) {
		String truckLiscense = configView.getTruckNoProvince();
		String truckNo = configView.getTruckNo();

		String detailAddress = configView.getEndStationDetail();
		String consigneeStr = configView.getConsigneeStr();
		String gruopInfo = configView.getGroupInfo();
		String time = configView.getDate();
//		LogUtil.i(TConfig.Echo, "truckLiscense:" + truckLiscense +"truckNo: " + truckNo);
		if (isValid(truckLiscense, truckNo, detailAddress, consigneeStr, gruopInfo, time)) {
			if (isCreate) {
				currentTruckInvoice = new TruckInvoiceBean();
			} 
			organizeTruckInvoice(truckLiscense, truckNo, detailAddress, consigneeStr, gruopInfo, time,option_mode);
				if (isCreate) {
					int id = truckInvoiceBll.insertTruckInvoice(currentTruckInvoice);
					currentTruckInvoice.setId(id);
				} else {
					truckInvoiceBll.updateTruckInvoice(currentTruckInvoice);
				}
			
				
			Intent intent = new Intent();
//			Intent intent = new Intent(context, ShipmentSingleScannerActivity.class);
			intent.putExtra("transId", currentTruckInvoice.getId());
			if (currentTruckInvoice.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);
			
			configView.finishPage();
		}

	}

	private void organizeTruckInvoice(String truckLiscense, String truckNo, String detailAddress, String consigneeStr,
			String gruopInfo, String time,int option_mode) {
		currentTruckInvoice.setResponsiblePersonId(uInfoBean.getAccount());
		currentTruckInvoice.setTruckno(truckLiscense + truckNo);
		currentTruckInvoice.setTerminalStationCode(salesArea);
		currentTruckInvoice.setDetailAddress(detailAddress);
		currentTruckInvoice.setConsignee(consigneeStr);
		currentTruckInvoice.setGruopInfo(gruopInfo);
		currentTruckInvoice.setTimestamp(time);
		currentTruckInvoice.setStartingstation(0);
		currentTruckInvoice.setStatus(0);
		currentTruckInvoice.setLabelMode(1);
		currentTruckInvoice.setOption_mode(option_mode);
	}

	private boolean isValid(String truckLiscense, String truckNo, String detailAddress, String consigneeStr,
			String gruopInfo, String time) {

		boolean b = true;
		if (StringUtils.isEmpty(truckLiscense)) {
			b = false;
			configView.showMsgToast("车辆牌照地区不能为空!",Toast.LENGTH_SHORT);
		} else if (StringUtils.isEmpty(truckNo)) {
			b = false;
			configView.showMsgToast("车牌号码不能为空",Toast.LENGTH_SHORT);
		} else if (salesArea <= 0) {
			b = false;
			configView.showMsgToast("收货地区不能为空", Toast.LENGTH_SHORT);
		} else if (StringUtils.isEmpty(gruopInfo)) {
			b = false;
			configView.showMsgToast("发运班组不能为空",Toast.LENGTH_SHORT);
		} else if (StringUtils.isEmpty(time)) {
			b = false;
			configView.showMsgToast("时间不能为空",Toast.LENGTH_SHORT);
		} /*else if (StringUtils.isEmpty(detailAddress)) {
			b = false;
			configView.showMsgToast("收货的详细地址信息不能为空",Toast.LENGTH_SHORT);
		} else if (StringUtils.isEmpty(consigneeStr)) {
			b = false;
			configView.showMsgToast("收货单位不能为空",Toast.LENGTH_SHORT);
		}*/

		return b;
	
	}

	@Override
	public void singleBtnClick() {
		if(!checkViewAvailable()) return;
		submitInvoice(Config.SINGLE_OPTION_LABEL_TYPE);
	}

	@Override
	public void palletBtnClick() {
		if(!checkViewAvailable()) return;
		submitInvoice(Config.BATCH_OPTION_LABEL_TYPE);
		
	}
}
