package com.qmth.sop.server.api;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.sop.business.bean.dto.RoleDto;
import com.qmth.sop.business.bean.params.SysRolePrivilegeParam;
import com.qmth.sop.business.cache.CommonCacheService;
import com.qmth.sop.business.entity.SysRole;
import com.qmth.sop.business.entity.SysRolePrivilege;
import com.qmth.sop.business.service.SysRoleService;
import com.qmth.sop.common.annotation.OperationLog;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.ExceptionResultEnum;
import com.qmth.sop.common.enums.LogTypeEnum;
import com.qmth.sop.common.util.Result;
import com.qmth.sop.common.util.ResultUtil;
import io.swagger.annotations.*;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author wangliang
 * @since 2023-07-17
 */
@Api(tags = "角色Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_ROLE)
public class SysRoleController {

    @Resource
    SysRoleService sysRoleService;

    @Resource
    CommonCacheService commonCacheService;

    @ApiOperation(value = "查询")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = RoleDto.class)})
    public Result list(@ApiParam(value = "角色名称") @RequestParam(required = false) String name,
                       @ApiParam(value = "是否启用") @RequestParam(required = false) Boolean enable,
                       @ApiParam(value = "页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                       @ApiParam(value = "页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        return ResultUtil.ok(sysRoleService.query(new Page<>(pageNumber, pageSize), name, enable));
    }

    @ApiOperation(value = "角色权限查询")
    @RequestMapping(value = "/privilege/list", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = SysRolePrivilegeParam.class)})
    public Result privilegeList(@ApiParam(value = "角色id", required = true) @RequestParam Long roleId) {
        List<SysRolePrivilege> sysRolePrivilegeList = commonCacheService.rolePrivilegeCache(roleId);
        SysRole sysRole = commonCacheService.roleCache(roleId);
        Optional.ofNullable(sysRole).orElseThrow(() -> ExceptionResultEnum.ROLE_NO_EXISTS.exception());
        return ResultUtil.ok(new SysRolePrivilegeParam(sysRole.getId(), sysRole.getName(), !CollectionUtils.isEmpty(sysRolePrivilegeList) ? sysRolePrivilegeList.stream().map(s -> s.getPrivilegeId()).collect(Collectors.toList()) : null));
    }

    @ApiOperation(value = "新增/修改")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.EDIT)
    public Result save(@Valid @ApiParam(value = "角色保存信息", required = true) @RequestBody SysRolePrivilegeParam sysRolePrivilegeParams, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return ResultUtil.ok(sysRoleService.saveRole(sysRolePrivilegeParams));
    }

    @ApiOperation(value = "删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.DELETE)
    public Result delete(@ApiParam(value = "角色id", required = true) @RequestParam Long roleId) throws NoSuchAlgorithmException {
        return ResultUtil.ok(sysRoleService.deleteRole(roleId));
    }
}
