package com.lideeyunji.service.system.controller;

import cn.hutool.core.util.ObjectUtil;
import com.lideeyunji.service.system.controller.vo.permission.role.*;
import com.lideeyunji.service.system.controller.vo.permission.role.*;
import com.lideeyunji.service.system.entity.DictDataDO;
import com.lideeyunji.service.system.entity.RoleDO;
import com.lideeyunji.service.system.service.IDictDataService;
import com.lideeyunji.service.system.service.IRoleService;
import com.lideeyunji.tool.framework.common.enums.CommonStatusEnum;
import com.lideeyunji.tool.framework.common.pojo.CommonResult;
import com.lideeyunji.tool.framework.common.pojo.PageParam;
import com.lideeyunji.tool.framework.common.pojo.PageResult;
import com.lideeyunji.tool.framework.common.util.object.BeanUtils;
import com.lideeyunji.tool.framework.excel.core.util.ExcelUtils;
import com.lideeyunji.tool.framework.operatelog.core.annotations.OperateLog;
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 javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.lideeyunji.tool.framework.common.pojo.CommonResult.success;
import static com.lideeyunji.tool.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static java.util.Collections.singleton;

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

    @Resource
    private IRoleService roleService;

    @Resource
    private IDictDataService dictDataService;

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

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

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

    @DeleteMapping("/delete")
    @Operation(tags = "菜单管理",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);
    }

    @GetMapping("/get")
    @Operation(tags = "菜单管理",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(tags = "菜单管理",summary = "获得角色分页")
    @PreAuthorize("@ss.hasPermission('system:role:query')")
    public CommonResult<PageResult<RoleRespVO>> getRolePage(RolePageReqVO pageReqVO) {
        PageResult<RoleDO> pageResult = roleService.getRolePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, RoleRespVO.class));
    }

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

    @GetMapping("/export-excel")
    @Operation(tags = "菜单管理",summary = "导出角色 Excel")
    @OperateLog(type = 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();
        List<CopyRoleRespVO> roleRespVOList = BeanUtils.toBean(list, CopyRoleRespVO.class);
        List<DictDataDO> dictDataList = dictDataService.getListByDictType("system_data_scope");
        Map<String, String> dataScopeMap = dictDataList.stream()
                .collect(Collectors.toMap(DictDataDO::getValue, DictDataDO::getLabel, (existingValue, newValue) -> newValue));
        roleRespVOList.stream()
                .filter(item -> ObjectUtil.isNotEmpty(item.getDataScope()))
                .forEach(item -> {
                    if (!dataScopeMap.containsKey(item.getDataScope())) {
                        return;
                    }
                    item.setDataScope(dataScopeMap.get(item.getDataScope()));
                });
        // 输出
        ExcelUtils.write(response, "角色数据.xls", "数据", CopyRoleRespVO.class, roleRespVOList);
    }

}
