package cn.net.caoyao.cpzshandset.service.presenter.impl.warehouse.back.chinatex;

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

import android.app.ProgressDialog;
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.widget.TextView;
import android.widget.Toast;
import cilico.tools.barcode.PhoneScanner;
import cn.net.caoyao.cpzshandset.R;
import cn.net.caoyao.cpzshandset.bean.SingleLabelOptionBean;
import cn.net.caoyao.cpzshandset.bean.WarehouseBean;
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.SingleLabelBll;
import cn.net.caoyao.cpzshandset.service.bll.WarehouseBll;
import cn.net.caoyao.cpzshandset.service.bll.config.ConfigBll;
import cn.net.caoyao.cpzshandset.service.presenter.SingleLabelScannerConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.SingleLabelScannerConstactImpl;
import cn.net.caoyao.cpzshandset.service.thread.ThreadReqTools;
import cn.net.caoyao.cpzshandset.ui.adapter.SingleLabelAdapter;
import cn.net.caoyao.cpzshandset.ui.dialog.TipsDialog;
import cn.net.caoyao.cpzshandset.ui.dialog.TipsDialog.DSure;

/** 
 * @author  作者 李扬: 
 * @date 创建时间：2017-4-24 下午6:30:13 
 * @version 1.0 
 * @parameter 
 * @since  
 * @return  
 */
public class ChinatexBackWarehouseSingleLSPresenter extends SingleLabelScannerConstactImpl{
	private final SingleLabelScannerConstact.View sView;
	private Context context;
	private WarehouseBean currentWarehouseBean;
	private int option_id;
	private SingleLabelBll labelBll;//单标操作
//	private ProductBll productBll;
	private WarehouseBll warehouseBll;//出入返操作
	private ConfigBll configBll;//配置设备id操作
	private TextView tv_scanner_text_identify1, tv_scanner_text_identify2, tv_scanner_text_identify3,
	tv_scanner_text_identify4;//四个描述信息
	private SingleLabelAdapter adapter;
	private List<SingleLabelOptionBean> labels = new ArrayList<>();
	private int option_type = HandsetOperation.OPERATION_BACK_WAREHOUSE_CONSTANT.getOption();
	private TipsDialog tipsDialog;
	private ProgressDialog bProgressDialog = null;
	
	public ChinatexBackWarehouseSingleLSPresenter(SingleLabelScannerConstact.View sView, Context context, Intent intent) {
		super(sView, context);
		this.sView = sView;
		this.context = context;
		currentWarehouseBean = (WarehouseBean) intent.getSerializableExtra("currentWarehouseBean");
		option_id = currentWarehouseBean.getId();//拿到订单id
		start();
	}

	@Override
	public void start() {
		if (!checkViewAvailable())
			return;
		init();
		View customView = LayoutInflater.from(context).inflate(R.layout.scanner_custom_diaplay_layout, null);
		initCustomView(customView);
		sView.setPageTitle("返库扫码");
		sView.setMoreOptionStr("上传");
		sView.setMoreOptionBtnVisiable(View.GONE);
		adapter = new SingleLabelAdapter(labels);
		sView.addHeadView(customView);
		sView.setAdapter(adapter);
		labels = labelBll.queryAllLabelById(option_type,
				currentWarehouseBean.getId());//查询当前单下的所有标签
		adapter.refreshData(labels);
		setLabelCountData();//标签数量
		setLabelStatusData();//状态
	}
	private void setLabelCountData() {
		tv_scanner_text_identify3.setText("标签数量：" + labels.size());
	}

	private void setLabelStatusData() {
		if (currentWarehouseBean.getStatus() == Config.SUBMIT_STATUS_NOT_SUBMIT) {
			tv_scanner_text_identify4.setText("状        态：未提交");
		} else {
			tv_scanner_text_identify4.setText("状        态：提交失败  错误码：" + currentWarehouseBean.getError_code() +"\n原        因："+ ThreadReqTools.getErrorMsg(currentWarehouseBean.getError_code()) );
		}
	}
	@Override
	public boolean checkViewAvailable() {
		boolean b = false;
		if (sView != null && context != null) {
			b = true;
		}
		return b;
	}

	@Override
	public Handler getHandler() {
		// TODO Auto-generated method stub
		return mHandler;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		
	}

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

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

	@Override
	public void btnScannerClick() {
		if (!checkViewAvailable())
			return;
		sView.readQRCode();
		
	}

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

	@Override
	public void onItemClickLinstener(int position) {
		// TODO Auto-generated method stub
		if (position > 0) {
			SingleLabelOptionBean b = labels.get(position - 1);
			String tipsContent = "确认删除返库标签：\n" + b.getLabel_id();
			showDelTipsDialog(position -1,tipsContent);
		}
	}

