package cn.net.caoyao.cpzshandset.service.presenter.impl.activate.liqueur;

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

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cilico.tools.barcode.PhoneScanner;
import cn.net.caoyao.cpzshandset.R;
import cn.net.caoyao.cpzshandset.bean.ActivateBean;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.config.HandsetOperation;
import cn.net.caoyao.cpzshandset.common.config.TConfig;
import cn.net.caoyao.cpzshandset.common.util.LogUtil;
import cn.net.caoyao.cpzshandset.common.util.StringUtils;
import cn.net.caoyao.cpzshandset.service.bll.ActivateBll;
import cn.net.caoyao.cpzshandset.service.bll.GroupInfoBll;
import cn.net.caoyao.cpzshandset.service.bll.ProductBll;
import cn.net.caoyao.cpzshandset.service.presenter.ActivateConfigConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.ActivateConfigConstactImpl;
import cn.net.caoyao.cpzshandset.ui.activity.BatchLabelScannerActivity;
import cn.net.caoyao.cpzshandset.ui.activity.ProductDetailListActivity;
import cn.net.caoyao.cpzshandset.ui.activity.SingleLabelScannerActivity;
import cn.net.caoyao.cpzshandset.ui.adapter.GroupInfoAdapter;
import cn.net.caoyao.cpzshandset.ui.adapter.SpinnerGroupInfoPopWindow;
import cn.net.caoyao.cpzshandset.ui.adapter.ListTextAdapter.IOnItemSelectListener;
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.cpzslibs.prot.handset.bean.Product;
import cn.net.cpzslibs.prot.handset.bean.res.LiqueurGroupInfoBean;
import cn.net.cpzslibs.prot.utils.StrUtils;

public class LiqueurActivateConfigPresenter extends ActivateConfigConstactImpl{

