package com.sundot.airport.exam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.domain.entity.SysRole;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.exam.domain.DailyTask;
import com.sundot.airport.exam.domain.DailyTaskDetail;
import com.sundot.airport.exam.domain.QuesCat;
import com.sundot.airport.exam.dto.UserProfileDTO;
import com.sundot.airport.exam.dto.UserProfileQueryDTO;
import com.sundot.airport.exam.mapper.DailyTaskDetailMapper;
import com.sundot.airport.exam.mapper.DailyTaskMapper;
import com.sundot.airport.exam.service.IUserProfileService;
import com.sundot.airport.exam.common.service.QuesCatService;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Date;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <b>功能名：</b>UserProfileServiceImpl<br>
 * <b>说明：</b> 用户画像Service实现 <br>
 * <b>著作权：</b> Copyright (C) 2025 SUNDOT CORPORATION<br>
 * <b>修改履历：
 *
 * @author Claude
 */
@Service
public class UserProfileServiceImpl implements IUserProfileService {

    private static final Logger log = LoggerFactory.getLogger(UserProfileServiceImpl.class);

    @Autowired
    private DailyTaskMapper dailyTaskMapper;

    @Autowired
    private DailyTaskDetailMapper dailyTaskDetailMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private QuesCatService quesCatService;

    @Autowired
    private com.sundot.airport.system.service.IBaseCheckCategoryService baseCheckCategoryService;

    @Override
    public UserProfileDTO getUserProfile(UserProfileQueryDTO query) {
        log.info("获取用户画像 - userId: {}, startDate: {}, endDate: {}",
                query.getUserId(), query.getStartDate(), query.getEndDate());

        // 1. 参数校验
        validateQuery(query);

        // 2. 获取用户信息
        SysUser user = userService.selectUserById(query.getUserId());
        if (user == null) {
            throw new ServiceException("用户不存在: userId=" + query.getUserId());
        }

        // 3. 构建用户画像DTO
        UserProfileDTO profile = new UserProfileDTO();
        profile.setUserId(user.getUserId());
        profile.setUserName(user.getNickName());
        profile.setPeriod(query.getStartDate() + " ~ " + query.getEndDate());

        // 设置部门名称
        if (user.getDeptId() != null) {
            SysDept dept = deptService.selectDeptById(user.getDeptId());
            if (dept != null) {
                profile.setDeptName(dept.getDeptName());
            }
        }

        // 设置角色名称
        if (user.getRoles() != null && !user.getRoles().isEmpty()) {
            String roleName = user.getRoles().stream()
                    .map(SysRole::getRoleName)
                    .collect(Collectors.joining(","));
            profile.setRoleName(roleName);
        }

        // 4. 统计测试分数
        profile.setScoreStats(calculateScoreStatistics(query));

        // 5. 统计排名
        profile.setRankingStats(calculateRankingStatistics(query, user));

        // 6. 统计总错题数量
        profile.setTotalErrors(calculateTotalErrors(query));

        // 7. 统计各分类错题数量（动态）
        profile.setCategoryErrors(calculateCategoryErrors(query));

        return profile;
    }

    /**
     * 参数校验
     */
    private void validateQuery(UserProfileQueryDTO query) {
        if (query.getUserId() == null) {
            throw new ServiceException("用户ID不能为空");
        }
        if (query.getStartDate() == null || query.getStartDate().trim().isEmpty()) {
            throw new ServiceException("开始日期不能为空");
        }
        if (query.getEndDate() == null || query.getEndDate().trim().isEmpty()) {
            throw new ServiceException("结束日期不能为空");
        }
    }

