package cn.net.caoyao.cpzshandset.service.presenter.impl.shipment.train;

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.TrainInvoiceBean;
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.ConsigneeBll;
import cn.net.caoyao.cpzshandset.service.bll.TrainInvoiceBll;
import cn.net.caoyao.cpzshandset.service.bll.TrainStationBll;
import cn.net.caoyao.cpzshandset.service.presenter.TrainInvoiceConfigConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.TrainInvoiceConfigConstactImpl;
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;
import cn.net.cpzslibs.prot.handset.bean.ConsigneeBean;
import cn.net.cpzslibs.prot.handset.bean.res.TrainStationBean;

public class YthTrainInvoiceConfigPresenter extends TrainInvoiceConfigConstactImpl {
	private final TrainInvoiceConfigConstact.View configView;
	private Context context;
	private boolean isCreate = true;
	private TrainInvoiceBean currentTrainInvoice;
	private String[] trainNoLetters = { "P", "C", "K", "U", "G" };
	List<String> letters = Arrays.asList(trainNoLetters);
	private List<StationManagerBean> startStations = new ArrayList<StationManagerBean>();
	private List<String> stations = new ArrayList<String>();
	private StationManagerBean startStation;// 始发站暂时不在数据库中存储
	private TrainStationBean terminalStation;
	private ConsigneeBean consigneeBean;
	private TrainStationBll stationBll;
	private ConsigneeBll consigneeBll;
	private TrainInvoiceBll trainBll;
	// 设置PopWindow
	private SpinerStationPopWindow mSpinerPopWindow;
	private SpinnerTextPopWindow mLettersPopWindow;

	public YthTrainInvoiceConfigPresenter(TrainInvoiceConfigConstact.View configView, Context context, Intent intent) {
		this.configView = configView;
		this.context = context;
		stationBll = new TrainStationBll(context);
		consigneeBll = new ConsigneeBll(context);
		trainBll = new TrainInvoiceBll(context);
		isCreate = intent.getBooleanExtra("isCreate", true);
		if (!isCreate) {
			int trainId = intent.getIntExtra("currentHisId", -1);
			currentTrainInvoice = trainBll.queryTrainInvoiceById(trainId);
		}
		start();
	}

	@Override
	public void start() {
		if (!checkViewAvailable())
			return;
		initDisplayView();
		initStartStation();
		initStartStationSpinnerView();
		initLetterSpinnerView();
		initDataView();
	}

	private void initDataView() {
//		LogUtil.d(TConfig.Echo, "currentTrainInvoice:" + currentTrainInvoice);
		if(isCreate || currentTrainInvoice == null) return;
		terminalStation = stationBll.queryStationById(currentTrainInvoice.getTerminalstation());
		consigneeBean = consigneeBll.queryConsigeeById(currentTrainInvoice.getConsigneeId());
		if (terminalStation != null) {
			configView.setEndStation(terminalStation.getStation());
			configView.setConsigneeStr(consigneeBean.getConsignee());
			configView.setDate(currentTrainInvoice.getTimestamp());
			String trainNO = currentTrainInvoice.getCarriageno();
			String trainLetter = letters.get(0);
			if (trainNO != null && trainNO.length() > 1) {
				trainLetter = trainNO.substring(0, 1);
				trainNO = trainNO.substring(1, trainNO.length());
			} 
			configView.setTrainLetter(trainLetter);
			configView.setTrainNo(trainNO);
			configView.setOrderNo(currentTrainInvoice.getOrderno());
			if (currentTrainInvoice.getStartingstation() == 0) {
				startStation = startStations.get(0);
			} else {
				startStation = startStations.get(1);
			}
			configView.setStartStation(startStation.getStationname());
		}
		
	}

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

