package cn.reghao.bnt.web.admin.controller;

import cn.reghao.bnt.web.admin.model.po.Menu;
import cn.reghao.bnt.web.admin.model.po.Role;
import cn.reghao.bnt.web.admin.model.po.User;
import cn.reghao.bnt.web.admin.model.vo.ResourceTree;
import cn.reghao.bnt.web.admin.model.vo.RoleVO;
import cn.reghao.bnt.web.admin.service.AccountService;
import cn.reghao.bnt.web.admin.service.MenuService;
import cn.reghao.bnt.web.admin.service.RoleService;
import cn.reghao.jutil.web.WebResult;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2021-04-04 21:24:18
 */
@Tag(name = "角色页面")
@RequestMapping("/api/devops/rbac/role")
@RestController
public class RoleController {
    private final RoleService roleService;
    private final MenuService menuService;
    private final AccountService accountService;

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

    @Operation(summary = "角色列表页面", description = "N")
    @GetMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
    public String rolePage() {
        List<RoleVO> list = roleService.getAllRoles();
        return WebResult.success(list);
    }

    @Operation(summary = "拥有角色的所有用户页面", description = "N")
    @GetMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
    public String userListWithRole(@RequestParam("roleId") Integer roleId) {
        List<User> list = accountService.getUsersByRole(roleId, 1);
        return WebResult.success(list);
    }

    @Operation(summary = "获取角色可访问的资源", description = "N")
    @GetMapping(value = "/menus", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getRoleMenus(@RequestParam("id") Role role) {
        List<Integer> roleMenuIds = role.getMenus().stream().map(Menu::getId).collect(Collectors.toList());
        List<ResourceTree> allMenus = menuService.getMenuTreeByRole1(role);

        Map<String, Object> map = new HashMap<>();
        map.put("roleMenuIds", roleMenuIds);
        map.put("allMenus", allMenus);
        return WebResult.success(map);
    }

    @Operation(summary = "设置角色可访问的资源", description = "N")
    @PostMapping(value = "/menus", produces = MediaType.APPLICATION_JSON_VALUE)
    public String setRoleMenus(@RequestParam(value = "id") Integer roleId,
                               @RequestParam(value = "menuIds") Set<Integer> menuIds) {
        roleService.updateRoleMenus(roleId, menuIds);
        return WebResult.success();
    }
}
