package cn.net.caoyao.cpzshandset.service.presenter.impl.activateWithPack.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.ActivateWithPackBll;
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.OptionSubListStyleActivity;
import cn.net.caoyao.cpzshandset.ui.activity.ProductDetailListActivity;
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 LiqueurActivateWithPackConfigPresenter extends ActivateConfigConstactImpl implements OnClickListener{

	private final ActivateConfigConstact.View configView;
	private Context context;
	private EditText et_activate_config_custom_common_batch_no,et_pack_count;//et_package_label 
	private TextView tv_activate_config_group_content;
	private View lin_activate_config_group,rel_activate_config_group;//btn_package_label_scanner
	private int choiceProductReqCode = 10001;
	private Product currentProduct;
	private ActivateBean aBean;
	private ActivateWithPackBll 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 HandsetOperation option_type = HandsetOperation.OPERATION_ACTIVATE_WITH_PACK_CONSTANT;
	
	
	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 LiqueurActivateWithPackConfigPresenter(Context context,ActivateConfigConstact.View configView,Intent intent) {
		this.context = context;
		this.configView = configView;
		groupInfoBll = new GroupInfoBll(context);
		isCreate = intent.getBooleanExtra("isCreate", true);
		if (!isCreate) {
			activateId = intent.getIntExtra("currentHisId", -1);
			configView.setMoreOptionBtnVisiable(View.VISIBLE);
			configView.setMoreOptionBtnStr("保存");
		}
		start();
	}
	
	private void scannerRecuess(String str) {
		if (!checkViewAvailable())
			return;
//		PhoneCilicoSoundUtils.play();
		configView.vibrate(100);
		
		if (!checkPackageIdInvalid(str)) {
//			et_package_label.setText(str);
		}
		
	}
	
	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);
//		View lin_package_label = v.findViewById(R.id.lin_package_label);
//		lin_package_label.setVisibility(View.VISIBLE);
		View lin_pack_count = v.findViewById(R.id.lin_pack_count);
		lin_pack_count.setVisibility(View.VISIBLE);
//		et_package_label = (EditText) v.findViewById(R.id.et_package_label);
//		btn_package_label_scanner = v.findViewById(R.id.btn_package_label_scanner);
		et_pack_count = (EditText) v.findViewById(R.id.et_pack_count);
//		btn_package_label_scanner.setOnClickListener(this);
		rel_activate_config_group.setOnClickListener(this);
	}


	@Override
	public void start() {
		if (!checkViewAvailable()) return;
		activateBll = new ActivateWithPackBll(context);
		configView.setPageTitle("生产打包配置");
		configView.setBatchActivateBtnVisiable(View.GONE);
		configView.setSingleActivateBtnStr("生产打包");
		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);
			aBean = activateBll.queryActivatePackBeanById(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);
			} else if (aBean.getOption_mode() == Config.BATCH_OPTION_LABEL_TYPE) {
				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());
			et_pack_count.setText(aBean.getPackCount()+"");
