package cn.net.caoyao.cpzshandset.service.presenter.impl.unpack.commonEgg;

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

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

import cilico.tools.barcode.PhoneScanner;
import cn.net.caoyao.cpzshandset.bean.ConfigBean;
import cn.net.caoyao.cpzshandset.bean.UnpackBean;
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.common.util.NetWorkUtils;
import cn.net.caoyao.cpzshandset.common.util.StringUtils;
import cn.net.caoyao.cpzshandset.service.bll.UnPackBll;
import cn.net.caoyao.cpzshandset.service.bll.UploadStatusBll;
import cn.net.caoyao.cpzshandset.service.bll.config.ConfigBll;
import cn.net.caoyao.cpzshandset.service.presenter.UnpackConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.UnpackConstactImpl;
import cn.net.caoyao.cpzshandset.service.thread.ThreadPoolManager;
import cn.net.caoyao.cpzshandset.service.thread.impl.common.CommonSubmitUnpackThread;
import cn.net.caoyao.cpzshandset.ui.adapter.UnpackHisListAdapter;
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 CommonEggUnpackPresenter extends UnpackConstactImpl{
	private final UnpackConstact.View pView;
	private Context context;
	private List<UnpackBean> unpacks = new ArrayList<>();
	private UnpackHisListAdapter adapter;
	private UnPackBll bll;
	private UploadStatusBll uploadStatusBll;
	private TipsDialog tipsDialog;
	private ConfigBll configBll;
	private ProgressDialog bProgressDialog = null;
	private int handset_version = HandsetVersionConstant.HANDSET_UNIVERSAL_EGG_VERSION_MODE;
	
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case PhoneScanner.BARCODE_ERR_LABEL:
			case PhoneScanner.BARCODE_READ:
				if (!checkViewAvailable())
					return;
//				PhoneCilicoSoundUtils.play();
				scannerSuccess(msg.obj.toString());
				break;
			case PhoneScanner.BARCODE_NOREAD:
				if (checkViewAvailable()) {
					pView.showMsgToast("取消扫描", Toast.LENGTH_SHORT);
				}
				break;
			case RequestConstant.REQUEST_FAIL:
				//请求失败
				if (!checkViewAvailable())return;
				dismissProgress();
				pView.showMsgToast("请求失败！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT:
				//超时
				if (!checkViewAvailable())return;
				dismissProgress();
				pView.showMsgToast("请求超时！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_PROT01_LOGIN_FAIL:
				//登录失败
				if (!checkViewAvailable())return;
				dismissProgress();
				String errorMsg = msg.obj.toString();
				int errorCode = msg.arg1;
				pView.showMsgToast(errorMsg + errorCode, Toast.LENGTH_SHORT);
				break;
			case RequestConstant.SUBMIT_ALL_UNPACK_COMPLETE:
				if (!checkViewAvailable())return;
				dismissProgress();
				pView.showMsgToast("所有拆包数据提交完成", Toast.LENGTH_SHORT);
				unpacks = bll.queryAllUnPackList();
				adapter.refreshData(unpacks);
				break;
			}
		}

	};
	private void scannerSuccess(String str) {
		LogUtil.d(TConfig.Echo, "scannerRecuess：" + str);
		pView.vibrate(100);
		if (StringUtils.isEmpty(str)) {
			pView.showMsgToast("扫描标签不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		if (!StringUtils.isNumber(str)) {
			pView.showMsgToast("您所扫描的不是中国追溯的合法标签！", Toast.LENGTH_SHORT);
			return;
		}
		if (!(str.length() == 16)) {
			pView.showMsgToast("您所扫描的不是中国追溯的合法标签！", Toast.LENGTH_SHORT);
			return;
		}
		
		if (bll.hasExistUnpackLabel(str)) {
			String tips = "本地已经存在未上传的拆包标签：\n" + str;
			showIKnowTipsDialog(tips);
			return;
		}
		
		bll.insertUnpack(new UnpackBean(str));
		unpacks = bll.queryAllUnPackList();
		adapter.refreshData(unpacks);
		
		
	};
	public CommonEggUnpackPresenter(UnpackConstact.View pView,Context context) {
		this.pView = pView;
		this.context = context;
		start();
	}

	@Override
	public void start() {
		if (!checkViewAvailable()) return;
		bll = new UnPackBll(context);
		uploadStatusBll = new UploadStatusBll(context);
		configBll = new ConfigBll(context);
		pView.setPageTitle("拆包");
		pView.setMoreOptionStr("上传");
		unpacks = bll.queryAllUnPackList();
		adapter = new UnpackHisListAdapter(unpacks);
		pView.setAdapter(adapter);
	}
	private void showIKnowTipsDialog(String tips) {
		if (tipsDialog == null) {
			tipsDialog = new TipsDialog(context);
		}
		tipsDialog.show();
		tipsDialog.setWarnView("提示", tips, true, null);
	}
	@Override
	public boolean checkViewAvailable() {
		boolean b = false;
		if (pView != null && context != null) {
			b=true;
		}
		return b;
	}

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


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

	@Override
	public void uploadClick() {
		if (!checkViewAvailable()) return;
		ConfigBean configBean = configBll.queryConfigByHandsetMode(handset_version);
		if (configBll == null) {
			pView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
			return;
		}
		if (unpacks.size() <= 0){
			pView.showMsgToast("当前的拆包单还没有标签，不能上传", Toast.LENGTH_SHORT);
			return;
		}
		if (!NetWorkUtils.isNetworkConnected(context)) {
			DialogUtils.showSetNetDialog(context);
			return;
		}
		
		showProgressDialog("提示", "正在提交激活信息，请稍后……");
		long deviceId = Long.parseLong(ReadDeviceIDUtil.readScanDecrypt(configBean.getDeviceId()));
		ThreadPoolManager.getThreadPool().execute(new CommonSubmitUnpackThread(mHandler, deviceId, bll,uploadStatusBll));
	}
	
	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 onItemClickLinstener(int position) {
		if (unpacks.size() > 0) {
			String tipsContent = "确认删除拆包标签：\n" + unpacks.get(position).getLabel_id();
			showDelTipsDialog(position, tipsContent);
		}
		
	}
	
	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() {
				UnpackBean b = unpacks.get(position);
				bll.deleteUnpackById(b);
				unpacks = bll.queryAllUnPackList();
				adapter.refreshData(unpacks);
			}
		});
	}

	@Override
	public void onItemLongClickListener(int position) {
		// TODO Auto-generated method stub
		
	}

}
