package com.zhyc.framework.web.service;

import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.zhyc.common.constant.CacheConstants;
import com.zhyc.common.core.domain.entity.SysUser;
import com.zhyc.common.core.redis.RedisCache;
import com.zhyc.common.exception.user.UserPasswordNotMatchException;
import com.zhyc.common.exception.user.UserPasswordRetryLimitExceedException;
import com.zhyc.common.utils.SecurityUtils;
import com.zhyc.framework.security.context.AuthenticationContextHolder;

/**
 * 系统密码服务类，用于处理登录密码验证相关的业务逻辑，包括密码错误次数限制、账户锁定等功能
 *
 * @author ruoyi
 */
@Component
public class SysPasswordService
{
    @Autowired
    private RedisCache redisCache;

    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    @Value(value = "${user.password.lockTime}")
    private int lockTime;

    /**
     * 构建登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username)
    {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    /**
     * 验证用户登录信息，包括密码匹配验证和错误次数限制检查
     *
     * @param user 待验证的系统用户对象
     * @throws UserPasswordRetryLimitExceedException 当密码错误次数超过限制时抛出异常
     * @throws UserPasswordNotMatchException 当密码不匹配时抛出异常
     */
    public void validate(SysUser user)
    {
        // 获取当前认证的用户名和密码
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();

        // 从Redis缓存中获取该用户的密码错误次数
        Integer retryCount = redisCache.getCacheObject(getCacheKey(username));

        if (retryCount == null)
        {
            retryCount = 0;
        }

        // 检查是否达到最大重试次数限制
        if (retryCount >= Integer.valueOf(maxRetryCount).intValue())
        {
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }

        // 验证密码是否匹配
        if (!matches(user, password))
        {
            // 密码不匹配时，增加错误次数并更新缓存
            retryCount = retryCount + 1;
            redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new UserPasswordNotMatchException();
        }
        else
        {
            // 密码匹配成功，清除登录记录缓存
            clearLoginRecordCache(username);
        }
    }

    /**
     * 验证原始密码与用户存储密码是否匹配
     *
     * @param user 系统用户对象
     * @param rawPassword 原始密码字符串
     * @return 密码匹配返回true，否则返回false
     */
    public boolean matches(SysUser user, String rawPassword)
    {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }

    /**
     * 清除指定登录名的登录记录缓存
     *
     * @param loginName 登录用户名
     */
    public void clearLoginRecordCache(String loginName)
    {
        if (redisCache.hasKey(getCacheKey(loginName)))
        {
            redisCache.deleteObject(getCacheKey(loginName));
        }
    }
}