	/**
	 * 初始化起始车站的信息
	 */
	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);
				configView.setStartStation(startStation.getStationname());
			}
		});

	}

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

	}

	/**
	 * 初始化其实车站的选项列表信息 目前只有一条数据
	 */
	private void initStartStation() {
		StationManagerBean s = new StationManagerBean();
		s.setId(0);
		s.setStationname("水富");
		s.setStatus(0);
		s.setTransmode(1);
		// getStationMBll().insertTrainStartStation(s);//本地写死，不做数据库存储
		
		StationManagerBean s1 = new StationManagerBean();
		s1.setId(1);
		s1.setStationname("云峰");
		s1.setStatus(0);
		s1.setTransmode(1);
		
		startStations.add(s);
		startStations.add(s1);
	}

	/**
	 * 显示选择车皮号前字母的popWindow
	 */
	private void showLetterSpinnerWindow() {
		mLettersPopWindow.setWidth(configView.getLetterView().getWidth());
		mLettersPopWindow.showAsDropDown(configView.getLetterTextView());
	}

	/**
	 * 显示起始站的popWindow
	 */
	private void showStartStationSpinnerWindow() {
		mSpinerPopWindow.setWidth(configView.getStartStationView().getWidth());
		mSpinerPopWindow.showAsDropDown(configView.getStartStationTextView());
	}

	@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(!checkViewAvailable()) return;
		if (resultCode == InternalOptionConstant.CHOICE_TRAIN_STATION_NAME_RESULT_CODE) {
			if(data == null) return;
			terminalStation = (TrainStationBean) data.getSerializableExtra("choiceAddressData");
			configView.setEndStation(terminalStation.getStation());
		} else if (resultCode == InternalOptionConstant.CHOICE_TRAIN_END_STATION_RESULT_CODE) {
			if(data == null) return;
			consigneeBean = (ConsigneeBean) data.getSerializableExtra("choiceAddressData");
			if(consigneeBean!=null) configView.setConsigneeStr(consigneeBean.getConsignee());
		}
	}


	/**
	 * 提交订单
	 */
	@Override
	public void choiceTrainLetter() {
		if (!checkViewAvailable())
			return;
		showLetterSpinnerWindow();
	}

	@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_TRAIN_STATION_NAME);
		configView.startAcForResult(InternalOptionConstant.CHOICE_TRAIN_STATION_REQUEST_CODE_COMMON, 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();

	}
	
	/**
	 * 所有信息输入完成，提交当前订单
	 */
	private void submitInvoice() {
		String trainLetter = configView.getTrainLetter();
		String trainNo = configView.getTrainNo();
		String invoiceNo = configView.getOrderNo();
		String time = configView.getDate();
		if (isValid(trainLetter,trainNo, invoiceNo, time)) {
			boolean isExist = false;
			// 检测数据表中是否已经存在该订单
			organizedTrainInvoice(trainLetter, trainNo, invoiceNo, time);
			if (isCreate) {
				isExist = trainBll.insertHasExist(currentTrainInvoice);
			} else {
				isExist = trainBll.updateHasExist(currentTrainInvoice);
			}

			if (isExist) {
				// 数据库中已经存在该订单，提示用户不能更改，并且不再做后续检测
				// 该车皮已经存在未提交的相同订单
				configView.showMsgToast("存在未提交的相同订单，请您修改车皮号或者订单号！", Toast.LENGTH_LONG);
				return;
			} else {
				if (isCreate) {
					int id = trainBll.insertTrainInvoice(currentTrainInvoice);
					currentTrainInvoice.setId(id);
				} else {
					trainBll.updateTrainInvoice(currentTrainInvoice);
				}
			}
			Intent intent = new Intent(context, ShipmentScannerActivity.class);
			intent.putExtra("shipmentMode", 1);
			intent.putExtra("transId", currentTrainInvoice.getId());
			context.startActivity(intent);
			configView.finishPage();
			/*Intent sIntent = new Intent(context, ChoiceShipmentMode.class);
			sIntent.putExtra("transMode", 1);// 1:火车 2:汽车
			sIntent.putExtra("transId", currentTrainInvoice.getId());
			// sIntent.putExtra("cTrainInvoice", currentTrainInvoice);
			startActivity(sIntent);
			finish();*/
		}

	}
	
	/**
	 * 获取创建的订单信息
	 * 
	 * @param trainNo
	 * @param invoiceNo
	 * @param time
	 * @return
	 */
	private void organizedTrainInvoice(String trainLetter,String trainNo, String invoiceNo, String time) {
		if (currentTrainInvoice == null) currentTrainInvoice = new TrainInvoiceBean();
		currentTrainInvoice.setCarriageno(trainLetter + trainNo);
		currentTrainInvoice.setStartingstation(startStation.getId());
		currentTrainInvoice.setTerminalstation(terminalStation.getId());
		currentTrainInvoice.setConsigneeId(consigneeBean.getId());
		currentTrainInvoice.setOrderno(invoiceNo);
		currentTrainInvoice.setTimestamp(time);
		currentTrainInvoice.setLabelMode(1);
	}
	private boolean isValid(String trainLetters,String trainNo, String invoiceNo, String time) {
		boolean b = true;
		if(StringUtils.isEmpty(trainLetters)){
			configView.showMsgToast("车皮号之前的字母不能为空", Toast.LENGTH_SHORT);
		}else  if (StringUtils.isEmpty(trainNo)) {
			configView.showMsgToast("车皮号不能为空", Toast.LENGTH_SHORT);
			b = false;
		} else if (StringUtils.isEmpty(invoiceNo)) {
			configView.showMsgToast("订单号不能为空", Toast.LENGTH_SHORT);
			b = false;
		} else if (StringUtils.isEmpty(time)) {
			configView.showMsgToast("时间不能为空", Toast.LENGTH_SHORT);
			b = false;
		} else if (startStation == null) {
			configView.showMsgToast("始发站不能为空", Toast.LENGTH_SHORT);
			b = false;
		} else if (terminalStation == null) {
			configView.showMsgToast("到达站不能为空", Toast.LENGTH_SHORT);
			b = false;
		} else if (consigneeBean == null) {
			configView.showMsgToast("收货人不能为空", Toast.LENGTH_SHORT);
			b = false;
		}

		return b;
	}
	@Override
	public void choiceConsigneeClick() {
		if(!checkViewAvailable()) return;
		String stationName = configView.getEndStationName();
		/*if (StringUtils.isEmpty(stationName)) {
			configView.showMsgToast("抱歉！到达站名称不能为空，请先选择到达站", Toast.LENGTH_SHORT);
			return;
		}*/
		Intent intent = new Intent(context, ChoiceAddressStyleActivity.class);
		intent.putExtra("optionMode", InternalOptionConstant.ADDRESS_MODE_TRAIN_END_STATION);
		intent.putExtra("stationName", stationName);
		configView.startAcForResult(InternalOptionConstant.CHOICE_TRAIN_STATION_REQUEST_CODE_COMMON, intent);
	}

}
