package cn.iocoder.yudao.module.inspection.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.common.InspectionRoleCommon;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.inspection.entity.InspectionEquInfo;
import cn.iocoder.yudao.module.inspection.entity.InspectionFile;
import cn.iocoder.yudao.module.inspection.service.IInspectionEquInfoService;
import cn.iocoder.yudao.module.inspection.service.IInspectionFileService;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.system.api.permission.RoleApi;
import cn.iocoder.yudao.module.system.api.permission.dto.RoleReqDTO;
import cn.iocoder.yudao.module.workReport.service.WorkReportService;
import cn.iocoder.yudao.module.workReport.vo.WorkReportPageReqVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 检测用的工具Controller
 *
 * @author 小李
 * @date 15:36 2024/12/15
 **/
@RestController
@RequestMapping("/admin-api/inspection/util")
public class InspectionUtilController {

    @Resource
    private PermissionApi permissionApi;

    @Resource
    private RoleApi roleApi;

    @Resource
    private IInspectionEquInfoService equInfoService;

    @Resource
    private IInspectionFileService fileService;

    @Resource
    private WorkReportService workReportService;

    @Resource
    private DictDataApi dictDataApi;

    /**
     * 根据用户取出当前用户的角色，只针对检测
     *
     * @author 小李
     * @date 15:15 2024/12/15
     **/
    @GetMapping("/getRoleName")
    public CommonResult<?> getRoleName() {
        String name = "未知岗位";
        List<Long> roleIdsByUserId = permissionApi.getRoleIdsByUserId(SecurityFrameworkUtils.getLoginUserId());
        if (CollUtil.isEmpty(roleIdsByUserId)) {
            return success(name);
        }
        List<RoleReqDTO> roleList = roleApi.getRoleList();
        List<RoleReqDTO> roles = roleList.stream().filter(item -> roleIdsByUserId.contains(item.getId())).collect(Collectors.toList());
        List<InspectionRoleCommon> roleCommons = Arrays.asList(InspectionRoleCommon.values());
        List<String> codes = roleCommons.stream().map(InspectionRoleCommon::getCode).collect(Collectors.toList());
        List<RoleReqDTO> inspectionRoles = roles.stream().filter(item -> codes.contains(item.getCode())).collect(Collectors.toList());
        if (CollUtil.isEmpty(inspectionRoles)) {
            return success(name);
        }
                                                                                                                                             Integer index = Integer.MAX_VALUE;
        for (RoleReqDTO inspectionRole : inspectionRoles) {
            InspectionRoleCommon inspectionRoleCommon = InspectionRoleCommon.valueOf(inspectionRole.getCode().toUpperCase());
            if (ObjectUtil.isEmpty(inspectionRoleCommon)) {
                continue;
            }
            Integer weight = inspectionRoleCommon.getWeight();
            if (weight < index) {
                index = weight;
                name = inspectionRole.getName();
            }
        }
        return success(name);
    }

    @GetMapping("/getTypeCount")
    public CommonResult<?> getTypeCount(@RequestParam("partnerId") Long partnerId) {
        Map<String, Long> map = new HashMap<>();
        Long staffCount = roleApi.selectListByRoleId();
        map.put("staff", staffCount);
        Page<InspectionEquInfo> page = new Page<>(1, 1000);
        IPage<InspectionEquInfo> equs = equInfoService.selectInspectionEquInfoList(page, new InspectionEquInfo());
        map.put("equ", equs.getTotal());
        long fileCount = fileService.count(new LambdaQueryWrapper<InspectionFile>().eq(InspectionFile::getType, "2"));
        map.put("file", fileCount);

        //查询汇报数量
        WorkReportPageReqVO workReportPageReqVO = new WorkReportPageReqVO();
        workReportPageReqVO.setUserId(SecurityFrameworkUtils.getLoginUserId());
        workReportPageReqVO.setServicePackageId("jiance");
        //根据dictType查询角色
        List<DictDataRespDTO> roleList = dictDataApi.getDictDataList("ins_high_rise");
        //公司高层角色code集合
        List<String> codes = roleList.stream().map(DictDataRespDTO::getValue).collect(Collectors.toList());

        Map<Long, List<String>> longListMap = permissionApi.roleCodesByUserIds(Collections.singletonList(SecurityFrameworkUtils.getLoginUserId()));
        List<String> roleKey = longListMap.get(SecurityFrameworkUtils.getLoginUserId());

        //判断当前登陆人的角色是否是公司高层
        boolean isCompanyLeader = roleKey != null && roleKey.stream().anyMatch(codes::contains);
        if (isCompanyLeader) {
            workReportPageReqVO.setUserId(null);
        }
        Long reportCount = workReportService.queryReportCount(workReportPageReqVO);
        map.put("report", reportCount);
        return success(map);
    }

    @GetMapping("/getRoleNameByIds")
    public CommonResult<?> getRoleNameByIds(@RequestParam("ids") List<Long> ids) {
        Map<Long, List<Long>> idToRoleIds = ids.stream().collect(Collectors.toMap(id -> id, id -> permissionApi.getRoleIdsByUserId(id)));
        if (CollUtil.isEmpty(idToRoleIds)){
            return null;
        }
        List<RoleReqDTO> roleList = roleApi.getRoleList();
        List<InspectionRoleCommon> roleCommons = Arrays.asList(InspectionRoleCommon.values());
        List<String> codes = roleCommons.stream().map(InspectionRoleCommon::getCode).collect(Collectors.toList());
        return success(idToRoleIds.entrySet().stream().collect(Collectors.toMap(
                Map.Entry::getKey,
                item -> {
                    String name = "未知岗位";
                    if (CollUtil.isEmpty(item.getValue())){
                        return name;
                    }
                    List<RoleReqDTO> roles = roleList.stream().filter(i -> item.getValue().contains(i.getId())).collect(Collectors.toList());
                    if (CollUtil.isEmpty(roles)) {
                        return name;
                    }
                    List<RoleReqDTO> inspectionRoles = roles.stream().filter(i -> codes.contains(i.getCode())).collect(Collectors.toList());
                    if (CollUtil.isEmpty(inspectionRoles)){
                        return name;
                    }
                    Integer index = Integer.MAX_VALUE;
                    for (RoleReqDTO inspectionRole : inspectionRoles) {
                        InspectionRoleCommon inspectionRoleCommon = InspectionRoleCommon.valueOf(inspectionRole.getCode().toUpperCase());
                        if (ObjectUtil.isEmpty(inspectionRoleCommon)) {
                            continue;
                        }
                        Integer weight = inspectionRoleCommon.getWeight();
                        if (weight < index) {
                            index = weight;
                            name = inspectionRole.getName();
                        }
                    }
                    return name;
                })));
    }
}