    /**
     * 计算分数统计
     */
    private UserProfileDTO.ScoreStatistics calculateScoreStatistics(UserProfileQueryDTO query) {
        UserProfileDTO.ScoreStatistics stats = new UserProfileDTO.ScoreStatistics();

        // 查询用户周期内的所有已完成和已过期任务
        LambdaQueryWrapper<DailyTask> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(DailyTask::getDtUserId, query.getUserId());
        userWrapper.ge(DailyTask::getDtBusinessDate, Date.valueOf(query.getStartDate()));
        userWrapper.le(DailyTask::getDtBusinessDate, Date.valueOf(query.getEndDate()));
        userWrapper.in(DailyTask::getDtStatus, "COMPLETED", "EXPIRED");
        userWrapper.eq(DailyTask::getDelStatus, 0);
        List<DailyTask> userTasks = dailyTaskMapper.selectList(userWrapper);

        if (!userTasks.isEmpty()) {
            // 个体平均分（EXPIRED任务分数算0）
            BigDecimal totalScore = userTasks.stream()
                    .map(task -> "EXPIRED".equals(task.getDtStatus()) ? BigDecimal.ZERO : task.getDtTotalScore())
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            stats.setUserAvgScore(totalScore.divide(new BigDecimal(userTasks.size()), 2, RoundingMode.HALF_UP));

            // 个体最高分（EXPIRED任务分数算0）
            BigDecimal maxScore = userTasks.stream()
                    .map(task -> "EXPIRED".equals(task.getDtStatus()) ? BigDecimal.ZERO : task.getDtTotalScore())
                    .max(BigDecimal::compareTo)
                    .orElse(BigDecimal.ZERO);
            stats.setUserMaxScore(maxScore);

            // 个体最低分（EXPIRED任务分数算0）
            BigDecimal minScore = userTasks.stream()
                    .map(task -> "EXPIRED".equals(task.getDtStatus()) ? BigDecimal.ZERO : task.getDtTotalScore())
                    .min(BigDecimal::compareTo)
                    .orElse(BigDecimal.ZERO);
            stats.setUserMinScore(minScore);
        } else {
            stats.setUserAvgScore(BigDecimal.ZERO);
            stats.setUserMaxScore(BigDecimal.ZERO);
            stats.setUserMinScore(BigDecimal.ZERO);
        }

        // 查询周期内所有用户的已完成和已过期任务(计算总平均分)
        LambdaQueryWrapper<DailyTask> totalWrapper = new LambdaQueryWrapper<>();
        totalWrapper.ge(DailyTask::getDtBusinessDate, Date.valueOf(query.getStartDate()));
        totalWrapper.le(DailyTask::getDtBusinessDate, Date.valueOf(query.getEndDate()));
        totalWrapper.in(DailyTask::getDtStatus, "COMPLETED", "EXPIRED");
        totalWrapper.eq(DailyTask::getDelStatus, 0);
        List<DailyTask> allTasks = dailyTaskMapper.selectList(totalWrapper);

        if (!allTasks.isEmpty()) {
            BigDecimal totalScore = allTasks.stream()
                    .map(task -> "EXPIRED".equals(task.getDtStatus()) ? BigDecimal.ZERO : task.getDtTotalScore())
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            stats.setTotalAvgScore(totalScore.divide(new BigDecimal(allTasks.size()), 2, RoundingMode.HALF_UP));
        } else {
            stats.setTotalAvgScore(BigDecimal.ZERO);
        }

        return stats;
    }

