package cn.iocoder.byzs.module.system.controller.admin.permission;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.byzs.framework.common.pojo.CommonResult;
import cn.iocoder.byzs.module.system.controller.admin.permission.vo.permission.*;
import cn.iocoder.byzs.module.system.service.permission.PermissionService;
import cn.iocoder.byzs.module.system.service.permission.RoleService;
import cn.iocoder.byzs.module.system.service.tenant.TenantService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.Set;

import static cn.iocoder.byzs.framework.common.pojo.CommonResult.success;

/**
 * 权限 Controller，提供赋予用户、角色的权限的 API 接口
 *
 * @author 博雅智算源码
 */
@Tag(name = "管理后台 - 权限")
@RestController
@RequestMapping("/system/permission")
public class PermissionController {

    @Resource
    private PermissionService permissionService;
    @Resource
    private TenantService tenantService;
    @Resource
    private RoleService roleService;

    @Operation(summary = "获得角色拥有的菜单编号")
    @Parameter(name = "roleId", description = "角色编号", required = true)
    @GetMapping("/list-role-menus")
    @PreAuthorize("@ss.hasPermission('system:permission:assign-role-menu')")
    public CommonResult<Set<Long>> getRoleMenuList(Long roleId) {
        return success(permissionService.getRoleMenuListByRoleId(roleId));
    }

    @PostMapping("/assign-role-menu")
    @Operation(summary = "赋予角色菜单")
    @PreAuthorize("@ss.hasPermission('system:permission:assign-role-menu')")
    public CommonResult<Boolean> assignRoleMenu(@Validated @RequestBody PermissionAssignRoleMenuReqVO reqVO) {
        // 开启多租户的情况下，需要过滤掉未开通的菜单
        tenantService.handleTenantMenu(menuIds -> reqVO.getMenuIds().removeIf(menuId -> !CollUtil.contains(menuIds, menuId)));

        // 执行菜单的分配
        permissionService.assignRoleMenu(reqVO.getRoleId(), reqVO.getMenuIds());
        return success(true);
    }

    @PostMapping("/assign-role-data-scope")
    @Operation(summary = "赋予角色数据权限")
    @PreAuthorize("@ss.hasPermission('system:permission:assign-role-data-scope')")
    public CommonResult<Boolean> assignRoleDataScope(@Valid @RequestBody PermissionAssignRoleDataScopeReqVO reqVO) {
        permissionService.assignRoleDataScope(reqVO.getRoleId(), reqVO.getDataScope(), reqVO.getDataScopeDeptIds());
        // 更新角色缓存
//        roleService.getRoleFromCache(reqVO.getRoleId());
        return success(true);
    }

    @PostMapping("/assign-role-course-scope")
    @Operation(summary = "赋予角色课程权限")
    @PreAuthorize("@ss.hasPermission('system:permission:assign-role-data-scope')")//后续改成course单独权限，目前没办法测试并更改租户默认管理员的权限
    public CommonResult<Boolean> assignRoleCourseScope(@Valid @RequestBody PermissionAssignRoleCourseScopeReqVO reqVO) {
        permissionService.assignRoleCourseScope(reqVO.getRoleId(), reqVO.getDataScopeCourseIds());
        // 更新角色缓存
//        roleService.getRoleFromCache(reqVO.getRoleId());
        return success(true);
    }


    @PostMapping("/assign-role-blockly-scope")
    @Operation(summary = "赋予角色blockly权限")
    @PreAuthorize("@ss.hasPermission('system:permission:assign-role-data-scope')")//后续改成blockly单独权限，目前没办法测试并更改租户默认管理员的权限
    public CommonResult<Boolean> assignRoleBlocklyScope(@Valid @RequestBody PermissionAssignRoleBlocklyScopeReqVO reqVO) {
        permissionService.assignRoleBlocklyScope(reqVO.getRoleId(), reqVO.getDataScopeBlocklyIds());
        // 更新角色缓存
//        roleService.getRoleFromCache(reqVO.getRoleId());
        return success(true);
    }

    @PostMapping("/assign-role-aiCourse-scope")
    @Operation(summary = "赋予角色aiCourse权限")
    @PreAuthorize("@ss.hasPermission('system:permission:assign-role-data-scope')")//后续改成aiCourse单独权限，目前没办法测试并更改租户默认管理员的权限
    public CommonResult<Boolean> assignRoleAiCourseScope(@Valid @RequestBody PermissionAssignRoleAiCourseScopeReqVO reqVO) {
        permissionService.assignRoleAiCourseScope(reqVO.getRoleId(), reqVO.getDataScopeAiCourseIds());
        // 更新角色缓存
//        roleService.getRoleFromCache(reqVO.getRoleId());
        return success(true);
    }

    @PostMapping("/assign-role-web-scope")
    @Operation(summary = "赋予角色web权限")
    @PreAuthorize("@ss.hasPermission('system:permission:assign-role-web-scope')")//后续改成web单独权限，目前没办法测试并更改租户默认管理员的权限
    public CommonResult<Boolean> assignRoleWebScope(@Valid @RequestBody PermissionAssignRoleWebScopeReqVO reqVO) {
        permissionService.assignRoleWebScope(reqVO);
        // 更新角色缓存
//        roleService.getRoleFromCache(reqVO.getRoleId());
        return success(true);
    }

    @Operation(summary = "获得管理员拥有的角色编号列表")
    @Parameter(name = "userId", description = "用户编号", required = true)
    @GetMapping("/list-user-roles")
    @PreAuthorize("@ss.hasPermission('system:permission:assign-user-role')")
    public CommonResult<Set<Long>> listAdminRoles(@RequestParam("userId") Long userId) {
        return success(permissionService.getUserRoleIdListByUserId(userId));
    }

    @Operation(summary = "赋予用户角色")
    @PostMapping("/assign-user-role")
    @PreAuthorize("@ss.hasPermission('system:permission:assign-user-role')")
    public CommonResult<Boolean> assignUserRole(@Validated @RequestBody PermissionAssignUserRoleReqVO reqVO) {
        // 清除角色缓存
        permissionService.assignUserRole(reqVO.getUserId(), reqVO.getRoleIds());
        // 刷新用户角色缓存
        permissionService.getUserRoleIdListByUserIdFromCache(reqVO.getUserId());
        return success(true);
    }

}
