package cn.qinys.platform.base.service;


import cn.qinys.platform.base.exceptions.BizException;
import cn.qinys.platform.base.redis.RedisKeyEnum;
import cn.qinys.platform.base.security.utils.CurrentUtils;
import cn.qinys.platform.base.utils.RedisUtils;
import cn.qinys.platform.base.vo.LoginUserInfo;
import jakarta.annotation.Resource;
import org.springframework.util.StringUtils;



/**
 * Description:
 *
 * @author tanlie
 * Date: 2024/3/8 8:26
 */
public abstract class AbstractLoginService {

    /**
     * 每天失败尝试次数
     */
    protected int failTries = 5;

    @Resource
    RedisUtils redisUtils;

    /**
     * 登录用户信息
     *
     * @param userInfo
     * @param token
     */
    protected void setLoginUserInfo(LoginUserInfo userInfo, String token) {
        CurrentUtils.setCurrentUserInfo(userInfo, token);
    }

    /**
     * 失败次数校验
     *
     * @param account
     */
    protected void checkFailCount(String account) {
        String failKey = RedisKeyEnum.LOGIN_FAIL.getCode() + account;
        Integer failCount = (Integer) redisUtils.get(failKey);
        if (failCount != null && failCount >= failTries) {
            throw new BizException("失败尝试次数太多，请24小时后再重试。");
        }
    }

    /**
     * 记录失败次数
     *
     * @param account
     */
    protected void setFailCount(String account) {
        String failKey = RedisKeyEnum.LOGIN_FAIL.getCode() + account;
        Integer failCount = (Integer) redisUtils.get(failKey);
        failCount = failCount == null ? 1 : (failCount + 1);
        redisUtils.set(failKey, failCount, RedisKeyEnum.LOGIN_FAIL.getExpireTime());
    }

    /**
     * 踢人下线
     *
     * @param account
     */
    protected void kicKOut(String account) {
        String token = (String) redisUtils.get(RedisKeyEnum.CURRENT_USER_TOKEN.getCode() + account);
        if (StringUtils.hasLength(token)) {
            redisUtils.delete(RedisKeyEnum.CURRENT_USER.getCode() + token);
        }
        redisUtils.delete(RedisKeyEnum.CURRENT_USER_TOKEN.getCode() + account);
    }

    /**
     * 记录token
     *
     * @param account
     * @param token
     */
    protected void recordToken(String account, String token) {
        redisUtils.set(RedisKeyEnum.CURRENT_USER_TOKEN.getCode() + account, token, RedisKeyEnum.CURRENT_USER_TOKEN.getExpireTime());
    }

}
