package com.qmth.distributed.print.api;

import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.teachcloud.common.bean.params.SysRolePrivilegeParams;
import com.qmth.teachcloud.common.entity.SysRolePrivilege;
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.SysPrivilege;
import com.qmth.teachcloud.common.entity.SysRole;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.log.OperationTypeEnum;
import com.qmth.teachcloud.common.service.SysPrivilegeService;
import com.qmth.teachcloud.common.service.SysRoleService;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import com.qmth.teachcloud.common.util.ServletUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 前端控制器
 * </p>
 *
 * @author xf
 * @since 2021-03-23
 */
@Api(tags = "菜单权限Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_SYS + "/privilege")
public class SysPrivilegeController {

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

    /**
     * 查询
     *
     * @return
     */
    @ApiOperation(value = "查询")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Result list() {
        return ResultUtil.ok(sysPrivilegeService.listPrivilegeTreeNew());
    }

    /**
     * 查询需要授权的菜单
     *
     * @return
     */
    @ApiOperation(value = "查询需要授权的菜单")
    @RequestMapping(value = "/list_auth", method = RequestMethod.POST)
    public Result listAuth() {
        return ResultUtil.ok(sysPrivilegeService.listPrivilegeTreeAuth());
    }

    /**
     * 新增/修改
     *
     * @param privilege
     * @return
     */
    @ApiOperation(value = "新增/修改")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.SAVE)
    public Result save(@RequestBody SysPrivilege privilege) {
        return ResultUtil.ok(sysPrivilegeService.savePrivilege(privilege));
    }

    /**
     * 删除
     *
     * @param privilege
     * @return
     */
    @ApiOperation(value = "删除")
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.DELETE)
    public Result remove(@RequestBody SysPrivilege privilege) {
        return ResultUtil.ok(sysPrivilegeService.remove(privilege.getId()));
    }

    /**
     * 角色已绑定权限列表
     *
     * @param roleId
     * @return
     */
    @ApiOperation(value = "角色已绑定权限列表")
    @RequestMapping(value = "/get_role_privileges", method = RequestMethod.POST)
    public Result getRolePrivileges(@RequestParam(value = "roleId", required = true) Long roleId) {
        SysRole sysRole = sysRoleService.getById(roleId);
        if (Objects.isNull(sysRole)) {
            throw ExceptionResultEnum.ERROR.exception("角色不存在");
        }

        SysRolePrivilegeParams result = new SysRolePrivilegeParams();
        // 该角色拥有的权限集合
        Long schoolId = Objects.nonNull(ServletUtil.getRequestHeaderSchoolIdByNotVaild()) ? Long.valueOf(ServletUtil.getRequestHeaderSchoolIdByNotVaild().toString()) : null;
        List<SysRolePrivilege> sysRolePrivilegeList = sysPrivilegeService.getRolePrivileges(schoolId, sysRole);
        if (!CollectionUtils.isEmpty(sysRolePrivilegeList)) {
            List<String> privilegeIds;
            if (schoolId == null && sysRole.getDefaultRole()) {
                privilegeIds = sysRolePrivilegeList.stream().filter(m -> m.getSchoolId() == null).map(m -> String.valueOf(m.getPrivilegeId())).collect(Collectors.toList());
            } else {
                privilegeIds = sysRolePrivilegeList.stream().map(m -> String.valueOf(m.getPrivilegeId())).collect(Collectors.toList());
            }
            result.setPrivilegeIds(privilegeIds);
            // 内置角色，只返回内置角色对应权限，不显示学校编辑的权限
            if (schoolId != null && sysRole.getDefaultRole()) {
                List<String> defaultPrivilegeIds = sysRolePrivilegeList.stream().filter(m -> m.getSchoolId() == null).map(m -> String.valueOf(m.getPrivilegeId())).collect(Collectors.toList());
                result.setDefaultPrivilegeIds(defaultPrivilegeIds);
            }
        }

        // 该角色拥有的数据权限
        result.setDataPermissionInfo(basicRoleDataPermissionService.findRoleDataPermissionInfo(roleId));
        result.setId(roleId);
        result.setInterpret(sysRole.getInterpret());
        result.setName(sysRole.getName());

        return ResultUtil.ok(result);
    }
}

