package com.yfd.platform.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yfd.platform.datasource.DataSource;
import com.yfd.platform.system.domain.LoginUser;
import com.yfd.platform.system.domain.SysUser;
import com.yfd.platform.system.mapper.SysMenuMapper;
import com.yfd.platform.system.service.IUserService;
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 javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 用户服务实现类  继承UserDetailsService  实现接口
 * </p>
 *
 * @author zhengsl
 * @since 2021-10-27
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private IUserService userService;

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    @DataSource(name = "master")
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名称查询用户信息
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        SysUser user = userService.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(user)) {
            throw new RuntimeException("用户账号不存在！");
        }
        //Todo 根据用户查询权限信息 添加到LoginUser中
        List<String> permissions =
                sysMenuMapper.selectPermsByUserId(user.getId());

        //封装成UserDetails对象返回
        return new LoginUser(user,permissions);
    }
}
