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

import cn.reghao.devops.web.admin.account.model.po.Menu;
import cn.reghao.devops.web.admin.account.model.vo.RoleVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author reghao
 * @date 2021-04-04 21:24:18
 */
@Api(tags = "资源页面")
@RequestMapping("/rbac/menu")
@Controller
public class MenuPageController {
    @ApiOperation(value = "资源列表页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping
    public String menuPage(@RequestParam(value = "enabled", required = false) Boolean enabled, Model model) {
        if (enabled == null) {
            enabled = true;
        }

        model.addAttribute("enabled", enabled);
        return "/admin/menu/index";
    }

    @ApiOperation(value = "资源添加页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping(value = "/add")
    public String addMenuPage(Model model) {
        return "/admin/menu/add";
    }

    @ApiOperation(value = "资源编辑页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/edit/{id}")
    public String toEdit(@PathVariable("id") Menu menu, Model model) {
        model.addAttribute("menu", menu);
        return "/admin/menu/edit";
    }

    // TODO Hibernate 会根据传入的 id 自动查找相应的 Menu
    @ApiOperation(value = "可访问资源的角色列表页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/{id}/roles")
    public String roleListWithResource(@PathVariable("id") Menu menu, Model model) {
        List<RoleVO> list = menu.getRoles().stream().map(RoleVO::new).collect(Collectors.toList());
        model.addAttribute("list", list);
        return "/admin/menu/roles";
    }
}