	@Override
	public void onItemLongClickListener(int position) {
		// TODO Auto-generated method stub
		
	}
	private void init() {
		labelBll = new SingleLabelBll(context);
		warehouseBll = new WarehouseBll(context);
		configBll = new ConfigBll(context);
		
	}
	private void initCustomView(View v) {
		tv_scanner_text_identify1 = (TextView) v.findViewById(R.id.tv_scanner_text_identify1);
		tv_scanner_text_identify2 = (TextView) v.findViewById(R.id.tv_scanner_text_identify2);
		tv_scanner_text_identify3 = (TextView) v.findViewById(R.id.tv_scanner_text_identify3);
		tv_scanner_text_identify4 = (TextView) v.findViewById(R.id.tv_scanner_text_identify4);
		String describeStr = StringUtils.isEmpty(currentWarehouseBean.getDescribe()) ? "无":currentWarehouseBean.getDescribe();
		tv_scanner_text_identify1.setText("描        述："+describeStr);
		/*City mCity = cityBll.queryCityByCode(currentWarehouseBean.getSale_area_code());
		String salesArea = (mCity==null?"全国":SaleAddressUtil.getAddressStrByCity(mCity));
		tv_scanner_text_identify2.setText("销售区域：" + salesArea);*/
		tv_scanner_text_identify2.setVisibility(View.GONE);
	
	}
	private void showIKnowTipsDialog(String tips) {
		if (tipsDialog == null) {
			tipsDialog = new TipsDialog(context);
		}
		tipsDialog.show();
		tipsDialog.setWarnView("提示", tips, true, null);
	}
	/**
	 * 删除提示语 删除后刷新界面并修改状态信息
	 * @param position
	 * @param tipContent
	 */
	private void showDelTipsDialog(final int position,String tipContent){
		if (tipsDialog == null) {
			tipsDialog = new TipsDialog(context);
		}
		tipsDialog.show();
		tipsDialog.setDelWarnView("提示", tipContent, position, false, new DSure() {
			
			@Override
			public void sureClick() {
				SingleLabelOptionBean b = labels.get(position);
				labelBll.deleteLabelByLabelId(b);
				labels = labelBll.queryAllLabelById(option_type, option_id);
				if (labels.size() == 0) {
					warehouseBll.updateWarehouseNotSubmitStatusById(option_id);//修改状态信息
					setLabelStatusData();
				}
				adapter.refreshData(labels);
				setLabelCountData();
			}
		});
	}
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case PhoneScanner.BARCODE_READ:
			case PhoneScanner.BARCODE_ERR_LABEL: // 成功
				scannerSuccess(msg.obj.toString());
				break;
			case PhoneScanner.BARCODE_NOREAD:
				// 数据扫描失败
				if (checkViewAvailable()) {
					sView.showMsgToast("取消扫描", Toast.LENGTH_SHORT);
				}
				break;
			
			}

		}

	};
	@Override
	public void scannerSuccess(String str) {
		if (!checkViewAvailable())
			return;
		LogUtil.d(TConfig.Echo, "scannerRecuess：" + str);
//		sView.vibrate(100);
		super.scannerSuccess(str);
		if (StringUtils.isEmpty(str)) {
			sView.showMsgToast("扫描标签不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		if (!StringUtils.isNumber(str)) {
			sView.showMsgToast("您所扫描的不是中国追溯的合法标签！", Toast.LENGTH_SHORT);
			return;
		}
		if (!(str.length() == 16)) {
			sView.showMsgToast("您所扫描的不是中国追溯的合法标签！"+ str.length(), Toast.LENGTH_SHORT);
			return;
		}
		//不同单中不可以有重复的标签
		if (labelBll.hasExistSingleLabel(str, option_type)) {
			String tips = "本地已经存在未上传的返库标签：\n" + str;
			showIKnowTipsDialog(tips);
			return;
		}
		
		if (labelBll.isMaxLimitCount(option_type, option_id)) {
			String tips = "抱歉，本次返库列表已达到上限，请重新建立返库信息扫描";
			showIKnowTipsDialog(tips);
			return;
		}
//		LogUtil.d(TConfig.Echo, "option_type: " + option_type +"  option_id:"+option_id);
		labelBll.insertLabel(new SingleLabelOptionBean(str, option_type, option_id));
		labels = labelBll.queryAllLabelById(option_type, option_id);
		adapter.refreshData(labels);
		setLabelCountData();
		LogUtil.d(TConfig.Echo, "labels：" + labels.size());
	}
}