    /**
     * 计算排名统计
     */
    private UserProfileDTO.RankingStatistics calculateRankingStatistics(UserProfileQueryDTO query, SysUser user) {
        UserProfileDTO.RankingStatistics stats = new UserProfileDTO.RankingStatistics();

        // 查询周期内所有用户的平均分
        Map<Long, BigDecimal> userAvgScoreMap = calculateAllUserAvgScores(query);

        // 获取当前用户的平均分
        BigDecimal userAvgScore = userAvgScoreMap.getOrDefault(query.getUserId(), BigDecimal.ZERO);

        // 获取当前用户的部门信息
        if (user.getDeptId() == null) {
            stats.setSiteRanking(0);
            stats.setSiteTotalUsers(0);
            stats.setDeptRanking(0);
            stats.setDeptTotalUsers(0);
            stats.setTeamRanking(0);
            stats.setTeamTotalUsers(0);
            return stats;
        }

        SysDept userDept = deptService.selectDeptById(user.getDeptId());
        if (userDept == null) {
            stats.setSiteRanking(0);
            stats.setSiteTotalUsers(0);
            stats.setDeptRanking(0);
            stats.setDeptTotalUsers(0);
            stats.setTeamRanking(0);
            stats.setTeamTotalUsers(0);
            return stats;
        }

        // 解析部门层级：ancestors格式为 "0,211,205"（root,站级,科级）
        // 用户的dept_id可能是班组ID、科级ID或站级ID
        DeptHierarchy hierarchy = parseDeptHierarchy(userDept);

        // 1. 全站排名（相同站级ID的用户）
        if (hierarchy.siteId != null) {
            Map<Long, BigDecimal> siteUserScores = userAvgScoreMap.entrySet().stream()
                    .filter(entry -> {
                        SysUser u = userService.selectUserById(entry.getKey());
                        if (u == null || u.getDeptId() == null) return false;
                        SysDept dept = deptService.selectDeptById(u.getDeptId());
                        if (dept == null) return false;
                        DeptHierarchy h = parseDeptHierarchy(dept);
                        return hierarchy.siteId.equals(h.siteId);
                    })
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

            List<BigDecimal> siteScores = new ArrayList<>(siteUserScores.values());
            siteScores.sort(Comparator.reverseOrder());

            int siteRanking = 1;
            for (BigDecimal score : siteScores) {
                if (score.compareTo(userAvgScore) > 0) {
                    siteRanking++;
                } else {
                    break;
                }
            }
            stats.setSiteRanking(siteRanking);
            stats.setSiteTotalUsers(siteUserScores.size());
        } else {
            stats.setSiteRanking(0);
            stats.setSiteTotalUsers(0);
        }

        // 2. 本科室排名（相同科级ID的用户）
        if (hierarchy.deptId != null) {
            Map<Long, BigDecimal> deptUserScores = userAvgScoreMap.entrySet().stream()
                    .filter(entry -> {
                        SysUser u = userService.selectUserById(entry.getKey());
                        if (u == null || u.getDeptId() == null) return false;
                        SysDept dept = deptService.selectDeptById(u.getDeptId());
                        if (dept == null) return false;
                        DeptHierarchy h = parseDeptHierarchy(dept);
                        return hierarchy.deptId.equals(h.deptId);
                    })
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

            List<BigDecimal> deptScores = new ArrayList<>(deptUserScores.values());
            deptScores.sort(Comparator.reverseOrder());

            int deptRanking = 1;
            for (BigDecimal score : deptScores) {
                if (score.compareTo(userAvgScore) > 0) {
                    deptRanking++;
                } else {
                    break;
                }
            }
            stats.setDeptRanking(deptRanking);
            stats.setDeptTotalUsers(deptUserScores.size());
        } else {
            stats.setDeptRanking(0);
            stats.setDeptTotalUsers(0);
        }

        // 3. 本班组排名（相同班组ID的用户）
        if (hierarchy.teamId != null) {
            Map<Long, BigDecimal> teamUserScores = userAvgScoreMap.entrySet().stream()
                    .filter(entry -> {
                        SysUser u = userService.selectUserById(entry.getKey());
                        if (u == null || u.getDeptId() == null) return false;
                        SysDept dept = deptService.selectDeptById(u.getDeptId());
                        if (dept == null) return false;
                        DeptHierarchy h = parseDeptHierarchy(dept);
                        return hierarchy.teamId.equals(h.teamId);
                    })
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

            List<BigDecimal> teamScores = new ArrayList<>(teamUserScores.values());
            teamScores.sort(Comparator.reverseOrder());

            int teamRanking = 1;
            for (BigDecimal score : teamScores) {
                if (score.compareTo(userAvgScore) > 0) {
                    teamRanking++;
                } else {
                    break;
                }
            }
            stats.setTeamRanking(teamRanking);
            stats.setTeamTotalUsers(teamUserScores.size());
        } else {
            stats.setTeamRanking(0);
            stats.setTeamTotalUsers(0);
        }

        return stats;
    }

