package com.njcn.rdms.module.system.controller.admin.permission;

import cn.hutool.core.util.StrUtil;
import com.njcn.rdms.framework.apilog.core.annotation.ApiAccessLog;
import com.njcn.rdms.framework.common.enums.CommonStatusEnum;
import com.njcn.rdms.framework.common.pojo.CommonResult;
import com.njcn.rdms.framework.common.pojo.PageParam;
import com.njcn.rdms.framework.common.pojo.PageResult;
import com.njcn.rdms.framework.common.util.object.BeanUtils;
import com.njcn.rdms.framework.common.util.validation.ValidationUtils;
import com.njcn.rdms.framework.excel.core.util.ExcelUtils;
import com.njcn.rdms.module.system.controller.admin.permission.vo.role.RolePageReqVO;
import com.njcn.rdms.module.system.controller.admin.permission.vo.role.RoleRespVO;
import com.njcn.rdms.module.system.controller.admin.permission.vo.role.RoleSaveReqVO;
import com.njcn.rdms.module.system.dal.dataobject.permission.RoleDO;
import com.njcn.rdms.module.system.enums.permission.PermissionScopeTypeEnum;
import com.njcn.rdms.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 jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Comparator;
import java.util.List;

import static com.njcn.rdms.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static com.njcn.rdms.framework.common.pojo.CommonResult.success;
import static java.util.Collections.singleton;

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

    private static final String GLOBAL_SCOPE_TYPE = PermissionScopeTypeEnum.GLOBAL.getScopeType();
    private static final String OBJECT_SCOPE_TYPE = PermissionScopeTypeEnum.OBJECT.getScopeType();
    private static final String GLOBAL_OBJECT_TYPE = PermissionScopeTypeEnum.GLOBAL_OBJECT_TYPE;

    @Resource
    private RoleService roleService;

    @PostMapping("/create")
    @Operation(summary = "创建角色")
    @PreAuthorize("@ss.hasPermission('system:role:create')")
    public CommonResult<Long> createRole(@Valid @RequestBody RoleSaveReqVO createReqVO) {
        return success(roleService.createRole(normalizeScopeReqVO(createReqVO), null));
    }

    @PutMapping("/update")
    @Operation(summary = "修改角色")
    @PreAuthorize("@ss.hasPermission('system:role:update')")
    public CommonResult<Boolean> updateRole(@Valid @RequestBody RoleSaveReqVO updateReqVO) {
        roleService.updateRole(updateReqVO);
        return success(true);
    }

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

    @DeleteMapping("/delete-list")
    @Operation(summary = "批量删除角色")
    @Parameter(name = "ids", description = "编号列表", required = true)
    @PreAuthorize("@ss.hasPermission('system:role:delete')")
    public CommonResult<Boolean> deleteRoleList(@RequestParam("ids") List<Long> ids) {
        roleService.deleteRoleList(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得角色信息")
    @PreAuthorize("@ss.hasPermission('system:role:query')")
    public CommonResult<RoleRespVO> getRole(@RequestParam("id") Long id) {
        RoleDO role = roleService.getRole(id);
        return success(BeanUtils.toBean(role, RoleRespVO.class));
    }

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

    @GetMapping("/simple-list")
    @Operation(summary = "获取角色精简信息列表", description = "只包含被开启的角色，主要用于前端的下拉选项")
    public CommonResult<List<RoleRespVO>> getSimpleRoleList(RolePageReqVO reqVO) {
        RolePageReqVO effectiveReqVO = normalizeScopeReqVO(reqVO);
        List<RoleDO> list = roleService.getRoleListByStatus(singleton(CommonStatusEnum.ENABLE.getStatus()),
                effectiveReqVO.getScopeType(), effectiveReqVO.getObjectType());
        list.sort(Comparator.comparing(RoleDO::getSort));
        return success(BeanUtils.toBean(list, RoleRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出角色 Excel")
    @ApiAccessLog(operateType = EXPORT)
    @PreAuthorize("@ss.hasPermission('system: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));
    }

    private RolePageReqVO normalizeScopeReqVO(RolePageReqVO reqVO) {
        RolePageReqVO effectiveReqVO = reqVO == null ? new RolePageReqVO() : reqVO;
        String scopeType = normalizeScopeType(effectiveReqVO.getScopeType());
        effectiveReqVO.setScopeType(scopeType);
        effectiveReqVO.setObjectType(normalizeObjectType(scopeType, effectiveReqVO.getObjectType()));
        ValidationUtils.validate(effectiveReqVO);
        return effectiveReqVO;
    }

    private RoleSaveReqVO normalizeScopeReqVO(RoleSaveReqVO reqVO) {
        RoleSaveReqVO effectiveReqVO = reqVO == null ? new RoleSaveReqVO() : reqVO;
        String scopeType = normalizeScopeType(effectiveReqVO.getScopeType());
        effectiveReqVO.setScopeType(scopeType);
        effectiveReqVO.setObjectType(normalizeObjectType(scopeType, effectiveReqVO.getObjectType()));
        ValidationUtils.validate(effectiveReqVO);
        return effectiveReqVO;
    }

    private String normalizeScopeType(String scopeType) {
        return StrUtil.blankToDefault(StrUtil.trim(scopeType), GLOBAL_SCOPE_TYPE);
    }

    private String normalizeObjectType(String scopeType, String objectType) {
        return OBJECT_SCOPE_TYPE.equals(scopeType) ? StrUtil.trim(objectType) : GLOBAL_OBJECT_TYPE;
    }

}
