package com.org.system.service;

import com.org.system.config.security.Md5PasswordEncoder;
import com.org.system.entity.LoginUser;
import com.org.system.entity.SysUser;
import com.org.utils.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
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;

/**
 * 用户验证处理
 *
 */
@Service
public class CustomUserService implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(CustomUserService.class);

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // SysUser user = sysUserService.findByUserName(username);
        SysUser user = sysUserService.findByUserNameOrPhone(username);
        if (user == null) {
            log.info("登录用户：{} 不存在.", username);
            // throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
            throw new InternalAuthenticationServiceException("登录用户：" + username + " 不存在");
        } else if (1 == user.getIsDelete()) {
            log.info("登录用户：{} 已被删除.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        } else if (0 == user.getStatus()) {
            log.info("登录用户：{} 已被停用.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        Md5PasswordEncoder.getInstance().setSalt(user.getSalt());
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        // 这里可以查询用户权限放入 LoginUser 内
        return new LoginUser().setUser(user);
    }
}
