package com.cool.bang.core.secure.domain;

import com.cool.bang.modules.system.domain.po.Menu;
import com.cool.bang.modules.system.domain.po.User;
import com.cool.bang.modules.system.mapper.MenuMapper;
import com.cool.bang.modules.system.mapper.UserMapper;
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 javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 实现{@link UserDetailsService}接口，重写{@link #loadUserByUsername}方法
 *
 * Spring Security 登录用户验证实现类，使用登录用户名查询数据库是否存在，
 * 密码验证由spring security内部实现验证
 *
 * @author PeiZhi Guo
 * 2021-2-18 14:10
 */
@Component
public class SecureUserService implements UserDetailsService {

    private static final long LOCK_TIME = 1000 * 60 * 10;

    @Resource
    private UserMapper sysUserMapper;

    @Resource
    private MenuMapper sysMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User sysUser = sysUserMapper.selectByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("账户密码错误");
        }
        if (sysUser.getLock() == 0) {
            long lockTime = sysUser.getLastLoginTime().getTime() + LOCK_TIME;
            long currentTime = new Date().getTime();
            if (currentTime > lockTime) {
                sysUserMapper.updateLoginInfo(sysUser.getUsername(), 0);
                sysUser.setLock(1);
            } else {
                long min = (lockTime - currentTime) / 1000 /60 + 1;
                throw new UsernameNotFoundException("账户已锁定，请" + min + "分钟后重试");
            }
        }
        List<Menu> menuList = sysMenuMapper.selectByUsername(username);
        sysUser.setMenuList(menuList);
        return sysUser;
    }
}
