package cn.reghao.oss.console.account.controller.page;

import cn.reghao.oss.console.account.db.query.RoleQuery;
import cn.reghao.oss.console.account.model.po.User;
import cn.reghao.oss.console.account.model.vo.RoleVO;
import cn.reghao.oss.console.util.db.PageSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
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 RoleQuery roleQuery;

    public RolePageController(RoleQuery roleQuery) {
        this.roleQuery = roleQuery;
    }

    @ApiOperation("角色列表页面")
    @GetMapping
    public String rolePage(@RequestParam(value = "name", required = false) String name, Model model) {
        Page<RoleVO> page;
        if (name != null) {
            List<RoleVO> list = roleQuery.getByMatchName(name);
            page = new PageImpl<>(list);
        } else {
            PageRequest pageRequest = PageSort.pageRequest();
            page = roleQuery.getRoleVOByPage(pageRequest);
        }

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

    @ApiOperation("角色新增页面")
    @GetMapping("/add")
    public String addRolePage() {
        return "/rbac/role/add";
    }

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

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

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

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