package com.agileboot.auth.service;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.agileboot.auth.pojo.dto.RegisterBody;
import com.agileboot.auth.properties.CaptchaProperties;
import com.agileboot.auth.properties.UserPasswordProperties;
import com.agileboot.common.core.constant.Constants;
import com.agileboot.common.core.enums.LoginType;
import com.agileboot.common.core.enums.UserType;
import com.agileboot.common.core.exception.BizException;
import com.agileboot.common.redis.utils.RedisUtils;
import com.agileboot.common.satoken.pojo.LoginUser;
import com.agileboot.common.satoken.utils.LoginHelper;
import com.agileboot.system.user.entity.SysUser;
import com.agileboot.system.user.service.ISysUserService;
import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.function.Supplier;

/**
 * 登录校验方法
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class SysLoginService {

    private final UserPasswordProperties userPasswordProperties;
    private final CaptchaProperties captchaProperties;

    private final ISysUserService sysUserService;
//    private final RedisTemplate<String, String> redisTemplate;

    /**
     * 登录校验
     */
    public void checkLogin(LoginType loginType, String tenantId, String username, Supplier<Boolean> supplier) {
        String errorKey = Constants.Cache.PWD_ERR_CNT_KEY + username;
        String loginFail = Constants.LOGIN_FAIL;
        Integer maxRetryCount = userPasswordProperties.getMaxRetryCount();
        Integer lockTime = userPasswordProperties.getLockTime();

        // 获取用户登录错误次数，默认为0 (可自定义限制策略 例如: key + username + ip)
        int errorNumber = ObjectUtil.defaultIfNull(RedisUtils.getCacheObject(errorKey), 0);
        // 锁定时间内登录 则踢出
        if (errorNumber >= maxRetryCount) {
            throw new BizException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
        }

        if (supplier.get()) {
            // 错误次数递增
            errorNumber++;
            RedisUtils.setCacheObject(errorKey, errorNumber, Duration.ofMinutes(lockTime));
            // 达到规定错误次数 则锁定登录
            if (errorNumber >= maxRetryCount) {
                throw new BizException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
            } else {
                // 未达到规定错误次数
                throw new BizException(loginType.getRetryLimitCount(), errorNumber);
            }
        }

        // 登录成功 清空错误次数
        RedisUtils.deleteObject(errorKey);
    }

    /**
     * 退出登录
     */
    public void logout() {
        try {
            LoginUser loginUser = LoginHelper.getLoginUser();
            if (ObjectUtil.isNull(loginUser)) {
                return;
            }
            log.info(JSONObject.toJSONString(loginUser));
        } catch (NotLoginException ignored) {
        } finally {
            try {
                StpUtil.logout();
            } catch (NotLoginException ignored) {
            }
        }
    }

    /**
     * 注册
     */
    public void register(RegisterBody registerBody) {
        String tenantId = registerBody.getTenantId();
        String username = registerBody.getUsername();
        String password = registerBody.getPassword();

        // 校验用户类型是否存在
        String userType = UserType.getUserType(registerBody.getUserType()).getUserType();

        // 验证码开关
        if (captchaProperties.getEnabled()) {
            validateCaptcha(tenantId, username, registerBody.getCode(), registerBody.getUuid());
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setTenantId(tenantId);
        sysUser.setUsername(username);
        sysUser.setNickname(username);
        sysUser.setPassword(BCrypt.hashpw(password));
        sysUser.setUserType(userType);
        sysUser.setClientId(Long.parseLong(registerBody.getClientId()));

        boolean regFlag = sysUserService.registerUserInfo(sysUser);
        if (!regFlag) {
            throw new BizException("user.register.error");
        }
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     */
    public void validateCaptcha(String tenantId, String username, String code, String uuid) {
        String verifyKey = Constants.Cache.CAPTCHA_CODE_KEY + StringUtils.defaultIfBlank(uuid, "");
        String captcha = RedisUtils.getCacheObject(verifyKey);
//        String captcha = redisTemplate.opsForValue().get(verifyKey);
        RedisUtils.deleteObject(verifyKey);
        if (captcha == null) {
            throw new BizException("user.captcha.expire");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new BizException("user.captcha.error");
        }
    }
}
