package com.qmth.distributed.print.api;

import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.teachcloud.common.bean.dto.DataPermissionInfo;
import com.qmth.distributed.print.business.bean.params.SysRolePrivilegeParams;
import com.qmth.teachcloud.common.service.BasicRoleDataPermissionService;
import com.qmth.teachcloud.common.annotation.OperationLogDetail;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysRole;
import com.qmth.teachcloud.common.enums.log.CustomizedOperationTypeEnum;
import com.qmth.teachcloud.common.service.SysRoleService;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
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;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author xf
 * @since 2021-03-23
 */
@Api(tags = "角色Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX  + SystemConstant.PREFIX_URL_SYS + "/role")
@Validated
public class SysRoleController {

    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private BasicRoleDataPermissionService basicRoleDataPermissionService;

    /**
     * 查询
     *
     * @param name
     * @param enable
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "查询")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Result list(@RequestParam(value = "name", required = false) String name,
                       @RequestParam(value = "enable", required = false) Boolean enable,
                       @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                       @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        return ResultUtil.ok(sysRoleService.list(name, enable, pageNumber, pageSize));
    }

    /**
     * 新增用户时查询角色方法
     *
     * @return
     */
    @ApiOperation(value = "新增用户时查询角色方法")
    @RequestMapping(value = "/list_to_user", method = RequestMethod.POST)
    public Result listToUser() {
        return ResultUtil.ok(sysRoleService.listToUser());
    }

    /**
     * 超管-角色管理
     *
     * @return
     */
    @ApiOperation(value = "超管-角色管理")
    @RequestMapping(value = "/list_to_admin", method = RequestMethod.POST)
    public Result listToAdmin() {
        return ResultUtil.ok(sysRoleService.listToAdmin());
    }

    /**
     * 新增/修改
     *
     * @param sysRolePrivilegeParams
     * @return
     */
    @ApiOperation(value = "新增/修改")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @OperationLogDetail(customizedOperationType = CustomizedOperationTypeEnum.EDIT)
    public Result save(@Valid @RequestBody SysRolePrivilegeParams sysRolePrivilegeParams, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        // 组装角色
        SysRole role = new SysRole();
        role.setId(sysRolePrivilegeParams.getId());
        role.setName(sysRolePrivilegeParams.getName());
        role.setInterpret(sysRolePrivilegeParams.getInterpret());
        role.setPrivilegeIds(sysRolePrivilegeParams.getPrivilegeIds().stream().map(SystemConstant::convertIdToLong).toArray(Long[]::new));
        role.setDefaultRole(sysRolePrivilegeParams.getDefaultRole() == null ? false : sysRolePrivilegeParams.getDefaultRole());
        boolean rolePrivilegeResult = sysRoleService.saveRoleNew(role);

        // 组装角色权限
        Long roleId = role.getId();
        // 数据权限集合
        if (rolePrivilegeResult && roleId > 0){
            List<DataPermissionInfo> dataPermissionInfoList = sysRolePrivilegeParams.getDataPermissionInfo();
            basicRoleDataPermissionService.saveRoleDataPermission(roleId,dataPermissionInfoList);
        }
        return ResultUtil.ok();
    }

    /**
     * 启用/禁用
     *
     * @param role
     * @return
     */
    @ApiOperation(value = "启用/禁用")
    @RequestMapping(value = "/enable", method = RequestMethod.POST)
    @OperationLogDetail(customizedOperationType = CustomizedOperationTypeEnum.UPDATE)
    public Result enable(@RequestBody SysRole role) throws NoSuchAlgorithmException {
        return ResultUtil.ok(sysRoleService.enableReport(role));
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除")
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @OperationLogDetail(customizedOperationType = CustomizedOperationTypeEnum.DELETE)
    public Result remove(@RequestParam(value = "id", required = true) Long id) {
        return ResultUtil.ok(sysRoleService.removeReport(id));
    }

    /**
     * 用户已绑定角色列表
     *
     * @param userId
     * @return
     */
    @ApiOperation(value = "用户已绑定角色列表")
    @RequestMapping(value = "/get_user_roles", method = RequestMethod.POST)
    public Result getUserRoles(@RequestParam(value = "userId", required = true) Long userId) {
        return ResultUtil.ok(sysRoleService.getUserRoles(userId));
    }

    /**
     * 设置内置角色
     *
     * @param
     */
    @ApiOperation(value = "内置角色")
    @RequestMapping(value = "/builtin", method = RequestMethod.POST)
    public Result builtin(@RequestParam Long id,
                          @RequestParam boolean defaultRole) {
        return ResultUtil.ok(sysRoleService.builtin(id, defaultRole));
    }
}