    /**
     * 解析部门层级
     * ancestors格式：0,211,205（root, 站级, 科级）
     * 用户dept_id可能是班组ID、科级ID或站级ID
     */
    private DeptHierarchy parseDeptHierarchy(SysDept dept) {
        DeptHierarchy hierarchy = new DeptHierarchy();

        String ancestors = dept.getAncestors();
        Long deptId = dept.getDeptId();

        if (ancestors == null || ancestors.trim().isEmpty()) {
            // 没有ancestors，当前dept_id可能是站级
            hierarchy.siteId = deptId;
            hierarchy.deptId = deptId;
            hierarchy.teamId = deptId;
            return hierarchy;
        }

        // 分割ancestors：0,211,205
        String[] ancestorIds = ancestors.split(",");

        // ancestors[0] = 0 (root)
        // ancestors[1] = 站级ID
        // ancestors[2] = 科级ID
        // dept_id = 班组ID（如果有3层以上）

        if (ancestorIds.length >= 2) {
            hierarchy.siteId = Long.parseLong(ancestorIds[1].trim());
        }

        if (ancestorIds.length >= 3) {
            hierarchy.deptId = Long.parseLong(ancestorIds[2].trim());
        }

        // 如果ancestors只有2层（0,站级），那么dept_id就是科级
        // 如果ancestors有3层（0,站级,科级），那么dept_id就是班组
        if (ancestorIds.length == 2) {
            // ancestors = "0,211"，dept_id是科级
            hierarchy.deptId = deptId;
            hierarchy.teamId = deptId;
        } else if (ancestorIds.length >= 3) {
            // ancestors = "0,211,205"，dept_id是班组
            hierarchy.teamId = deptId;
        } else {
            // ancestors = "0"，dept_id可能是站级
            hierarchy.siteId = deptId;
            hierarchy.deptId = deptId;
            hierarchy.teamId = deptId;
        }

        return hierarchy;
    }

    /**
     * 部门层级内部类
     */
    private static class DeptHierarchy {
        Long siteId;  // 站级ID
        Long deptId;  // 科级ID
        Long teamId;  // 班组ID
    }

    /**
     * 计算所有用户的平均分
     */
    private Map<Long, BigDecimal> calculateAllUserAvgScores(UserProfileQueryDTO query) {
        // 查询周期内所有已完成和已过期的任务
        LambdaQueryWrapper<DailyTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.ge(DailyTask::getDtBusinessDate, Date.valueOf(query.getStartDate()));
        wrapper.le(DailyTask::getDtBusinessDate, Date.valueOf(query.getEndDate()));
        wrapper.in(DailyTask::getDtStatus, "COMPLETED", "EXPIRED");
        wrapper.eq(DailyTask::getDelStatus, 0);
        List<DailyTask> allTasks = dailyTaskMapper.selectList(wrapper);

        // 按用户分组计算平均分
        Map<Long, List<DailyTask>> userTasksMap = allTasks.stream()
                .collect(Collectors.groupingBy(DailyTask::getDtUserId));

        Map<Long, BigDecimal> userAvgScoreMap = new HashMap<>();
        for (Map.Entry<Long, List<DailyTask>> entry : userTasksMap.entrySet()) {
            List<DailyTask> tasks = entry.getValue();
            if (!tasks.isEmpty()) {
                BigDecimal totalScore = tasks.stream()
                        .map(task -> "EXPIRED".equals(task.getDtStatus()) ? BigDecimal.ZERO : task.getDtTotalScore())
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal avgScore = totalScore.divide(new BigDecimal(tasks.size()), 2, RoundingMode.HALF_UP);
                userAvgScoreMap.put(entry.getKey(), avgScore);
            }
        }

        return userAvgScoreMap;
    }

