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

import cn.reghao.bnt.web.admin.db.repository.MenuRepository;
import cn.reghao.bnt.web.admin.model.dto.MenuDto;
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.vo.MenuTree;
import cn.reghao.bnt.web.admin.model.vo.ResourceTree;
import cn.reghao.bnt.web.admin.service.MenuService;
import cn.reghao.bnt.web.admin.service.RoleService;
import cn.reghao.bnt.web.admin.service.UserContext;
import cn.reghao.jutil.jdk.web.result.Result;
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.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author reghao
 * @date 2021-04-04 21:24:18
 */
@Tag(name = "资源页面")
@RequestMapping("/api/devops/rbac/menu")
@RestController
public class MenuController {
    private final MenuService menuService;
    private final MenuRepository menuRepository;
    private final RoleService roleService;

    public MenuController(MenuService menuService, MenuRepository menuRepository, RoleService roleService) {
        this.menuService = menuService;
        this.menuRepository = menuRepository;
        this.roleService = roleService;
    }

    @Operation(summary = "可访问资源的角色列表页面", description = "N")
    @GetMapping("/roles")
    public String roleListWithResource(@RequestParam("id") Integer id) {
        Menu menu = menuRepository.getById(id);
        List<Role> list = new ArrayList<>(menu.getRoles());

        String resource = String.format("%s %s", menu.getType(), menu.getUrl());
        /*model.addAttribute("url", resource);
        model.addAttribute("list", list);*/
        return WebResult.success();
    }

    @Operation(summary = "修改资源", description = "N")
    @PostMapping(value = "/update", produces = MediaType.APPLICATION_JSON_VALUE)
    public String updateMenu(@Validated MenuDto menuDto) {
        Result result = menuService.updateMenu(menuDto);
        return WebResult.result(result);
    }

    @Operation(summary = "获取 ztree 形式的资源", description = "N")
    @GetMapping(value = "/ztree", produces = MediaType.APPLICATION_JSON_VALUE)
    public String list() {
        Role role = roleService.getRolesByUser(UserContext.getUserId()).get(0);
        List<ResourceTree> list = menuService.getMenuTreeByRole1(role);
        return WebResult.success(list);
    }
}
