package org.dromara.system.service.impl;

import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.TenantConstants;
import org.dromara.common.core.domain.vo.SysProjectRoleMenuVo;
import org.dromara.common.core.domain.vo.SysProjectRolePermissionVo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.BusProject;
import org.dromara.system.service.IBusProjectService;
import org.dromara.system.service.ISysMenuService;
import org.dromara.system.service.ISysPermissionService;
import org.dromara.system.service.ISysRoleService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户权限处理
 *
 * @author ruoyi
 */
@RequiredArgsConstructor
@Service
public class SysPermissionServiceImpl implements ISysPermissionService {

    private final ISysRoleService roleService;
    private final ISysMenuService menuService;
    private final IBusProjectService projectService;

    /**
     * 获取角色数据权限
     *
     * @param userId 用户id
     * @return 角色权限信息
     */
    @Override
    public List<SysProjectRolePermissionVo> getRolePermission(Long userId) {
        // 管理员拥有所有权限
        if (LoginHelper.isSuperAdmin(userId)) {
            List<SysProjectRolePermissionVo> roles = new ArrayList<>();
            List<BusProject> projects = projectService.list();
            for (BusProject project : projects) {
                SysProjectRolePermissionVo vo = new SysProjectRolePermissionVo();
                Set<String> role = new HashSet<>();
                vo.setProjectId(project.getId());
                role.add(TenantConstants.SUPER_ADMIN_ROLE_KEY);
                vo.setProjectRoles(role);
                roles.add(vo);
            }
            return roles;
        } else {
            return roleService.selectRolePermissionByUserId(userId);
        }
    }

    /**
     * 获取菜单数据权限
     *
     * @param userId 用户id
     * @return 菜单权限信息
     */
    @Override
    public List<SysProjectRoleMenuVo> getMenuPermission(Long userId) {
        // 管理员拥有所有权限
        if (LoginHelper.isSuperAdmin(userId)) {
            List<SysProjectRoleMenuVo> roles = new ArrayList<>();
            List<BusProject> projects = projectService.list();
            for (BusProject project : projects) {
                SysProjectRoleMenuVo vo = new SysProjectRoleMenuVo();
                Set<String> role = new HashSet<>();
                vo.setProjectId(project.getId());
                role.add("*:*:*");
                vo.setProjectPermissions(role);
                roles.add(vo);
            }
            return roles;
        } else {
            return menuService.selectMenuPermsByUserId(userId);
        }
    }
}