    /**
     * 计算总错题数量
     */
    private Integer calculateTotalErrors(UserProfileQueryDTO query) {
        // 先查询用户在周期内的所有任务ID（包含COMPLETED和EXPIRED）
        LambdaQueryWrapper<DailyTask> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.eq(DailyTask::getDtUserId, query.getUserId());
        taskWrapper.ge(DailyTask::getDtBusinessDate, Date.valueOf(query.getStartDate()));
        taskWrapper.le(DailyTask::getDtBusinessDate, Date.valueOf(query.getEndDate()));
        taskWrapper.in(DailyTask::getDtStatus, "COMPLETED", "EXPIRED");
        taskWrapper.eq(DailyTask::getDelStatus, 0);
        List<DailyTask> tasks = dailyTaskMapper.selectList(taskWrapper);

        if (tasks.isEmpty()) {
            return 0;
        }

        int totalErrors = 0;

        for (DailyTask task : tasks) {
            if ("EXPIRED".equals(task.getDtStatus())) {
                // EXPIRED任务：所有题目都算错题
                LambdaQueryWrapper<DailyTaskDetail> allWrapper = new LambdaQueryWrapper<>();
                allWrapper.eq(DailyTaskDetail::getDtdTaskId, task.getDtId());
                allWrapper.eq(DailyTaskDetail::getDelStatus, 0);
                totalErrors += dailyTaskDetailMapper.selectCount(allWrapper).intValue();
            } else {
                // COMPLETED任务：只统计错题
                LambdaQueryWrapper<DailyTaskDetail> errorWrapper = new LambdaQueryWrapper<>();
                errorWrapper.eq(DailyTaskDetail::getDtdTaskId, task.getDtId());
                errorWrapper.eq(DailyTaskDetail::getDtdIsCorrect, false);
                errorWrapper.eq(DailyTaskDetail::getDelStatus, 0);
                totalErrors += dailyTaskDetailMapper.selectCount(errorWrapper).intValue();
            }
        }

        return totalErrors;
    }

    /**
     * 计算各分类错题数量（按一级分类统计）
     */
    private List<UserProfileDTO.CategoryErrorStatistics> calculateCategoryErrors(UserProfileQueryDTO query) {
        List<UserProfileDTO.CategoryErrorStatistics> categoryErrorsList = new ArrayList<>();

        // 先查询用户在周期内的所有任务ID（包含COMPLETED和EXPIRED）
        LambdaQueryWrapper<DailyTask> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.eq(DailyTask::getDtUserId, query.getUserId());
        taskWrapper.ge(DailyTask::getDtBusinessDate, Date.valueOf(query.getStartDate()));
        taskWrapper.le(DailyTask::getDtBusinessDate, Date.valueOf(query.getEndDate()));
        taskWrapper.in(DailyTask::getDtStatus, "COMPLETED", "EXPIRED");
        taskWrapper.eq(DailyTask::getDelStatus, 0);
        List<DailyTask> tasks = dailyTaskMapper.selectList(taskWrapper);

        if (tasks.isEmpty()) {
            return categoryErrorsList;
        }

        // 分别处理COMPLETED和EXPIRED任务
        List<DailyTaskDetail> errorDetails = new ArrayList<>();

        for (DailyTask task : tasks) {
            if ("EXPIRED".equals(task.getDtStatus())) {
                // EXPIRED任务：所有题目都算错题
                LambdaQueryWrapper<DailyTaskDetail> allWrapper = new LambdaQueryWrapper<>();
                allWrapper.eq(DailyTaskDetail::getDtdTaskId, task.getDtId());
                allWrapper.eq(DailyTaskDetail::getDelStatus, 0);
                errorDetails.addAll(dailyTaskDetailMapper.selectList(allWrapper));
            } else {
                // COMPLETED任务：只统计错题
                LambdaQueryWrapper<DailyTaskDetail> errorWrapper = new LambdaQueryWrapper<>();
                errorWrapper.eq(DailyTaskDetail::getDtdTaskId, task.getDtId());
                errorWrapper.eq(DailyTaskDetail::getDtdIsCorrect, false);
                errorWrapper.eq(DailyTaskDetail::getDelStatus, 0);
                errorDetails.addAll(dailyTaskDetailMapper.selectList(errorWrapper));
            }
        }

        if (errorDetails.isEmpty()) {
            return categoryErrorsList;
        }

        // 按一级分类分组统计
        Map<String, Integer> level1CategoryErrorCounts = groupErrorsByLevel1Category(errorDetails);

        // 获取所有一级分类
        com.sundot.airport.system.domain.BaseCheckCategory queryParam = new com.sundot.airport.system.domain.BaseCheckCategory();
        queryParam.setLevel(1);
        List<com.sundot.airport.system.domain.BaseCheckCategory> level1Categories =
                baseCheckCategoryService.selectBaseCheckCategoryList(queryParam);

        // 构建一级分类错题统计列表
        for (com.sundot.airport.system.domain.BaseCheckCategory level1Category : level1Categories) {
            String categoryId = String.valueOf(level1Category.getId());
            Integer errorCount = level1CategoryErrorCounts.getOrDefault(categoryId, 0);

            // 只添加有错题的分类
            if (errorCount > 0) {
                UserProfileDTO.CategoryErrorStatistics stats = new UserProfileDTO.CategoryErrorStatistics();
                stats.setCategoryId(categoryId);
                stats.setCategoryName(level1Category.getName());
                stats.setErrorCount(errorCount);
                categoryErrorsList.add(stats);
            }
        }

        // 处理"未分类"的错题
        Integer uncategorizedCount = level1CategoryErrorCounts.getOrDefault(null, 0);
        if (uncategorizedCount > 0) {
            UserProfileDTO.CategoryErrorStatistics uncategorized = new UserProfileDTO.CategoryErrorStatistics();
            uncategorized.setCategoryId(null);
            uncategorized.setCategoryName("未分类");
            uncategorized.setErrorCount(uncategorizedCount);
            categoryErrorsList.add(uncategorized);
        }

        // 按错题数量降序排序
        categoryErrorsList.sort((a, b) -> b.getErrorCount().compareTo(a.getErrorCount()));

        return categoryErrorsList;
    }

