package com.xunmei.auth.service;

import com.xunmei.common.core.constant.CacheConstants;
import com.xunmei.common.core.constant.Constants;
import com.xunmei.common.core.exception.ServiceException;
import com.xunmei.common.redis.utils.RedisUtils;
import com.xunmei.common.security.utils.SecurityUtils;
import com.xunmei.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * 登录密码方法
 *
 * @author xunmei
 */
@Component
public class SysPasswordService
{

    private int maxRetryCount = CacheConstants.PASSWORD_MAX_RETRY_COUNT;

    private Long lockTime = CacheConstants.PASSWORD_LOCK_TIME;

    @Autowired
    private SysRecordLogService recordLogService;

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

    public void validate(SysUser user, String password,String platformType)
    {
        String username = user.getUsername();

        Integer retryCount =RedisUtils.getCacheObject(getCacheKey(username));
        //Integer retryCount = redisService.getCacheObject(getCacheKey(username));

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

        if (retryCount >= Integer.valueOf(maxRetryCount).intValue())
        {
            String errMsg = String.format("密码输入错误%s次，帐户锁定%s分钟", maxRetryCount, lockTime);
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL,errMsg,platformType);
            throw new ServiceException(errMsg);
        }

        if (!matches(user, password))
        {
            retryCount = retryCount + 1;
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, String.format("密码输入错误%s次", retryCount),platformType);
            RedisUtils.setCacheObject(getCacheKey(username), retryCount, Duration.ofMinutes(lockTime));
            //redisService.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new ServiceException("用户不存在/密码错误");
        }
        else
        {
            clearLoginRecordCache(username);
        }
    }

    public boolean matches(SysUser user, String rawPassword)
    {
        return SecurityUtils.isEquals(user.getPassword(), rawPassword,user.getSalt());
    }


    public void clearLoginRecordCache(String loginName)
    {
        RedisUtils.deleteObject(getCacheKey(loginName));
        /*if (redisService.hasKey(getCacheKey(loginName)))
        {
            redisService.deleteObject(getCacheKey(loginName));
        }*/
    }
}
