package com.securitycontrol.auth.service;

import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.securitycontrol.common.core.constant.CacheConstants;
import com.securitycontrol.common.core.constant.Constants;
import com.securitycontrol.common.core.exception.ServiceException;
import com.securitycontrol.common.redis.service.RedisService;
import com.securitycontrol.common.security.utils.SecurityUtils;
import com.securitycontrol.system.api.domain.SysUser;

import javax.annotation.Resource;

/**
 * 登录密码方法
 *
 * @author czc
 */
@Component
public class SysPasswordService
{
    @Resource
    private RedisService redisService;

    public  int ERROR_TIMES=5;

    public  int LOCK_TIMES=5*60;

    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)
    {
        long startTime = System.currentTimeMillis();
        String username = user.getNickName();
        Integer retryCount=redisService.getIntVal(username);
        if(retryCount>ERROR_TIMES){
            long time=redisService.getExpireTimes(username);
            recordLogService.recordLogininfor(username,user.getUserId(),"用户登录","账号被锁定",1,0,"username="+username,startTime);
            throw new ServiceException("账号已锁定,请"+time+"分钟后重试",201);
        }else{
            if (!matches(user, password)) {
                retryCount = retryCount + 1;
                recordLogService.recordLogininfor(username,user.getUserId(),"用户登录", String.format("密码输入错误%s次", retryCount),1,0,"username="+username,startTime);
                redisService.set(username, retryCount, LOCK_TIMES);
                throw new ServiceException("用户不存在/密码错误",201);

            } else {
             //   redisService.deleteObject(username);
                clearLoginRecordCache(username);
            }
        }

    }

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

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