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

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.widget.Toast;
import cn.net.caoyao.cpzshandset.R;
import cn.net.caoyao.cpzshandset.bean.ActivateBean;
import cn.net.caoyao.cpzshandset.bean.ConfigBean;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.config.HandsetOperation;
import cn.net.caoyao.cpzshandset.common.config.HandsetVersionConstant;
import cn.net.caoyao.cpzshandset.common.config.RequestConstant;
import cn.net.caoyao.cpzshandset.common.config.TConfig;
import cn.net.caoyao.cpzshandset.common.util.LogUtil;
import cn.net.caoyao.cpzshandset.service.bll.ActivateBll;
import cn.net.caoyao.cpzshandset.service.bll.BatchLabelBll;
import cn.net.caoyao.cpzshandset.service.bll.ProductBll;
import cn.net.caoyao.cpzshandset.service.bll.SingleLabelBll;
import cn.net.caoyao.cpzshandset.service.bll.config.ConfigBll;
import cn.net.caoyao.cpzshandset.service.presenter.OptionHisListStyleConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.OptionHisListStyleConstactImpl;
import cn.net.caoyao.cpzshandset.service.thread.ThreadPoolManager;
import cn.net.caoyao.cpzshandset.service.thread.impl.ythImage.YthImageSubmitAllActivateThread;
import cn.net.caoyao.cpzshandset.ui.activity.ActivateConfigActivity;
import cn.net.caoyao.cpzshandset.ui.activity.BatchLabelScannerActivity;
import cn.net.caoyao.cpzshandset.ui.activity.SingleLabelScannerActivity;
import cn.net.caoyao.cpzshandset.ui.adapter.ActivateHisListAdapter;
import cn.net.caoyao.cpzshandset.ui.dialog.OperationDialog;
import cn.net.caoyao.cpzshandset.ui.dialog.OperationDialog.DClick;
import cn.net.caoyao.cpzshandset.ui.dialog.TipsDialog;
import cn.net.caoyao.cpzshandset.ui.dialog.TipsDialog.DSure;
import cn.net.caoyao.cpzshandset.ui.weight.DialogUtils;
import cn.net.handsetlib.utils.ReadDeviceIDUtil;