//			et_package_label.setText(aBean.getPackage_label_id());
	}
	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 singleActivateClick() {
		if(!checkViewAvailable()) return;
		if (organizeActivateBean(Config.SINGLE_OPTION_LABEL_TYPE))
			return;

		if (isCreate) {
			// int activateId = activateBll.insertActivate(aBean);
			int activateId = activateBll.insertActivatePack(aBean);
			aBean.setId(activateId);
		} else {
			// activateBll.updateActivateById(aBean);
			activateBll.updateActivatePack(aBean);
		}


		
		Intent activateIntent = new Intent(context, OptionSubListStyleActivity.class);
		activateIntent.putExtra("optionMode", option_type);
		activateIntent.putExtra("currentActivateBean", aBean);
		context.startActivity(activateIntent);
		configView.finishPage();
	}

	private boolean checkPackageIdInvalid(String package_id) {
		if (StrUtils.isEmpty(package_id)) {
			configView.showMsgToast("包标签不能为空", Toast.LENGTH_SHORT);
			return true;
		}
		if (!(package_id.length() == 16)) {
			configView.showMsgToast("不合法的包标签！", Toast.LENGTH_SHORT);
			return true;
		}
		if (activateBll.isSubLabelInOtherPack(package_id)) {
			configView.showMsgToast("该标签已经作为子标签使用，不能再作为本单的包标签", Toast.LENGTH_SHORT);
			return true;
		}
		if (activateBll.packageIdIsExitInOtherActivate(package_id, activateId, isCreate)) {
			configView.showMsgToast("该标签已经存在于其他激活单中，不能再作为本单的包标签", Toast.LENGTH_SHORT);
			return true;
		}
		
		if (activateBll.isPackageIdInOtherPack(package_id,activateId)) {
			configView.showMsgToast("在其他打包信息中作为包标签使用，不能再作为本单的包标签", Toast.LENGTH_SHORT);
			return true;
		}
		
		return false;
	}


	private boolean organizeActivateBean(int option_mode) {
		
		if (currentProduct == null) {
			configView.showMsgToast("产品信息不能为空！", Toast.LENGTH_SHORT);
			return true;
		}
		if (StrUtils.isEmpty(configView.getProductDate())) {
			configView.showMsgToast("生产日期不能为空！", Toast.LENGTH_SHORT);
			return true;
		}
		if (currentGroup == null) {
			configView.showMsgToast("班组信息不能为空！", Toast.LENGTH_SHORT);
			return true;
		}
		
//		String package_id = et_package_label.getText().toString().trim();
//		
//		if (checkPackageIdInvalid(package_id)) return true;
//		
		String pack_count_str = et_pack_count.getText().toString().trim();
		if (StrUtils.isEmpty(pack_count_str)) {
			configView.showMsgToast("预设数量不能为空", Toast.LENGTH_SHORT);
			return true;
		}
		
		int pack_count = Integer.parseInt(pack_count_str);
		if (pack_count <= 0 || pack_count > 2000) {
			configView.showMsgToast("预设数量必须为大于0，并且小于2000的数字", Toast.LENGTH_SHORT);
			return true;
		}
		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.setPackage_label_id(package_id);
		aBean.setPackCount(pack_count);
		
		return false;
//		aBean.setProducer(et_activate_config_custom_common_producer.getText().toString().trim());
	}


	@Override
	public void batchActivateClick() {
		if(!checkViewAvailable()) return;
		if(organizeActivateBean(Config.BATCH_OPTION_LABEL_TYPE)) return;
		Intent intent = new Intent(context, BatchLabelScannerActivity.class);
//		intent.putExtra("optionMode", HandsetOperation.OPERATION_ACTIVATE_CONSTANT.getOption());
		intent.putExtra("optionMode", HandsetOperation.OPERATION_ACTIVATE_WITH_PACK_CONSTANT);
		
		
		if (isCreate) {
//			int activateId = activateBll.insertActivate(aBean);
			int activateId = activateBll.insertActivatePack(aBean);
			aBean.setId(activateId);
		} else {
//			activateBll.updateActivateById(aBean);
			activateBll.updateActivatePack(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) {
					if (!organizeActivateBean(Config.SINGLE_OPTION_LABEL_TYPE)) {
						activateBll.updateActivatePack(aBean);
						configView.finishPage();
					}
				} else if (aBean.getOption_mode() == Config.BATCH_OPTION_LABEL_TYPE) {
					if (!organizeActivateBean(Config.BATCH_OPTION_LABEL_TYPE)) {
						activateBll.updateActivatePack(aBean);
						configView.finishPage();
					}
				}
//				activateBll.updateActivateById(aBean);
				
			}
		});
		
	}

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


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_package_label_scanner:
			if(!checkViewAvailable()) return;
			configView.readQRCode();
			break;

		case R.id.rel_activate_config_group:
			if (!checkViewAvailable()) return;
			if (groupInfos == null || groupInfos.size() <= 0) {
				configView.showMsgToast("班组信息为空，请在设置中更新班组信息！", Toast.LENGTH_SHORT);
				return;
			}
			if(groupInfoPopWindow == null )initGropInfoSpinnerView();
			showGroupInfoSpinnerWindow();
			break;
		}
		
	}

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

}
