package cc.smtweb.system.bpm.web.login;

import cc.smtweb.framework.core.cache.redis.RedisManager;
import cc.smtweb.framework.core.common.SwConsts;
import cc.smtweb.framework.core.common.SwEnum;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.exception.BizException;
import cc.smtweb.framework.core.session.UserSession;
import cc.smtweb.system.bpm.web.common.BpmConst;
import cc.smtweb.system.bpm.web.common.BpmEnum;
import cc.smtweb.system.bpm.web.sys.user.user.User;
import cc.smtweb.system.bpm.web.sys.user.user.UserCache;
import cc.smtweb.system.bpm.web.sys.user.user.UserParty;
import cc.smtweb.system.bpm.web.sys.user.user.UserPartyCache;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: AKhh
 * Date: 12-12-23 下午10:12
 * 登录辅助类
 */
public class LoginHelper {
    private static final String PWD_SALT = "goodpj";

    public static User login(LoginVO loginPO) {
        String key = loginPO.getUuid() + "_" + SwConsts.LOGIN_VERIFY_CODE;
        //先提取验证码
        String verifyCode = RedisManager.getInstance().get(key, String.class);
        RedisManager.getInstance().del(key);
        MappingUserParam mappingUserEvent = new MappingUserParam();
        if (StringUtils.isBlank(loginPO.getUsername())) {
            throw new BizException("账号不能为空");
        }
        if(!SwConsts.SysParam.SYS_DEBUG){
            if (StringUtils.isBlank(loginPO.getPassword())) {
                throw new BizException("密码不能为空");
            }

            if (StringUtils.isBlank(loginPO.getVerifyCode())) {
                throw new BizException("验证码不能为空");
            }

            if (!loginPO.getVerifyCode().equalsIgnoreCase(verifyCode)) {
                throw new BizException("验证码错误");
            }
        }

        //查询数据库
        List<User> userObjList = DbEngine.getInstance().findDao(User.ENTITY_NAME).queryWhere(" sur_nicky=? or sur_tel=?", new Object[]{loginPO.getUsername(), loginPO.getUsername()});
//        User user = UserCache.getInstance().getByKey(loginPO.getUsername());
        if (null == userObjList || userObjList.size() <= 0) {
            throw new BizException("账号或者密码出错");
        }
        User user = userObjList.get(0);
//        if (user == null) {
//            throw new BizException("账号或者密码出错");
//        }
        if(!SwConsts.SysParam.SYS_DEBUG){
            if (!verifyPwd(user, loginPO.getPassword())) {
                throw new BizException("账号或者密码出错");
            }

            if (BpmEnum.UserStatu.NORMAL.value != user.getStatu()) {
                throw new BizException("账户状态异常");
            }
        }
        return user;
    }

    public static UserSession simpleLogin(long useId) {
        User user = UserCache.getInstance().get(useId);
        if (user == null) {
            throw new BizException("账号或者密码出错");
        }
        return createUserSession(user);
    }
    public static UserSession createUserSession(User user){
        UserSession us = new UserSession(user.getId());
        Set<UserParty> ups = UserPartyCache.getInstance().getByUser(String.valueOf(us.getUserId()));
        if(ups!=null&&ups.size()>0){
           UserParty up = ups.iterator().next();
           us.setPartyId(up.getPartyId());
           us.setDeptId(up.getDeptId());
           us.setUserLevel(user.getLevel());
        }
        return us;
    }

//    public static UserSession login(LoginVO loginPO) {
//        String key = loginPO.getUuid() + "_" + SwConsts.LOGIN_VERIFY_CODE;
//        //先提取验证码
//        String verifyCode = RedisManager.getInstance().get(key, String.class);
//        RedisManager.getInstance().del(key);
//
//        if (StringUtils.isBlank(loginPO.getUsername())) {
//            throw new BizException("账号不能为空");
//        }
//
//        if ("admin".equals(loginPO.getUsername())) {
//            return new UserSession(1);
//        }
//
//        if (StringUtils.isBlank(loginPO.getPassword())) {
//            throw new BizException("密码不能为空");
//        }
//
//        if (StringUtils.isBlank(loginPO.getVerifyCode())) {
//            throw new BizException("验证码不能为空");
//        }
//
//        if (!loginPO.getVerifyCode().equalsIgnoreCase(verifyCode)) {
//            throw new BizException("验证码错误");
//        }
//
//        //查询数据库
//        List<User> userObjList = DbEngine.getInstance().findDao(User.ENTITY_NAME).queryWhere(" sur_code=? or sur_tel=?", loginPO.getUsername(), loginPO.getUsername());
////        User user = UserCache.getInstance().getByKey(loginPO.getUsername());
//        if(null == userObjList || userObjList.size()<=0){
//            throw new BizException("账号或者密码出错");
//        }
//        User user =userObjList.get(0);
////        if (user == null) {
////            throw new BizException("账号或者密码出错");
////        }
//
//        if (!verifyPwd(user, loginPO.getPassword())) {
//            throw new BizException("账号或者密码出错");
//        }
//
//        if (BpmEnum.UserStatu.NORMAL.value != user.getStatu()) {
//            throw new BizException("账户状态异常");
//        }
//
//        return new UserSession(user.getId());
//    }


    //密码加密(登录时以密文比较)
    public static String encodePwd(long user_id, String pwd) {
        return DigestUtils.md5Hex(PWD_SALT + user_id + pwd);
    }

    public static boolean verifyPwd(User user, String pwd) {
        return DigestUtils.md5Hex(PWD_SALT + user.getId() + pwd).equals(user.getPwd());
    }

    /**
     * 校验密码是否符合规定
     *
     * @param pwd
     * @throws Exception
     */
    public static void checkPwdLevel(String pwd) throws Exception {
        if (BpmConst.DEF_PWD.equals(pwd)) return;

    }

    public static int checkPwdValid(User user) {

        return 0;
    }

    public static void checkPwdSecurity(String pwd) {

    }
    // 重置密码
    public static void resetUserPwd(User user, String pwd) {
        user.setPwd(LoginHelper.encodePwd(user.getId(), pwd));
        DbEngine.getInstance().findDao(User.ENTITY_NAME).updateEntity(user);
        UserCache.getInstance().put(user);
    }
}
