package cn.reghao.devops.web.admin.account.controller;

import cn.reghao.devops.web.admin.account.model.dto.RoleDto;
import cn.reghao.devops.web.admin.account.model.po.Menu;
import cn.reghao.devops.web.admin.account.model.po.Role;
import cn.reghao.devops.web.admin.account.model.vo.MenuTree;
import cn.reghao.devops.web.admin.account.service.MenuService;
import cn.reghao.devops.web.admin.account.service.RoleService;
import cn.reghao.jutil.jdk.result.Result;
import cn.reghao.jutil.jdk.result.WebResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * @author reghao
 * @date 2021-04-04 21:24:18
 */
@Api(tags = "角色接口")
@RequestMapping("/api/rbac/role")
@RestController
public class RoleController {
    private final RoleService roleService;
    private final MenuService menuService;

    public RoleController(RoleService roleService, MenuService menuService) {
        this.roleService = roleService;
        this.menuService = menuService;
    }

    @ApiOperation("添加或修改角色")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public String addOrModifyRole(@Validated RoleDto roleDto) {
        roleService.addOrUpdate(roleDto);
        return WebResult.success();
    }

    @ApiOperation("删除角色")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @DeleteMapping(value = "/{roleId}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String deleteRole(@PathVariable("roleId") Integer roleId) {
        Result result = roleService.deleteRole(roleId);
        return WebResult.result(result);
    }

    /**
     * spring data jpa 会自动根据 id 参数查询 Role 实例
     *
     * @param
     * @return
     * @date 2024-07-30 16:08:42
     */
    @ApiOperation("获取角色可访问的资源")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping(value = "/menus/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getRoleMenus(@PathVariable("id") Role role) {
        List<MenuTree> allMenus = menuService.getMenusByRole(role);
        return WebResult.success(allMenus);
    }

    @ApiOperation("设置角色可访问的资源")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @PostMapping(value = "/menus", produces = MediaType.APPLICATION_JSON_VALUE)
    public String setRoleMenus(@RequestParam(value = "id") Integer roleId,
                               @RequestParam(value = "menuId", required = false) Set<Menu> menus) {
        if (menus == null) {
            menus = Collections.emptySet();
        }
        roleService.setRoleMenus(roleId, menus);
        return WebResult.success();
    }
}
