package com.skr.mdm.api.system.controller;

import com.skr.mdm.api.system.service.RoleService;
import com.skr.mdm.bean.qo.role.RoleQO;
import com.skr.mdm.dto.LoginAdminDTO;
import com.skr.mdm.result.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;

/**
 * @author nfq
 * @date 2020/9/8 17:44
 */
@RestController
@RequestMapping("role")
@Api(tags = "角色管理")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @PostMapping("menuTree")
    @ApiOperation(value = "角色菜单树")
    public ResponseResult menuTree(@RequestParam(required = false) @ApiParam(value = "角色id") Integer roleId, @ApiIgnore Authentication authentication) {
        LoginAdminDTO loginAdminDTO = (LoginAdminDTO) authentication.getPrincipal();
        return roleService.menuTree(loginAdminDTO.getCompanyId(), roleId);
    }

    @PostMapping("add")
    @ApiOperation(value = "创建角色")
    @PreAuthorize("hasAnyAuthority('sys:role:add')")
    ResponseResult addRole(@RequestBody RoleQO roleQO, @ApiIgnore Authentication authentication) {
        LoginAdminDTO loginAdminDTO = (LoginAdminDTO) authentication.getPrincipal();
        return roleService.addRole(roleQO, loginAdminDTO);
    }

    @PostMapping("list")
    @ApiOperation(value = "角色列表")
    @PreAuthorize("hasAnyAuthority('sys:role:list')")
    public ResponseResult listRole(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                                   @RequestParam(required = false) String roleName,
                                   @ApiIgnore Authentication authentication) {
        LoginAdminDTO loginAdminDTO = (LoginAdminDTO) authentication.getPrincipal();
        return roleService.listRole(pageNum, pageSize, loginAdminDTO.getCompanyId(), roleName);
    }

    @PostMapping("update")
    @ApiOperation(value = "编辑角色")
    @PreAuthorize("hasAnyAuthority('sys:role:update')")
    public ResponseResult updateRole(@RequestBody RoleQO roleQO, @ApiIgnore Authentication authentication, HttpServletRequest request) {
        LoginAdminDTO loginAdminDTO = (LoginAdminDTO) authentication.getPrincipal();
        return roleService.updateRole(roleQO, loginAdminDTO, request);
    }

    @PostMapping("delete")
    @ApiOperation(value = "删除角色")
    @PreAuthorize("hasAnyAuthority('sys:role:delete')")
    public ResponseResult deleteRole(@RequestParam Integer roleId, @ApiIgnore Authentication authentication) {
        LoginAdminDTO loginAdminDTO = (LoginAdminDTO) authentication.getPrincipal();
        return roleService.deleteRole(roleId, loginAdminDTO);
    }
}
