package com.jiayue.ssi.service.impl;


import com.jiayue.ssi.entity.SysPolicy;
import com.jiayue.ssi.service.SysPolicyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.mapper.SysUserMapper;

/**
 * 用户登录查询
 *
 * @author xsl
 * @version 3.0
 */
@Service
@Slf4j
public class UserServiceImpl implements UserDetailsService {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysPolicyService sysPolicyService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("username", username));
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名错误！");
        } else {
            SysPolicy sysPolicy = sysPolicyService.getOne(new QueryWrapper<>());
            // 锁定时长
            int lockedTime = sysPolicy.getLoginLock()*1000*60;
            if (sysUser.getStatus().equals("1") && (System.currentTimeMillis() - sysUser.getLockTime()) < lockedTime) {
                sysUser.setPassword("1");
            }
            if (sysUser.getStatus().equals("2")) {
                sysUser.setPassword("1");
            }
        }
        return sysUser;
    }
}