public class YthImageActivateListPresenter extends OptionHisListStyleConstactImpl{
	private final OptionHisListStyleConstact.View hisView;
	private Context context;
	private ActivateHisListAdapter adapter;
	private List<ActivateBean> aBeans = new ArrayList<ActivateBean>();
	private int createActivateConfigReqCode=1001;
	private int modifyActivateConfigReqCode=1002;
	private ActivateBll bll;
	private ProductBll productBll;
	private SingleLabelBll singleLabelBll;
	private BatchLabelBll batchLabelBll;
	private ConfigBll configBll;
	private OperationDialog operationDialog;
	private ProgressDialog bProgressDialog = null;
	private TipsDialog tipsDialog;
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case RequestConstant.SUBMIT_ALL_ACTIVATE_COMPLETE:
				dismissProgress();
				onResume();
				break;
			case RequestConstant.REQUEST_FAIL:
				//请求失败
				if (!checkViewAvailable())return;
				dismissProgress();
				hisView.showMsgToast("请求失败！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT:
				//超时
				if (!checkViewAvailable())return;
				dismissProgress();
				hisView.showMsgToast("请求超时！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_PROT01_LOGIN_FAIL:
				//登录失败
				if (!checkViewAvailable())return;
				dismissProgress();
				String errorMsg = msg.obj.toString();
				int errorCode = msg.arg1;
				hisView.showMsgToast(errorMsg + errorCode, Toast.LENGTH_SHORT);
				break;
			}
		};
	};
	public YthImageActivateListPresenter(Context context,OptionHisListStyleConstact.View hisView) {
		super(hisView, context);
		this.hisView = hisView;
		this.context = context;
		start();
	}
	
	public void dismissProgress() {
		if (bProgressDialog != null) {
			try {
				DialogUtils.dismissProgressDialog(bProgressDialog);
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 提示正在更新数据
	 */
	protected void showProgressDialog(String titleStr, String tipsMsg) {
		bProgressDialog = DialogUtils.showProgressDialog(bProgressDialog, titleStr,
				tipsMsg, context);
	}

	@Override
	public void start() {
		if (!checkViewAvailable()) return;
		bll = new ActivateBll(context);
		configBll = new ConfigBll(context);
		hisView.setPageTitle(context.getResources().getString(R.string.activate_history_list_title_str));
		hisView.setMoreOptionText(context.getResources().getString(R.string.new_create_str));
		adapter = new ActivateHisListAdapter(aBeans,getProductBll(),getSingelLabelBll(),getBatchLabelBll(),HandsetOperation.OPERATION_ACTIVATE_CONSTANT);
		hisView.setAdapter(adapter);
	}

	private BatchLabelBll getBatchLabelBll() {
		if (batchLabelBll == null) {
			batchLabelBll = new BatchLabelBll(context);
		}
		return batchLabelBll;
	}

	private SingleLabelBll getSingelLabelBll() {
		if (singleLabelBll == null) {
			singleLabelBll = new SingleLabelBll(context);
		}
		return singleLabelBll;
	}

	private ProductBll getProductBll() {
		if (productBll == null) {
			productBll = new ProductBll(context);
		}
		return productBll;
	}

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

	@Override
	public void onItemClickListener(int position) {
		if (aBeans.size() == 0) {
			return;
		}
		ActivateBean a = aBeans.get(position);
//		LogUtil.d(TConfig.Echo,position + "position:" + a.getProduct_date());
		if (a.getOption_mode() == Config.SINGLE_OPTION_LABEL_TYPE) {
			//单标激活样式
			Intent intent = new Intent(context, SingleLabelScannerActivity.class);
			intent.putExtra("optionMode", HandsetOperation.OPERATION_ACTIVATE_CONSTANT);
			intent.putExtra("currentActivateBean", a);
			context.startActivity(intent);
		} else {
			//批量激活样式
			Intent intent = new Intent(context, BatchLabelScannerActivity.class);
			intent.putExtra("optionMode", HandsetOperation.OPERATION_ACTIVATE_CONSTANT);
			intent.putExtra("currentActivateBean", a);
			context.startActivity(intent);
		}
	}

	@Override
	public void onItemLongClickListener(int position) {
		if (aBeans.size() > 0) {
			showOperationDialog(position);
		}
	}


	@Override
	public void backBtnClick() {
		if (!checkViewAvailable()) return;
		hisView.finishPage();
	}

	@Override
	public void moreOptionClick() {
		if (!checkViewAvailable()) return;
		Intent intent = new Intent(context, ActivateConfigActivity.class);
		intent.putExtra("isCreate", true);
		hisView.startAcForResult(createActivateConfigReqCode, intent);
//		hisView.showMsgToast("新建", Toast.LENGTH_SHORT);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		LogUtil.d(TConfig.Echo, "onActivityResult"+" requestCode:" + requestCode +"  resultCode:" + resultCode);
		
	}

	@Override
	public void onResume() {
		LogUtil.d(TConfig.Echo, "onResume");
		aBeans = bll.queryAllActivateList();
		adapter.refreshActivateHisData(aBeans);
		
	}
	
	private void showOperationDialog(final int position) {
		if (operationDialog == null) {
			operationDialog = new OperationDialog(context);
		}
		operationDialog.show();
		operationDialog.setDClick(position, new DClick() {
			
			@Override
			public void modifyClick() {
//				showToast("修改：" + position);
//				if(presenter != null) presenter.operateModifyClick(position);
				if (!checkViewAvailable()) return;
				Intent intent = new Intent(context, ActivateConfigActivity.class);
				intent.putExtra("isCreate", false);
				intent.putExtra("currentHisId", aBeans.get(position).getId());
				hisView.startAcForResult(createActivateConfigReqCode, intent);
			}
			
			@Override
			public void delClick() {
				//"是否确定删除订单：" + trainInvoices.get(position).getOrderno()+"\n\n确定删除后\n\n该订单对应的所有信息都会被删除", position, false
//				if(presenter != null) presenter.operateDelClick(position);
				String msg = "本条数据还未上传\n\n是否确定删除激活数据？\n\n确定删除后\n\n该数据对应的所有信息都会被删除" ;
				showWarnTipDialog(msg,position);
			}

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

	protected void showWarnTipDialog(String msg,final int position) {
		if (tipsDialog == null) {
			tipsDialog = new TipsDialog(context);
		}
		tipsDialog.show();
		tipsDialog.setDelWarnView("警告", msg, position, false, new DSure() {
			
			@Override
			public void sureClick() {
//				singleLabelBll.deleteLabelById(HansetOperationConstant.OPERATION_ACTIVATE_CONSTANT, aBeans.get(position).getId());
//				bll.delActivateById(aBeans.get(position).getId());
				bll.delActivateById(aBeans.get(position));
				aBeans = bll.queryAllActivateList();
				adapter.refreshActivateHisData(aBeans);
				hisView.showMsgToast("删除成功！", Toast.LENGTH_SHORT);
			}
		});
		
	}

	@Override
	public void uploadAllHisList() {
		if (!checkViewAvailable()) return;
		ConfigBean configBean = configBll.queryConfigByHandsetMode(HandsetVersionConstant.HANDSET_YTH_IMAGE_VERSION_MODE);
		if (configBean == null) {
			hisView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
			return;
		}
		if (aBeans == null || aBeans.size() == 0) {
			hisView.showMsgToast("抱歉，当前的激活数据中都没有标签，不可上传", Toast.LENGTH_SHORT);
			return;
		}
		
		List<ActivateBean> valid = getValidActivate();
		if (valid == null || valid.size() == 0) {
			hisView.showMsgToast("抱歉，当前的激活数据中都没有标签，不可上传", Toast.LENGTH_SHORT);
			return;
		}
		showProgressDialog("提示", "正在提交激活信息，请稍后……");
		long deviceId = Long.parseLong(ReadDeviceIDUtil.readScanDecrypt(configBean.getDeviceId()));
		ThreadPoolManager.getThreadPool().execute(new YthImageSubmitAllActivateThread(mHandler, deviceId, bll, getSingelLabelBll(), valid));
		
	}

	private List<ActivateBean> getValidActivate() {
		List<ActivateBean> ascList = bll.queryAllActivateListByASC();
		List<ActivateBean> valid = new ArrayList<>();
		for (ActivateBean activateBean : ascList) {
			if (activateBean.getOption_mode() == Config.SINGLE_OPTION_LABEL_TYPE) {
				int count = singleLabelBll.queryLabelCountById(HandsetOperation.OPERATION_ACTIVATE_CONSTANT.getOption(), activateBean.getId());
				if (count > 0) {
					valid.add(activateBean);
				}
			}
			
		}
		return valid;
	}


}
