package com.trade.client.enterprise.customer.service.impl;

import java.util.concurrent.TimeUnit;

import com.trade.client.enterprise.customer.domain.CustomerUser;
import com.trade.client.enterprise.customer.service.CustomerPasswordService;
import com.trade.common.constant.HttpStatus;
import com.trade.common.exception.ServiceException;
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 com.trade.common.constant.CacheConstants;
import com.trade.common.context.AuthenticationContextHolder;

import com.trade.common.redis.RedisCache;
import com.trade.common.security.EncryptUtils;

/**
 * @description: 客户密码服务类
 * @Author: wanglang
 * @Date: 2024-04-02 10:18
 * @Version: 1.0
 */
@Service
public class CustomerPasswordServiceImpl implements CustomerPasswordService {

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

    @Override
    public void validate(CustomerUser user) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();
        Long retryCount = redisCache.getCacheObject(getCacheKey(username));
        if (retryCount == null) {
            retryCount = 0L;
        }
        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
            String msg = "密码输入错误" + maxRetryCount + "，帐户锁定" + lockTime + "分钟";
            throw new ServiceException(msg, HttpStatus.BAD_REQUEST);
        }
        if (!matches(user, password)) {
            retryCount = retryCount + 1;
            redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new ServiceException("用户不存在或密码错误", HttpStatus.BAD_REQUEST);
        } else {
            clearLoginRecordCache(username);
        }
    }

    @Override
    public boolean matches(CustomerUser 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;
    }
}
