package cn.net.caoyao.cpzshandset.service.presenter.impl.pack.commonfarmers;

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.view.View;
import android.widget.Toast;
import cn.net.caoyao.cpzshandset.bean.ConfigBean;
import cn.net.caoyao.cpzshandset.bean.PackBean;
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.util.NetWorkUtils;
import cn.net.caoyao.cpzshandset.service.bll.PackBll;
import cn.net.caoyao.cpzshandset.service.bll.PackPackageBll;
import cn.net.caoyao.cpzshandset.service.bll.PackSubLabelBll;
import cn.net.caoyao.cpzshandset.service.bll.UploadStatusBll;
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.common.CommonSubmitAllPackThread;
import cn.net.caoyao.cpzshandset.ui.activity.OptionSubListStyleActivity;
import cn.net.caoyao.cpzshandset.ui.activity.PackConfigActivity;
import cn.net.caoyao.cpzshandset.ui.adapter.PackHisListAdapter;
import cn.net.caoyao.cpzshandset.ui.dialog.OperationDialog;
import cn.net.caoyao.cpzshandset.ui.dialog.TipsDialog;
import cn.net.caoyao.cpzshandset.ui.dialog.OperationDialog.DClick;
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 CommonFarmersPackListPresenter extends OptionHisListStyleConstactImpl{

	private final OptionHisListStyleConstact.View hisView;
	private Context context;
	private PackHisListAdapter adapter;
	private List<PackBean> packs = new ArrayList<PackBean>();
	private PackBll packBll;
//	private SingleLabelBll labelBll;
	private UploadStatusBll uploadStatusBll;
	private PackSubLabelBll subLabelBll;
	private PackPackageBll packageBll;
	private ConfigBll configBll;
	private TipsDialog tipsDialog;
	private OperationDialog operationDialog;
	private ProgressDialog bProgressDialog = null;
	private int currentHansetVersion = HandsetVersionConstant.HANDSET_UNIVERSAL_VERSION_MODE_FARMERS;
	private HandsetOperation option_type = HandsetOperation.OPERATION_PACK_CONSTANT;
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case RequestConstant.SUBMIT_ALL_PACK_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;
			case RequestConstant.PROT_REQ_CHECK_LABEL_SUCCESS:
				if (!checkViewAvailable())return;
				dismissProgress();
				hisView.showMsgToast("检测标签信息成功，请在扫码界面中查看详细信息", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.PROT_REQ_CHECK_LABEL_FAIL:
				if (!checkViewAvailable())return;
				dismissProgress();
				hisView.showMsgToast("检测标签信息失败", Toast.LENGTH_SHORT);
				break;
			}
		};
	};
	public CommonFarmersPackListPresenter(OptionHisListStyleConstact.View hisView,Context context) {
		super(hisView, context);
		this.hisView = hisView;
		this.context = context;
		start();
	}
	
	@Override
	public void start() {
		if (!checkViewAvailable()) return;
		init();
		hisView.setPageTitle("打包列表");
		adapter = new PackHisListAdapter(packs);
		hisView.setAdapter(adapter);
//		setTestData();
	}

	private void init() {
		packBll = new PackBll(context);
//		labelBll = new SingleLabelBll(context);
		uploadStatusBll = new UploadStatusBll(context);
		configBll = new ConfigBll(context);
		subLabelBll = new PackSubLabelBll(context);
		packageBll = new PackPackageBll(context);
	}

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

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

	@Override
	public void onItemClickListener(int position) {
		if (packs.size() > 0) {
//			Intent intent = new Intent(context, SingleLabelScannerActivity.class);
//			intent.putExtra("optionMode", option_type);
//			intent.putExtra("currentPackBean", packs.get(position));
//			context.startActivity(intent);
			PackBean a = packs.get(position);
			Intent activateIntent = new Intent(context, OptionSubListStyleActivity.class);
			activateIntent.putExtra("optionMode", option_type);
			activateIntent.putExtra("currentPackBean", a);
			context.startActivity(activateIntent);
		}
		
		
	}

	@Override
	public void onItemLongClickListener(int position) {
		if (!checkViewAvailable())return;
		if (packs.size() > 0) {
			showOptionDialog(position);
		}
		
	}

	private void showOptionDialog(final int position) {
		if (operationDialog == null) {
			operationDialog = new OperationDialog(context);
		}
		operationDialog.show();
		int labelCount = subLabelBll.queryLabelCountByOptionId(packs.get(position).getId(), option_type.getOption());
		if (labelCount > 0) {
			operationDialog.setDelViewVisiable(View.GONE);
		} else {
			operationDialog.setDelViewVisiable(View.VISIBLE);
		}
		operationDialog.setDClick(position, new DClick() {
			
			@Override
			public void modifyClick() {
				//修改
				if (!checkViewAvailable()) return;
				Intent intent = new Intent(context, PackConfigActivity.class);
				intent.putExtra("isCreate", false);
				intent.putExtra("currentHisId", packs.get(position).getId());
				context.startActivity(intent);
			}
			
			@Override
			public void delClick() {
				// 删除
				if (!checkViewAvailable()) return;
				String msg = "本条数据还未上传\n\n是否确定删除打包数据？\n\n确定删除后\n\n该数据对应的所有信息都会被删除" ;
				showWarnTipDialog(msg,position);
				
			}

			@Override
			public void searckClick() {
				if (!checkViewAvailable()) return;
				if (!NetWorkUtils.isNetworkConnected(context)) {
					DialogUtils.showSetNetDialog(context);
					return;
				}
				ConfigBean configBean = configBll.queryConfigByHandsetMode(currentHansetVersion);
				if (configBean == null) {
					hisView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
					return;
				}
				
				if (packs == null || packs.size() == 0) {
					hisView.showMsgToast("抱歉，当前的打包数据中都没有标签，不可上传", Toast.LENGTH_SHORT);
					return;
				}
				
//				List<String> labels = labelBll.queryAllLabelStrById(option_type.getOption(), packs.get(position).getId());
//				if (labels == null) {
//					hisView.showMsgToast("抱歉，当前的打包数据中还没有标签，不可查询", Toast.LENGTH_SHORT);
//					return;
//				}
//				
//				if (labels.size() == 0) {
//					hisView.showMsgToast("抱歉，当前的打包数据中还没有标签，不可查询", Toast.LENGTH_SHORT);
//					return;
//				}
//				showProgressDialog("提示", "正在检测标签信息，请稍后……");
//				long deviceId = Long.parseLong(ReadDeviceIDUtil.readScanDecrypt(configBean.getDeviceId()));
//				ThreadPoolManager.getThreadPool().execute(new CommonCheckLabelThread(mHandler, deviceId, option_type, packs.get(position).getId(), labels, labelBll));				
			}
		});
		
	}
	
	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() {
				PackBean a = packs.get(position);
				packBll.deletePackInfoById(a);
				packs = packBll.queryAllPackList();
				adapter.refreshData(packs);
				hisView.showMsgToast("删除成功！", Toast.LENGTH_SHORT);
			}
		});
		
	}
	@Override
	public void backBtnClick() {
		if (!checkViewAvailable()) return;
		hisView.finishPage();
	}

	@Override
	public void moreOptionClick() {
		if (!checkViewAvailable()) return;
		Intent intent = new Intent(context, PackConfigActivity.class);
		intent.putExtra("isCreate", true);
		context.startActivity(intent);
	}

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

	@Override
	public void onResume() {
		packs = packBll.queryAllPackList();
		adapter.refreshData(packs);
//		LogUtil.i(TConfig.Echo, "packs:" + packs.toString());
	}

	@Override
	public void uploadAllHisList() {
		if (!checkViewAvailable()) return;
		ConfigBean configBean = configBll.queryConfigByHandsetMode(currentHansetVersion);
		if (configBean == null) {
			hisView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
			return;
		}
		if (packs == null || packs.size() == 0) {
			hisView.showMsgToast("抱歉，当前的打包数据中都没有标签，不可上传", Toast.LENGTH_SHORT);
			return;
		}
		
		List<PackBean> valid = getValidPack();
		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 CommonSubmitAllPackThread(mHandler, deviceId, packageBll, subLabelBll, uploadStatusBll, valid));
	}
	
	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);
	}

	private List<PackBean> getValidPack() {
		List<PackBean> ascLists = packBll.queryAllPackListASC();
		List<PackBean> valid = new ArrayList<>();
		for (PackBean packBean : ascLists) {
//			int count = labelBll.queryLabelCountById(option_type.getOption(), packBean.getId());
			int count = subLabelBll.queryLabelCountByOptionId(packBean.getId(), option_type.getOption());
			if (count > 0) {
				valid.add(packBean);
			}
					
		}
		return valid;
	}

}
