package com.trade.admin.system.service.impl;

import com.trade.admin.system.domain.entity.SysUser;
import com.trade.admin.system.service.ISysPasswordService;
import com.trade.common.constant.CacheConstants;
import com.trade.common.constant.Constants;
import com.trade.common.context.AuthenticationContextHolder;
import com.trade.common.exception.UserException;
import com.trade.common.redis.RedisCache;
import com.trade.common.security.EncryptUtils;
import com.trade.common.utils.MessageUtils;
import com.trade.admin.manager.AsyncManager;
import com.trade.admin.manager.factory.AsyncFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @Author: wanglang
 * @Date: 2023/7/27 11:01
 * @Version: 1.0
 */
@Service
public class SysPasswordServiceImpl implements ISysPasswordService {

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

    @Override
    public void validate(SysUser user) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();
        Integer retryCount = redisCache.getCacheObject(getCacheKey(username));
        if (retryCount == null) {
            retryCount = 0;
        }
        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                    MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime)));
            throw new UserException("user.password.retry.limit.exceed", new Object[] {
                    maxRetryCount, lockTime
            });
        }
        if (!matches(user, password)) {
            retryCount = retryCount + 1;
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                    MessageUtils.message("user.password.retry.limit.count", retryCount)));
            redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new UserException("user.password.not.match", null);
        } else {
            clearLoginRecordCache(username);
        }
    }

    @Override
    public boolean matches(SysUser user, String rawPassword) {
        return EncryptUtils.matchesPassword(rawPassword, user.getPassword());
    }

    @Override
    public void clearLoginRecordCache(String loginName) {
        if (redisCache.hasKey(getCacheKey(loginName))) {
            redisCache.deleteObject(getCacheKey(loginName));
        }
    }

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