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

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

import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import cn.net.caoyao.cpzshandset.bean.StationManagerBean;
import cn.net.caoyao.cpzshandset.bean.TruckInvoiceBean;
import cn.net.caoyao.cpzshandset.common.config.InternalOptionConstant;
import cn.net.caoyao.cpzshandset.common.util.DateUtil;
import cn.net.caoyao.cpzshandset.common.util.StringUtils;
import cn.net.caoyao.cpzshandset.service.bll.StationManagerBll;
import cn.net.caoyao.cpzshandset.service.bll.TruckInvoiceBll;
import cn.net.caoyao.cpzshandset.service.presenter.TruckInvoiceConfigConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.TruckInvoiceConfigConstactImpl;
import cn.net.caoyao.cpzshandset.ui.activity.ChoiceAddressStyleActivity;
import cn.net.caoyao.cpzshandset.ui.activity.ShipmentScannerActivity;
import cn.net.caoyao.cpzshandset.ui.adapter.ListTextAdapter;
import cn.net.caoyao.cpzshandset.ui.adapter.ListTextAdapter.IOnItemSelectListener;
import cn.net.caoyao.cpzshandset.ui.adapter.SpinerStationAdapter;
import cn.net.caoyao.cpzshandset.ui.adapter.SpinerStationPopWindow;
import cn.net.caoyao.cpzshandset.ui.adapter.SpinnerTextPopWindow;
import cn.net.caoyao.cpzshandset.ui.dialog.DateTimePickDialogUtil;

public class YthTruckShipmentConfigPresenter extends TruckInvoiceConfigConstactImpl {
	private final TruckInvoiceConfigConstact.View configView;
	private Context context;
	private String[] truckNoP = { "云", "贵", "川 ", "渝" };// 车牌号选项
	private List<String> truckNoProvinces = Arrays.asList(truckNoP);
	private List<StationManagerBean> startStations = new ArrayList<StationManagerBean>();
	private StationManagerBean startStation, terminalStation;// 始发站暂时不在数据库中存储
	private StationManagerBll stationBll;
	// 设置PopWindow
	private SpinerStationPopWindow mSpinerPopWindow;
	private SpinnerTextPopWindow mtruckNoProvincesPopWindow;
	private TruckInvoiceBean currentTruckInvoice;
	private boolean isCreate = true;
	private TruckInvoiceBll truckBll;

	public YthTruckShipmentConfigPresenter(TruckInvoiceConfigConstact.View configView, Context context, Intent intent) {
		this.configView = configView;
		this.context = context;
		truckBll = new TruckInvoiceBll(context);
		stationBll = new StationManagerBll(context);
		isCreate = intent.getBooleanExtra("isCreate", true);
		if (!isCreate) {
			int trainId = intent.getIntExtra("currentHisId", -1);
			currentTruckInvoice = truckBll.queryTruckInvoiceById(trainId);
		}
		start();
	}

	@Override
	public void start() {
		initDisplayView();
		initStartStation();
		initStartStationSpinnerView();
		initTruckNoProvinceSpinnerView();
		initDataView();
	}
	
	private void initDataView() {
		if (isCreate) return;
		terminalStation = stationBll.queryStationById(currentTruckInvoice.getTerminalstation());
		String truckNo = currentTruckInvoice.getTruckno().substring(1, currentTruckInvoice.getTruckno().length());
		String truckProvince = currentTruckInvoice.getTruckno().substring(0,1);
		configView.setTruckNo(truckNo);
		configView.setTruckNoProvince(truckProvince);
		configView.setOrderNo(currentTruckInvoice.getOrderno());
		configView.setDriverName(currentTruckInvoice.getDrivername());
		configView.setDriverTel(currentTruckInvoice.getDriverphone());
		configView.setDate(currentTruckInvoice.getTimestamp());
		if(terminalStation == null) return;
		configView.setEndStation(terminalStation.getStationname() +"  " + terminalStation.getStationdec());
		
	}

	/**
	 * 初始化车皮号前面字母的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) +"");
			}
		});

	}

	/**
	 * 初始化其实车站的选项列表信息 目前只有一条数据
	 */
	private void initStartStation() {
		StationManagerBean s = new StationManagerBean();
		s.setId(0);
		s.setStationname("水富");
		s.setStatus(0);
		s.setTransmode(1);
		// getStationMBll().insertTrainStartStation(s);//本地写死，不做数据库存储
		startStations.add(s);
	}
	
	/**
	 * 初始化起始车站的信息
	 */
	private void initStartStationSpinnerView() {
		if (!checkViewAvailable())
			return;
		SpinerStationAdapter mAdapter = new SpinerStationAdapter(startStations);
		mAdapter.refreshData(startStations, 0);
		startStation = startStations.get(0);// 默认选中第一条数据
		configView.setStartStation(startStation.getStationname());
		// 初始化PopWindow
		mSpinerPopWindow = new SpinerStationPopWindow(context);
		mSpinerPopWindow.setAdatper(mAdapter);
		mSpinerPopWindow.setItemListener(new SpinerStationAdapter.IOnItemSelectListener() {

			@Override
			public void onItemClick(int pos) {
				startStation = startStations.get(pos);
			}
		});

	}