	private final ActivateConfigConstact.View configView;
	private Context context;
	private EditText et_activate_config_custom_common_batch_no; 
	private TextView tv_activate_config_group_content;
	private View lin_activate_config_group,rel_activate_config_group;
	private int choiceProductReqCode = 10001;
	private Product currentProduct;
	private ActivateBean aBean;
	private ActivateBll activateBll;
	private ProductBll productBll;
	private GroupInfoBll groupInfoBll;
	private boolean isCreate = true;
	private int activateId = -1;
	private TipsDialog tipsDialog;
	private List<LiqueurGroupInfoBean> groupInfos = new ArrayList<>();
	private SpinnerGroupInfoPopWindow groupInfoPopWindow;
	private LiqueurGroupInfoBean currentGroup;
	
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case PhoneScanner.BARCODE_READ:
			case PhoneScanner.BARCODE_ERR_LABEL: // 成功
//				scannerRecuess(msg.obj.toString());
				break;
			case PhoneScanner.BARCODE_NOREAD:
				// 数据扫描失败
				if (checkViewAvailable()) {
					configView.showMsgToast("取消扫描", Toast.LENGTH_SHORT);
				}
				break;
			}

		}
	};
	public LiqueurActivateConfigPresenter(Context context,ActivateConfigConstact.View configView,Intent intent) {
		this.context = context;
		this.configView = configView;
		groupInfoBll = new GroupInfoBll(context);
		isCreate = intent.getBooleanExtra("isCreate", true);
		LogUtil.d(TConfig.Echo, "isCreate:" + isCreate);
		if (!isCreate) {
			activateId = intent.getIntExtra("currentHisId", -1);
			configView.setMoreOptionBtnVisiable(View.VISIBLE);
			configView.setMoreOptionBtnStr("保存");
		}
		start();
	}
	
	
	private void initCustomView(View v) {
		et_activate_config_custom_common_batch_no = (EditText) v.findViewById(R.id.et_activate_config_custom_common_batch_no);
		View lin_activate_config_custom_common_producer =  v.findViewById(R.id.lin_activate_config_custom_common_producer);
		lin_activate_config_custom_common_producer.setVisibility(View.GONE);
		lin_activate_config_group = v.findViewById(R.id.lin_activate_config_group);
		lin_activate_config_group.setVisibility(View.VISIBLE);
		rel_activate_config_group = v.findViewById(R.id.rel_activate_config_group);
		tv_activate_config_group_content = (TextView) v.findViewById(R.id.tv_activate_config_group_content);
		
		
		rel_activate_config_group.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (!checkViewAvailable()) return;
				if (groupInfos == null || groupInfos.size() <= 0) {
					configView.showMsgToast("班组信息为空，请在设置中更新班组信息！", Toast.LENGTH_SHORT);
					return;
				}
				if(groupInfoPopWindow == null )initGropInfoSpinnerView();
				showGroupInfoSpinnerWindow();
			}
		});
	}


	@Override
	public void start() {
		if (!checkViewAvailable()) return;
		activateBll = new ActivateBll(context);
//		configView.setPackageRelationActivateBtnVisiable(View.VISIBLE);
		configView.setPageTitle(context.getResources().getString(R.string.activate_config_title_str));
		View customConfigView = LayoutInflater.from(context).inflate(R.layout.common_activate_config_custom_loyout, null);
		configView.addCustomView(customConfigView);
		initCustomView(customConfigView);
		groupInfos = groupInfoBll.queryAllGroupInfo();
		initDataView();
	}
	
	private void initGropInfoSpinnerView() {
		GroupInfoAdapter groupInfoAdapter = new GroupInfoAdapter(groupInfos);
		groupInfoAdapter.refreshData(groupInfos, 0);
		// 初始化PopWindow 
		groupInfoPopWindow = new SpinnerGroupInfoPopWindow(context);
		groupInfoPopWindow.setAdatper(groupInfoAdapter);
		groupInfoPopWindow.setItemListener(new IOnItemSelectListener() {
			@Override
			public void onItemClick(int pos) {
				if (!checkViewAvailable())
					return;
				currentGroup = groupInfos.get(pos);
				tv_activate_config_group_content.setText(currentGroup.getName());
			}
		});		
	}
	
	/**
	 * 显示选择班组信息的popWindow
	 */
	private void showGroupInfoSpinnerWindow() {
		groupInfoPopWindow.setWidth(rel_activate_config_group.getWidth());
		groupInfoPopWindow.showAsDropDown(tv_activate_config_group_content);
	}
	
	private void initDataView() {
			aBean = activateBll.queryActivateBeanById(activateId);
			if (aBean == null) return;
//			LogUtil.d(TConfig.Echo, "aBean:"+aBean.toString());
			if (aBean.getOption_mode() == Config.SINGLE_OPTION_LABEL_TYPE) {
				configView.setBatchActivateBtnVisiable(View.GONE);
				configView.setPackageRelationActivateBtnVisiable(View.GONE);
			} else if (aBean.getOption_mode() == Config.BATCH_OPTION_LABEL_TYPE) {
				configView.setSingleActivateBtnVisiable(View.GONE);
				configView.setPackageRelationActivateBtnVisiable(View.GONE);
			} else if (aBean.getOption_mode() == Config.PACKAGE_RELATION_LABEL_TYPE) {
				configView.setBatchActivateBtnVisiable(View.GONE);
				configView.setSingleActivateBtnVisiable(View.GONE);
			}
			et_activate_config_custom_common_batch_no.setText(aBean.getProduct_batch_number());
//			if (!StringUtils.isEmpty(aBean.getProducer())) et_activate_config_custom_common_producer.setText(aBean.getProducer());
			if(!StringUtils.isEmpty(aBean.getProduct_date())) configView.setProductDate(aBean.getProduct_date());
			currentProduct = getProductBll().queryProductById(aBean.getProduct_id());
			if (currentProduct == null) return;
			configView.setPId(currentProduct.getId());
			if(!StringUtils.isEmpty(currentProduct.getName())) configView.setPName(currentProduct.getName());
			if(!StringUtils.isEmpty(currentProduct.getNid())) configView.setPNid(currentProduct.getNid());
			currentGroup = groupInfoBll.queryGroupInfoById(aBean.getGroup_number_id());
			tv_activate_config_group_content.setText(currentGroup.getName());
	}
	private ProductBll getProductBll() {
		if (productBll == null) {
			productBll = new ProductBll(context);
		}
		return productBll;
	}


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

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

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		LogUtil.d(TConfig.Echo, "requestCode:" + requestCode +"  resultCode:" + resultCode);
		if (!checkViewAvailable()) return;
		if (requestCode == choiceProductReqCode && resultCode == 1001) {
			if (data != null) {
				currentProduct = (Product) data.getSerializableExtra("choicedProduct");
				configView.setPId(currentProduct.getId());
				configView.setPName(currentProduct.getName());
				configView.setPNid(currentProduct.getNid());
			}
			
		}
	}

	@Override
	public void onResume() {
		
	}

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

	@Override
	public void choiceProductClick() {
		if(!checkViewAvailable()) return;
//		configView.showMsgToast("选择产品", Toast.LENGTH_SHORT);
		Intent intent = new Intent(context, ProductDetailListActivity.class);
		configView.startAcForResult(choiceProductReqCode, intent);
		
	}

	@Override
	public void choiceProductDateClick() {
		if(!checkViewAvailable()) return;
//		configView.showMsgToast("选择生产日期", Toast.LENGTH_SHORT);
		String initEndDateTime = "2016年11月17日 13:30";
		DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                context, initEndDateTime,true);
        dateTimePicKDialog.dateTimePicKDialog(configView.getDateTextView());
		
	}
	
	@Override
	public void packageRelationActivateClick() {
		if(!checkViewAvailable()) return;
		if (currentProduct == null) {
			configView.showMsgToast("产品信息不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		if (StrUtils.isEmpty(configView.getProductDate())) {
			configView.showMsgToast("生产日期不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		if (currentGroup == null) {
			configView.showMsgToast("班组信息不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		Intent intent = new Intent(context, SingleLabelScannerActivity.class);
//		intent.putExtra("optionMode", HandsetOperation.OPERATION_ACTIVATE_CONSTANT.getOption());
		intent.putExtra("optionMode", HandsetOperation.OPERATION_ACTIVATE_CONSTANT);
		organizeActivateBean(Config.PACKAGE_RELATION_LABEL_TYPE);
		
		if (isCreate) {
			int activateId = activateBll.insertActivate(aBean);
			aBean.setId(activateId);;
		} else {
			activateBll.updateActivateById(aBean);
		}
		
		intent.putExtra("currentActivateBean", aBean);
		
		context.startActivity(intent);
		configView.finishPage();		
	}

	@Override
	public void singleActivateClick() {
		if(!checkViewAvailable()) return;
		if (currentProduct == null) {
			configView.showMsgToast("产品信息不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		if (StrUtils.isEmpty(configView.getProductDate())) {
			configView.showMsgToast("生产日期不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		if (currentGroup == null) {
			configView.showMsgToast("班组信息不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		Intent intent = new Intent(context, SingleLabelScannerActivity.class);
//		intent.putExtra("optionMode", HandsetOperation.OPERATION_ACTIVATE_CONSTANT.getOption());
		intent.putExtra("optionMode", HandsetOperation.OPERATION_ACTIVATE_CONSTANT);
		organizeActivateBean(Config.SINGLE_OPTION_LABEL_TYPE);
		
		if (isCreate) {
			int activateId = activateBll.insertActivate(aBean);
			aBean.setId(activateId);;
		} else {
			activateBll.updateActivateById(aBean);
		}
		
		intent.putExtra("currentActivateBean", aBean);
		
		context.startActivity(intent);
		configView.finishPage();
	}

	private void organizeActivateBean(int option_mode) {
		if (aBean == null) {
			aBean = new ActivateBean();
		}
		aBean.setProduct_id(currentProduct.getId());
		aBean.setOption_mode(option_mode);
		aBean.setProduct_date(configView.getProductDate());
		String batchNo = et_activate_config_custom_common_batch_no.getText().toString().trim();
		aBean.setProduct_batch_number(batchNo);
		LogUtil.e(TConfig.Echo, "currentGroup:" + currentGroup.toString());
		aBean.setGroup_number_id(currentGroup.getId());
//		aBean.setProducer(et_activate_config_custom_common_producer.getText().toString().trim());
	}


	@Override
	public void batchActivateClick() {
		if(!checkViewAvailable()) return;
		if (currentProduct == null) {
			configView.showMsgToast("产品信息不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		if (StrUtils.isEmpty(configView.getProductDate())) {
			configView.showMsgToast("生产日期不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		if (currentGroup == null) {
			configView.showMsgToast("班组信息不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		Intent intent = new Intent(context, BatchLabelScannerActivity.class);
//		intent.putExtra("optionMode", HandsetOperation.OPERATION_ACTIVATE_CONSTANT.getOption());
		intent.putExtra("optionMode", HandsetOperation.OPERATION_ACTIVATE_CONSTANT);
		organizeActivateBean(Config.BATCH_OPTION_LABEL_TYPE);
		
		if (isCreate) {
			int activateId = activateBll.insertActivate(aBean);
			aBean.setId(activateId);
		} else {
			activateBll.updateActivateById(aBean);
		}
		
		
		/*if (isCreate) {
			int activateId = activateBll.insertActivate(aBean);
			aBean.setId(activateId);;
		} else {
			activateBll.updateActivateById(aBean);
		}*/
		intent.putExtra("currentActivateBean", aBean);
		context.startActivity(intent);
		configView.finishPage();	
	}
	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;
				if (aBean.getOption_mode() == Config.SINGLE_OPTION_LABEL_TYPE) {
					organizeActivateBean(Config.SINGLE_OPTION_LABEL_TYPE);
				} else if (aBean.getOption_mode() == Config.BATCH_OPTION_LABEL_TYPE) {
					organizeActivateBean(Config.BATCH_OPTION_LABEL_TYPE);
				} else if (aBean.getOption_mode() == Config.PACKAGE_RELATION_LABEL_TYPE) {
					organizeActivateBean(Config.PACKAGE_RELATION_LABEL_TYPE);
				}
				activateBll.updateActivateById(aBean);
				configView.finishPage();
			}
		});
		
	}

	@Override
	public void moreOptionClick() {
		if (currentProduct == null) {
			configView.showMsgToast("产品信息不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		showTipsDialog("是否保存当前修改的信息？");
		
		
	}



}