    /**
     * 按一级分类分组错题
     * <p>
     * 1. 从DailyTaskDetail中获取二级分类ID（dtdModuleId，即qc_id）
     * 2. 通过qc_id查询edu_cs_ques_cat获取二级分类名称（qc_name）
     * 3. 通过qc_name在base_check_category中查找对应的二级分类（level=2, name=qc_name）
     * 4. 获取该二级分类的parent_id，即为一级分类ID
     * 5. 按一级分类ID分组统计错题数量
     * 6. 如果找不到对应的一级分类，则归入null（未分类）
     * </p>
     */
    private Map<String, Integer> groupErrorsByLevel1Category(List<DailyTaskDetail> errorDetails) {
        Map<String, Integer> result = new HashMap<>();

        // 缓存二级分类名称到一级分类ID的映射
        Map<String, String> level2NameToLevel1IdCache = new HashMap<>();

        for (DailyTaskDetail detail : errorDetails) {
            String qcId = detail.getDtdModuleId(); // 二级分类ID（edu_cs_ques_cat.qc_id）

            if (qcId == null || qcId.trim().isEmpty()) {
                // 未分类
                result.put(null, result.getOrDefault(null, 0) + 1);
                continue;
            }

            // 查询二级分类名称
            LambdaQueryWrapper<QuesCat> catWrapper = new LambdaQueryWrapper<>();
            catWrapper.eq(QuesCat::getQcId, qcId);
            catWrapper.eq(QuesCat::getDelStatus, 0);
            QuesCat quesCat = quesCatService.getOne(catWrapper);

            if (quesCat == null || quesCat.getQcName() == null) {
                // 找不到二级分类，归入未分类
                result.put(null, result.getOrDefault(null, 0) + 1);
                continue;
            }

            String qcName = quesCat.getQcName();

            // 检查缓存
            String level1CategoryId;
            if (level2NameToLevel1IdCache.containsKey(qcName)) {
                level1CategoryId = level2NameToLevel1IdCache.get(qcName);
            } else {
                // 通过二级分类名称查找对应的一级分类
                com.sundot.airport.system.domain.BaseCheckCategory level1Category =
                        baseCheckCategoryService.selectLevel1ByLevel2Name(qcName);

                if (level1Category != null) {
                    level1CategoryId = String.valueOf(level1Category.getId());
                    level2NameToLevel1IdCache.put(qcName, level1CategoryId);
                } else {
                    // 找不到一级分类，归入未分类
                    level1CategoryId = null;
                    level2NameToLevel1IdCache.put(qcName, null);
                }
            }

            // 按一级分类ID统计
            result.put(level1CategoryId, result.getOrDefault(level1CategoryId, 0) + 1);
        }

        return result;
    }
}
