package com.backendsys.modules.common.config.security.utils;

import cn.hutool.core.convert.Convert;
import com.backendsys.exception.CustException;
import com.backendsys.modules.common.config.redis.utils.RedisUtil;
import com.backendsys.utils.response.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class LockStatusUtil {

    @Autowired
    private RedisUtil redisUtil;

    private Integer TIMEOUT = 1;        // 1分钟内
    private Integer TRIGGER_COUNT = 5;  // 错误5次触发

    /**
     * 判断 1分钟内错误 5次，则出现提示
     */
    public void setLockStatus(String prefix, String suffix) {
        String redisKey = prefix + "-" + suffix;
        String redisValue = redisUtil.getCacheObject(redisKey);
        if (redisValue == null) {
            redisValue = "1";
        } else if (Convert.toInt(redisValue) >= TRIGGER_COUNT) {
            throw new CustException("错误次数过多，为账号安全，请等待" + TIMEOUT + "分钟后重新尝试", ResultEnum.LOCK_CREDENTIALS.getCode());
        } else {
            redisValue = Convert.toStr((Convert.toInt(redisValue) + 1));
        }
        redisUtil.setCacheObject(redisKey, redisValue, TIMEOUT, TimeUnit.MINUTES);
    }
    /**
     * 判断是否处于 5次的错误状态
     */
    public void checkLockStatus(String prefix, String suffix) {
        String redisKey = prefix + "-" + suffix;
        String redisValue = redisUtil.getCacheObject(redisKey);
        if (redisValue != null && Convert.toInt(redisValue) >= TRIGGER_COUNT) {
            throw new CustException("错误次数过多，为账号安全，请等待" + TIMEOUT + "分钟后重新尝试", ResultEnum.LOCK_CREDENTIALS.getCode());
        }
    }

}
