package com.simuwang.base.components;

import com.simuwang.base.pojo.dos.sys.SysMenuDO;
import com.simuwang.base.pojo.dos.sys.SysRoleDO;
import com.simuwang.base.pojo.dos.sys.SysUserDO;
import com.simuwang.shiro.core.ShiroUser;
import com.simuwang.shiro.core.adapter.LoginAuthAdapter;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangzaijun
 * @date 2024/9/12 19:11
 * @description 自定义的登录认证适配器实现，从数据库获取数据并且bean注入要调整为当前实现
 */
public record ShiroLoginAuthAdapter(UserAuthService userAuthService) implements LoginAuthAdapter {
    @Override
    public ShiroUser findUserByUsername(String username) {
        SysUserDO userInfo = this.userAuthService.getUserInfoByUsername(username);
        ShiroUser sysUser = new ShiroUser();
        sysUser.setUserId(userInfo.getUserId());
        sysUser.setUsername(userInfo.getUserName());
        sysUser.setPassword(userInfo.getPassword());
        sysUser.setStatus(userInfo.getStatus());
        return sysUser;
    }

    @Override
    public List<String> findRoleByUserId(Integer userId) {
        List<SysRoleDO> roles = this.userAuthService.listUserRoleByUserId(userId);
        return roles.stream().map(SysRoleDO::getRoleKey).distinct().collect(Collectors.toList());
    }

    @Override
    public List<String> findPermissionsByUserId(Integer userId) {
        List<SysMenuDO> menus = this.userAuthService.listUserMenuByUserId(userId);
        return menus.stream().map(SysMenuDO::getPerms).distinct().collect(Collectors.toList());
    }
}
