package cn.sh.stc.sict.cloud.upms.controller.web;

import cn.sh.stc.sict.cloud.common.core.util.R;
import cn.sh.stc.sict.cloud.upms.dto.RoleDTO;
import cn.sh.stc.sict.cloud.upms.model.HpMenu;
import cn.sh.stc.sict.cloud.upms.model.HpRole;
import cn.sh.stc.sict.cloud.upms.service.HpMenuService;
import cn.sh.stc.sict.cloud.upms.service.HpRoleMenuService;
import cn.sh.stc.sict.cloud.upms.service.HpRoleService;
import cn.sh.stc.sict.cloud.upms.service.HpUserRoleService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 系统角色表
 *
 * @author F_xh。
 * @date 2021-01-07 09:26:01
 */
@RestController
@RequestMapping("/hprole")
@AllArgsConstructor
@Slf4j
@Api(value = "系统角色表 controller", tags = "系统角色表")
public class HpRoleController {

    private HpRoleService hpRoleService;
    private HpRoleMenuService hpRoleMenuService;
    private HpUserRoleService hpUserRoleService;
    private HpMenuService hpMenuService;

    /**
     * 分页查询
     *
     * @param page   分页对象
     * @param hpRole 系统角色表
     * @return
     */
    @ApiOperation("分页查询 系统角色表")
    @GetMapping("/page")
    public R getHpRolePage(Page page, HpRole hpRole) {
        return new R<>(hpRoleService.page(page, Wrappers.query(hpRole)));
    }

    /**
     * 通过id查询系统角色表
     *
     * @param id id
     * @return R
     */
    @ApiOperation("通过id查询 系统角色表")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Long id) {
        HpRole role = hpRoleService.getById(id);
        if (role == null) {
            return new R().error("未找到角色！");
        }
        List<HpMenu> menuList = hpMenuService.listByRoleId(id);
        RoleDTO dto = new RoleDTO();
        dto.setRole(role);
        dto.setMenuList(menuList);
        return new R<>(dto);
    }

    @ApiOperation("新增/修改系统角色")
    @PostMapping
    public R save(@RequestBody RoleDTO dto) {
        hpRoleService.saveDto(dto);
        return new R<>();
    }

    @ApiOperation("删除系统角色表")
    @DeleteMapping("/{id}")
    public R removeById(@PathVariable Long id) {
        // 判断是否可删除
        if(hpUserRoleService.exist(id)){
            return new R().error("不可删除！");
        }
        hpRoleMenuService.removeByRoleId(id);
        hpRoleService.removeById(id);
        return new R<>();
    }

}
