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

import cn.reghao.devops.web.admin.account.model.po.User;
import cn.reghao.devops.web.admin.account.model.vo.RoleVO;
import cn.reghao.devops.web.admin.account.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
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.List;

/**
 * @author reghao
 * @date 2021-04-04 21:24:18
 */
@Api(tags = "角色页面")
@RequestMapping("/rbac/role")
@Controller
public class RolePageController {
    private final RoleService roleService;

    public RolePageController(RoleService roleService) {
        this.roleService = roleService;
    }

    @ApiOperation("角色列表页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping
    public String rolePage(@RequestParam(value = "name", required = false) String name, Model model) {
        Page<RoleVO> page;
        if (name != null) {
            page = roleService.getByPage(null, name);
        } else {
            PageRequest pageRequest = PageRequest.of(0, 100);
            page = roleService.getByPage(pageRequest, null);
        }

        model.addAttribute("page", page);
        model.addAttribute("list", page.getContent());
        return "/admin/role/index";
    }

    @ApiOperation("角色新增页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/add")
    public String addRolePage() {
        return "/admin/role/add";
    }

    @ApiOperation("角色编辑页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/edit/{id}")
    public String editRolePage(@PathVariable("id") int id, Model model) {
        RoleVO vo = roleService.getRoleVOById(id);
        model.addAttribute("role", vo);
        return "/admin/role/add";
    }

    @ApiOperation("角色详细信息页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/detail/{id}")
    public String roleDetailPage(@PathVariable("id") int id, Model model) {
        RoleVO vo = roleService.getRoleVOById(id);
        model.addAttribute("role", vo);
        return "/admin/role/detail";
    }

    @ApiOperation("设置角色可访问的资源页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/menus/{id}")
    public String menusPage(@PathVariable(value = "id") Integer id, Model model){
        model.addAttribute("roleId", id);
        return "/admin/role/menus";
    }

    @ApiOperation("拥有角色的所有用户页面")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/users/{id}")
    public String userListWithRole(@PathVariable("id") Integer roleId, Model model) {
        List<User> list = roleService.getRoleUsers(roleId);
        model.addAttribute("list", list);
        return "/admin/role/users";
    }
}
