package com.sunyard.config.security;

import cn.hutool.core.util.StrUtil;
import com.sunyard.ssp.common.constant.CommonConstant;
import com.sunyard.ssp.common.exception.LoginFailLimitException;
import com.sunyard.ssp.modules.user.entity.ScUser;
import com.sunyard.ssp.modules.user.service.IScPermissionService;
import com.sunyard.ssp.modules.user.service.IScUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

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

/**
 * @author Exrickx
 */
@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService{

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IScUserService userService;

    @Autowired
    private IScPermissionService permissionService;

    @Value("${ssp.passMaxDays}")
    private Integer passMaxDays;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        long begin = System.currentTimeMillis();
        String flagKey = "loginFailFlag:" + username;
        String value = redisTemplate.opsForValue().get(flagKey);

        if(StrUtil.isBlank(username)){
            return new SecurityUserDetails(null);
        }

        //通过用户名登陆
        ScUser user = userService.findByUsername(username);

        if(user == null){
            return new SecurityUserDetails(null);
        }

        //admin特殊处理
        if(CommonConstant.DEFAULT_USER_ROOT_ID.equals(user.getId())){
            Long timeRest = redisTemplate.getExpire(flagKey, TimeUnit.SECONDS);
            Double minutes = Math.ceil(Double.valueOf(timeRest)/60);
            if(StrUtil.isNotBlank(value)){
                //超过限制次数
                throw new LoginFailLimitException("登录错误次数超过限制，请"+minutes.intValue()+"分钟后再试");
            }
            return new SecurityUserDetails(user);
        }

        //密码过期日
        LocalDateTime passLimitDate = LocalDateTime.now().minusDays(passMaxDays);
        if(passLimitDate.isAfter(user.getPassUpdateTime())){
            throw new LoginFailLimitException("密码已过期,请联系管理员修改后重试");
        }

        return new SecurityUserDetails(user);
    }
}
