package cn.net.caoyao.cpzshandset.service.presenter.impl.login.ythScanner;

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.common.config.Config;
import cn.net.caoyao.cpzshandset.common.config.RequestConstant;
import cn.net.caoyao.cpzshandset.common.util.CacheGet;
import cn.net.caoyao.cpzshandset.common.util.CachePut;
import cn.net.caoyao.cpzshandset.common.util.DateUtil;
import cn.net.caoyao.cpzshandset.common.util.MD5;
import cn.net.caoyao.cpzshandset.common.util.NetWorkUtils;
import cn.net.caoyao.cpzshandset.common.util.StringUtils;
import cn.net.caoyao.cpzshandset.service.bll.UserLoginBll;
import cn.net.caoyao.cpzshandset.service.presenter.LoginConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.LoginConstactImpl;
import cn.net.caoyao.cpzshandset.service.thread.ThreadPoolManager;
import cn.net.caoyao.cpzshandset.service.thread.ThreadReqTools;
import cn.net.caoyao.cpzshandset.service.thread.impl.ythScanner.YthScannerReqUserInfoRunable;
import cn.net.caoyao.cpzshandset.ui.activity.HomeActivity;
import cn.net.caoyao.cpzshandset.ui.weight.DialogUtils;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20020ResBean;
import cn.net.cpzslibs.prot.handset.bean.res.ResponsibleUserInfoBean;

public class YthScannerLoginPresenter extends LoginConstactImpl{
	private final LoginConstact.View loginView;
	private Context context;
	private CacheGet cacheG = new CacheGet();
	private CachePut cacheP = new CachePut();
	private UserLoginBll loginBll;
	private ProgressDialog bProgressDialog = null;
	private long defaultDevicedId = 1000022L;
	
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case RequestConstant.REQUEST_FAIL:
				//请求失败
				if (!checkViewAvailable())return;
				dismissProgress();
				loginView.showMsgToast("请求失败！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT:
				//超时
				if (!checkViewAvailable())return;
				dismissProgress();
				loginView.showMsgToast("请求超时！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_PROT01_LOGIN_FAIL:
				//登录失败
				if (!checkViewAvailable())return;
				dismissProgress();
				String errorMsg = msg.obj.toString();
				int errorCode = msg.arg1;
				loginView.showMsgToast(errorMsg + errorCode, Toast.LENGTH_SHORT);
				break;
			case RequestConstant.PROT_REQ_USERINFO_20020_NO_DATA:
				//无用户信息
				if (!checkViewAvailable()) return;
				dismissProgress();
				loginView.showMsgToast("请求成功，但未获取到用户信息，请确认是否在后台注册过用户数据",Toast.LENGTH_SHORT);
				break;
			case RequestConstant.PROT_REQ_USERINFO_20020_FAIL:
				//请求用户信息失败
				if (!checkViewAvailable()) return;
				dismissProgress();
				Prot20020ResBean resBean = (Prot20020ResBean) msg.obj;
				if (resBean != null) {
//					res = resBean.getErrmsg()+resBean.getErrcode();
					loginView.showMsgToast(ThreadReqTools.getErrorMsg(resBean.getErrcode()) +"错误码："+ resBean.getErrcode(),Toast.LENGTH_SHORT);
				} else {
					loginView.showMsgToast("请求用户配置信息失败!",Toast.LENGTH_SHORT);
				}
				break;
			case RequestConstant.PROT_REQ_USERINFO_20020_SUCCESS:
				//请求用户信息成功
				if (!checkViewAvailable()) return;
				dismissProgress();
				loginView.showMsgToast("用户配置信息更新成功",Toast.LENGTH_SHORT);
				saveUserConfigUpdateDate();
				break;
				
			}
		};
	};
	
	public YthScannerLoginPresenter(LoginConstact.View loginView,Context context) {
		this.loginView = loginView;
		this.context = context;
		loginBll = new UserLoginBll(context);
		start();
	}


	@Override
	public void start() {
		if(!checkViewAvailable()) return;
		loginView.setUpdateBtnVisibility(View.VISIBLE);
		loginView.setBottomTipsVisibility(View.VISIBLE);
		setUpdateDate();
		
	}

	private void setUpdateDate() {
		String date = cacheG.getCacheStringG(context, Config.configSPName, Config.updateUserConfigDate);
		if (StringUtils.isEmpty(date)) {
			loginView.setBottomTipsStr("当前设备还没有更新过配置信息");
		} else {
			loginView.setBottomTipsStr("上次更新时间：" + date);
		}		
	}

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

	

	@Override
	public void loginClick() {
		if(!checkViewAvailable()) return;
		String account = loginView.getAccountStr();
		String pwd = loginView.getPwdStr();
		if (StringUtils.isEmpty(account)) {
			loginView.showMsgToast("账号不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		if (StringUtils.isEmpty(pwd)) {
			loginView.showMsgToast("密码不能为空！", Toast.LENGTH_SHORT);
			return;
		}
		ResponsibleUserInfoBean uBean = loginBll.queryUserInfoByAccount(account);
		if (uBean == null) {
			loginView.showMsgToast("该用户不存在，请确认账户是否输入有误并且已经注册过，或者更新配置信息重试！", Toast.LENGTH_SHORT);
			return;
		} 
		if (MD5.GetMD5Code(pwd).equals(uBean.getPwd())) {
			//登录成功
			loginView.showMsgToast("登录成功", Toast.LENGTH_SHORT);
			Intent intent = new Intent(context, HomeActivity.class);
			intent.putExtra("userInfo", uBean);
			context.startActivity(intent);
			loginView.finishPage();
		} else {
			loginView.showMsgToast("密码输入错误", Toast.LENGTH_SHORT);
		}
	}

	@Override
	public void updateBtnClick() {
		if(!checkViewAvailable()) return;
//		addTestData();
		if (!NetWorkUtils.isNetworkConnected(context)) {
			DialogUtils.showSetNetDialog(context);
			return;
		}
		showProgressDialog("提示", "正在请求用户配置信息，请稍后……");
		ThreadPoolManager.getThreadPool().execute(new YthScannerReqUserInfoRunable(mHandler, defaultDevicedId, loginBll));
	}
	
	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 void addTestData() {
		List<ResponsibleUserInfoBean> beans = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			ResponsibleUserInfoBean b = new ResponsibleUserInfoBean();
			b.setAccount("10001" + i);
			b.setUsername("测试用户-" + i);
			b.setPwd(MD5.GetMD5Code("123456"));
			b.setUserType(0);
			beans.add(b);
		}
		ResponsibleUserInfoBean b = new ResponsibleUserInfoBean();
		b.setAccount("10001");
		b.setUsername("大权限用户");
		b.setPwd(MD5.GetMD5Code("123456"));
		b.setUserType(1);
		beans.add(b);
		loginBll.deleteAllUserInfo();
		loginBll.insertUserInfoList(beans);
		saveUserConfigUpdateDate();
	}*/

	private void saveUserConfigUpdateDate() {
		String updateDate = DateUtil.getDateTime(System.currentTimeMillis());
		cacheP.putCacheStringG(context, Config.configSPName, Config.updateUserConfigDate, updateDate);
		loginView.setBottomTipsStr("本次更新时间：" + updateDate);
	}

}
