package com.cf.imes.module.system.controller.admin.permission;

import cn.hutool.core.util.ObjectUtil;
import com.cf.imes.framework.common.enums.CommonStatusEnum;
import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.common.pojo.PageParam;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.framework.excel.core.util.ExcelUtils;
import com.cf.imes.framework.operatelog.core.annotations.OperateLog;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import com.cf.imes.framework.security.core.util.SecurityFrameworkUtils;
import com.cf.imes.module.system.constants.permission.InternalRoleConstants;
import com.cf.imes.module.system.controller.admin.permission.vo.role.RolePageReqVO;
import com.cf.imes.module.system.controller.admin.permission.vo.role.RoleRespVO;
import com.cf.imes.module.system.controller.admin.permission.vo.role.RoleSaveReqVO;
import com.cf.imes.module.system.controller.admin.permission.vo.role.RoleSimpleRespVO;
import com.cf.imes.module.system.controller.admin.permission.vo.role.RoleUpdateStatusReqVO;
import com.cf.imes.module.system.dal.dataobject.permission.RoleDO;
import com.cf.imes.module.system.service.permission.RoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.framework.common.pojo.CommonResult.success;
import static com.cf.imes.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.ROLE_NOT_EXISTS;
import static java.util.Collections.singleton;

@Tag(name = "管理后台 - 角色")
@RestController
@RequestMapping("/system/role")
@Validated
public class RoleController {

    @Resource
    private RoleService roleService;

    @PostMapping("/create")
    @Operation(summary = "创建角色")
    @PreAuthorize("@ss.hasAnyPermissions('system:role:create','base:role:create')")
    public CommonResult<Long> createRole(@Valid @RequestBody RoleSaveReqVO createReqVO) {
        if(Objects.isNull(createReqVO.getOrganId())) {
            createReqVO.setOrganId(OrganContextHolder.getOrganId());
        }
        Long organId = SecurityFrameworkUtils.getLoginUser().getOrganId();
        return success(roleService.createRole(createReqVO, null));
    }

    @PutMapping("/update")
    @Operation(summary = "修改角色")
    @PreAuthorize("@ss.hasAnyPermissions('system:role:update','base:role:update')")
    public CommonResult<Boolean> updateRole(@Valid @RequestBody RoleSaveReqVO updateReqVO) {
        if (Objects.equals(updateReqVO.getId(), InternalRoleConstants.ORGAN_ADMIN_ROLE_ID) || Objects.equals(updateReqVO.getId(), InternalRoleConstants.ORGAN_STAFF_ROLE_ID)) {
            throw new ServiceException(11541, "内置角色无法修改");
        }

        if(Objects.isNull(updateReqVO.getOrganId())) {
            updateReqVO.setOrganId(OrganContextHolder.getOrganId());
        }
        roleService.updateRole(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "修改角色状态")
    @PreAuthorize("@ss.hasAnyPermissions('system:role:update','base:role:update')")
    public CommonResult<Boolean> updateRoleStatus(@Valid @RequestBody RoleUpdateStatusReqVO reqVO) {
        roleService.updateRoleStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除角色")
    @Parameter(name = "id", description = "角色编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasAnyPermissions('system:role:delete','base:role:delete')")
    public CommonResult<Boolean> deleteRole(@RequestParam("id") Long id) {
        roleService.deleteRole(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得角色信息")
//    @PreAuthorize("@ss.hasAnyPermissions('system:role:query','base:role:query','system:permission:assign-user-role')")
    public CommonResult<RoleRespVO> getRole(@RequestParam("id") Long id) {
        RoleDO role = roleService.getRole(id);
        if (ObjectUtil.isNull(role)) {
            throw exception(ROLE_NOT_EXISTS);
        }
        return success(BeanUtils.toBean(role, RoleRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得角色分页")
    @PreAuthorize("@ss.hasAnyPermissions('system:role:query','base:role:query')")
    public CommonResult<PageResult<RoleRespVO>> getRolePage(@Valid RolePageReqVO pageReqVO) {
        PageResult<RoleDO> pageResult = roleService.getRolePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, RoleRespVO.class));
    }

    @GetMapping({"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取角色精简信息列表", description = "只包含被开启的角色，主要用于前端的下拉选项")
    public CommonResult<List<RoleSimpleRespVO>> getSimpleRoleList(@RequestParam(value = "organId", required = false) Long organId) {
        List<RoleDO> list = roleService.getRoleListByStatus(singleton(CommonStatusEnum.ENABLE.getStatus()), organId);
        //List<RoleDO> roleDOS = list.stream().filter(f -> !Objects.equals(f.getId(), 1L)).sorted(Comparator.comparing(RoleDO::getSort)).toList();
        list.sort(Comparator.comparing(RoleDO::getSort));
        return success(BeanUtils.toBean(list, RoleSimpleRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出角色 Excel")
    @OperateLog(type = EXPORT)
    @PreAuthorize("@ss.hasAnyPermissions('system:role:export','base:role:export')")
    public void export(HttpServletResponse response, @Validated RolePageReqVO exportReqVO) throws IOException {
        exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<RoleDO> list = roleService.getRolePage(exportReqVO).getList();
        // 输出
        ExcelUtils.write(response, "角色数据.xls", "数据", RoleRespVO.class,
                BeanUtils.toBean(list, RoleRespVO.class));
    }

}
