package cn.reghao.autodop.dmaster.rbac.controller;

import cn.reghao.autodop.dmaster.rbac.db.query.MenuQuery;
import cn.reghao.autodop.dmaster.rbac.model.po.Menu;
import cn.reghao.autodop.dmaster.rbac.model.po.Role;
import cn.reghao.autodop.dmaster.rbac.service.RoleService;
import cn.reghao.jdkutil.result.WebBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
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 MenuQuery menuQuery;
    private RoleService roleService;

    public RoleController(MenuQuery menuQuery, RoleService roleService) {
        this.menuQuery = menuQuery;
        this.roleService = roleService;
    }

    @ApiOperation("添加或修改角色")
    @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public String addOrModifyRole(@Validated Role role) {
        roleService.addOrModify(role);
        return WebBody.success();
    }

    @ApiOperation("删除角色")
    @DeleteMapping(value = "/{roleId}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String deleteRole(@PathVariable("roleId") Integer roleId) {
        roleService.delete(roleId);
        return WebBody.success();
    }

    @ApiOperation("获取角色可访问的资源")
    @GetMapping(value = "/menus/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getRoleMenus(@PathVariable("id") Role role) {
        List<Menu> allMenus = menuQuery.findAll();
        allMenus.forEach(menu -> {
            if (menu.getRoles().contains(role)) {
                // 对应前端的 checked 复选框
                menu.setRemark("auth:true");
            }
        });
        return WebBody.success(allMenus);
    }

    @ApiOperation("设置角色可访问的资源")
    @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 WebBody.success();
    }
}