	/**
	 * 显示选择车皮号前字母的popWindow
	 */
	private void showTruckNoProvinceSpinnerWindow() {
		mtruckNoProvincesPopWindow.setWidth(configView.getTruckNoProvinceView().getWidth());
		mtruckNoProvincesPopWindow.showAsDropDown(configView.getTruckNoProvinceTextView());
	}
	/**
	 * 显示起始站的popWindow
	 */
	private void showStartStationSpinnerWindow() {
		mSpinerPopWindow.setWidth(configView.getStartStationView().getWidth());
		mSpinerPopWindow.showAsDropDown(configView.getStartStationTextView());
	}

	private void initDisplayView() {
		configView.setPageTitle("汽车发货");
		configView.setMoreOptionStr("完成");
		configView.setTruckNoProvince(truckNoProvinces.get(0));
		configView.setDate(DateUtil.getDateTimeFormat(System.currentTimeMillis()));
	}

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


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

		String invoiceNo = configView.getOrderNo();
		String driverName = configView.getDriverName();
		String driverPhone = configView.getDriverTel();
		String time = configView.getDate();
		if (isValid(truckLiscense, truckNo, invoiceNo, driverName, driverPhone, time)) {
			boolean isExist = false;
			if (isCreate) {
				currentTruckInvoice = new TruckInvoiceBean();
				organizeTruckInvoice(truckLiscense, truckNo, invoiceNo, driverName, driverPhone, time);
				isExist = truckBll.insertHasExist(currentTruckInvoice);
			} else {
				organizeTruckInvoice(truckLiscense, truckNo, invoiceNo, driverName, driverPhone, time);
				isExist =truckBll.updateHasExist(currentTruckInvoice);
			}
			
			if (isExist) {
				//数据库中已经存在该订单，提示用户不能更改，并且不再做后续检测  该车牌号已经存在未提交的相同订单
				Toast.makeText(context, "存在未提交的相同订单，请您修改车牌号或者订单号！", Toast.LENGTH_LONG).show();
				return;
			} else {
				if (isCreate) {
					int id = truckBll.insertTruckInvoice(currentTruckInvoice);
					currentTruckInvoice.setId(id);
				} else {
					truckBll.updateTruckInvoice(currentTruckInvoice);
				}
			}
			
			Intent intent = new Intent(context, ShipmentScannerActivity.class);
			intent.putExtra("shipmentMode", 2);
			intent.putExtra("transId", currentTruckInvoice.getId());
			context.startActivity(intent);
			
			configView.finishPage();
		}

	}
	
	private void organizeTruckInvoice(String truckLiscense, String truckNo, String invoiceNo, String driverName,
			String driverPhone, String time) {
		currentTruckInvoice.setDrivername(driverName);
		currentTruckInvoice.setDriverphone(driverPhone);
		currentTruckInvoice.setOrderno(invoiceNo);
		currentTruckInvoice.setStartingstation(startStation.getId());
		currentTruckInvoice.setStatus(0);
		currentTruckInvoice.setTerminalstation(terminalStation.getId());
		currentTruckInvoice.setTimestamp(time);
		currentTruckInvoice.setTruckno(truckLiscense + truckNo);
		currentTruckInvoice.setLabelMode(1);
		
	}

	private boolean isValid(String truckLiscense, String truckNo2, String invoiceNo, String driverName,
			String driverPhone, String time) {
		boolean b = true;
		if (StringUtils.isEmpty(truckLiscense)) {
			b = false;
			configView.showMsgToast("车辆牌照地区不能为空!",Toast.LENGTH_SHORT);
		} else if (StringUtils.isEmpty(truckNo2)) {
			b = false;
			configView.showMsgToast("车牌号码不能为空",Toast.LENGTH_SHORT);
		} else if (StringUtils.isEmpty(invoiceNo)) {
			b = false;
			configView.showMsgToast("订单号不能为空",Toast.LENGTH_SHORT);
		} else if (StringUtils.isEmpty(driverName)) {
			b = false;
			configView.showMsgToast("司机名称不能为空",Toast.LENGTH_SHORT);
		} else if (StringUtils.isEmpty(driverPhone)) {
			b = false;
			configView.showMsgToast("司机电话不能为空",Toast.LENGTH_SHORT);
		} else if (StringUtils.isEmpty(time)) {
			b = false;
			configView.showMsgToast("时间不能为空",Toast.LENGTH_SHORT);
		} else if (startStation == null) {
			b = false;
			configView.showMsgToast("始发站不能为空",Toast.LENGTH_SHORT);
		} else if (terminalStation == null) {
			b = false;
			configView.showMsgToast("到达站不能为空",Toast.LENGTH_SHORT);
		} else if (startStation.getId() == terminalStation.getId()) {
			b = false;
			configView.showMsgToast("始发站和到达站不能相同",Toast.LENGTH_SHORT);
		}

		return b;
	}
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == InternalOptionConstant.CHOICE_TRUCK_END_STATION_RESULT_CODE) {
			if(data == null) return;
			terminalStation = (StationManagerBean) data.getSerializableExtra("choiceAddressData");
			if(terminalStation!=null) configView.setEndStation(terminalStation.getStationname() +"  " +terminalStation.getStationdec());
		}
	}


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

	@Override
	public void choiceStartStation() {
		if (!checkViewAvailable()) return;
		showStartStationSpinnerWindow();
	}

	@Override
	public void choiceEndStation() {
		if (!checkViewAvailable()) return;
		Intent intent = new Intent(context, ChoiceAddressStyleActivity.class);
		intent.putExtra("optionMode", InternalOptionConstant.ADDRESS_MODE_TRUCK_STATION);
		configView.startAcForResult(InternalOptionConstant.CHOICE_TRUCK_END_STATION_RESULT_CODE, intent);
	}


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

	}


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

	}

}
