package com.simuwang.base.components;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.simuwang.base.mapper.system.SysUserMapper;
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 org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author wangzaijun
 * @date 2024/9/13 17:08
 * @description 用户权限服务
 */
@Service
public class UserAuthService {
    private final SysUserMapper userMapper;

    public UserAuthService(SysUserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 根据用户账号获取用户信息
     *
     * @param username 用户账号
     * @return /
     */
    public SysUserDO getUserInfoByUsername(String username) {
        LambdaQueryWrapper<SysUserDO> wrapper = Wrappers.lambdaQuery(SysUserDO.class)
                .eq(SysUserDO::getUserName, username);
        return this.userMapper.selectOne(wrapper);
    }

    /**
     * 根据用户id获取角色权限列表
     *
     * @param userId 用户id
     * @return /
     */
    public List<SysRoleDO> listUserRoleByUserId(Integer userId) {
        boolean admin = this.isAdmin(userId);
        if (admin) {
            return this.userMapper.selectAllRole();
        }
        return this.userMapper.selectRoleByUserId(userId);
    }

    /**
     * 根据用户id获取菜单列表
     *
     * @param userId 用户id
     * @return /
     */
    public List<SysMenuDO> listUserMenuByUserId(Integer userId) {
        boolean admin = this.isAdmin(userId);
        if (admin) {
            return this.userMapper.selectAllMenu();
        }
        return this.userMapper.selectMenuByUserId(userId);
    }

    /**
     * 判断用户是否超级管理员
     * 1、如果用户id为0或者1则为超级管理员
     * 2、或者用户有system和admin角色
     *
     * @param userId 用户id
     * @return /
     */
    private boolean isAdmin(Integer userId) {
        if (Objects.equals(0, userId) || Objects.equals(1, userId)) {
            return true;
        }
        List<SysRoleDO> roles = this.userMapper.selectRoleByUserId(userId);
        SysRoleDO adminRole = roles.stream()
                .filter(e -> "system".equalsIgnoreCase(e.getRoleKey()) || "admin".equalsIgnoreCase(e.getRoleKey()))
                .findFirst().orElse(null);
        return adminRole != null;
    }
}
