package com.xy.xyaicpzs.jt.jtssq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xy.xyaicpzs.domain.entity.*;
import com.xy.xyaicpzs.domain.vo.SSQSecondStepResultVO;
import com.xy.xyaicpzs.mapper.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 精推双色球第二步算法分析
 */
@Slf4j
@Component
public class FollowBallAnalysis {
    
    @Autowired
    private T3Mapper t3Mapper;
    
    @Autowired
    private T4Mapper t4Mapper;
    
    @Autowired
    private T7Mapper t7Mapper;
    
    @Autowired
    private HistoryTopMapper historyTopMapper;
    
    @Autowired
    private HistoryTop100Mapper historyTop100Mapper;
    
    /**
     * 球号和系数的关联类
     */
    @Data
    public static class BallWithCoefficient {
        private Integer ballNumber;
        private Double coefficient;
        private Integer masterBallNumber; // 主球号，用于标识来源

        public BallWithCoefficient(Integer ballNumber, Double coefficient, Integer masterBallNumber) {
            this.ballNumber = ballNumber;
            this.coefficient = coefficient;
            this.masterBallNumber = masterBallNumber;
        }
    }
    
    /**
     * 精推双色球第二步算法主方法
     * @param level 位置级别（H-高位/M-中位/L-低位）
     * @param redBalls 前6个红球号码
     * @param blueBall 蓝球号码
     * @param nextFirstBall 下期首球号码
     * @return 分析结果
     */
    public SSQSecondStepResultVO analyze(String level, List<Integer> redBalls, Integer blueBall, Integer nextFirstBall) {
        // 参数验证
        validateInputParams(level, redBalls, blueBall, nextFirstBall);
        
        log.info("开始精推双色球第二步分析，策略：{}，红球：{}，蓝球：{}，下期首球：{}", 
                level, redBalls, blueBall, nextFirstBall);
        
        // 用于存储所有候选球号和对应的系数
        Map<Integer, List<BallWithCoefficient>> ballCoefficientMap = new HashMap<>();
        List<Integer> allCandidateBalls = new ArrayList<>();
        
        // Step 1: 根据6个红球号码获取候选球（T3表前26个）
        for (Integer redBall : redBalls) {
            List<BallWithCoefficient> ballsWithCoefficients = getTop26FromT3(redBall);
            for (BallWithCoefficient ball : ballsWithCoefficients) {
                ballCoefficientMap.computeIfAbsent(ball.getBallNumber(), k -> new ArrayList<>()).add(ball);
                allCandidateBalls.add(ball.getBallNumber());
            }
        }
        
        // Step 2: 从history_top_100百期排行获取前3个球号
        List<Integer> top3HistoryTop100 = getTop3FromHistoryTop100();
        allCandidateBalls.addAll(top3HistoryTop100);
        
        // Step 3: 根据蓝球号码获取候选球（T4表前26个）
        List<BallWithCoefficient> blueBallsWithCoefficients = getTop26FromT4(blueBall);
        for (BallWithCoefficient ball : blueBallsWithCoefficients) {
            ballCoefficientMap.computeIfAbsent(ball.getBallNumber(), k -> new ArrayList<>()).add(ball);
            allCandidateBalls.add(ball.getBallNumber());
        }
        
        // Step 4: 根据下期首球号码获取候选球（T7表，根据策略不同）
        List<BallWithCoefficient> nextFirstBallsWithCoefficients = getT7BallsByLevel(nextFirstBall, level);
        for (BallWithCoefficient ball : nextFirstBallsWithCoefficients) {
            ballCoefficientMap.computeIfAbsent(ball.getBallNumber(), k -> new ArrayList<>()).add(ball);
            allCandidateBalls.add(ball.getBallNumber());
        }
        
        // Step 5: 统计分析并生成结果
        List<SSQSecondStepResultVO.BallAnalysisResult> results = analyzeResults(allCandidateBalls, ballCoefficientMap);
        
        return SSQSecondStepResultVO.builder()
                .results(results)
                .strategy(level)
                .redBalls(redBalls)
                .blueBall(blueBall)
                .nextFirstBall(nextFirstBall)
                .build();
    }
    
    /**
     * 从T3表获取前26个球号和系数（如果第26个系数相同则一并加入）
     */
    private List<BallWithCoefficient> getTop26FromT3(Integer masterBallNumber) {
        List<T3> t3List = t3Mapper.selectList(
            new QueryWrapper<T3>()
                .eq("masterBallNumber", masterBallNumber)
                .orderByDesc("lineCoefficient"));
        
        if (CollectionUtils.isEmpty(t3List)) {
            log.warn("T3表中主球{}没有数据", masterBallNumber);
            return new ArrayList<>();
        }
        
        List<BallWithCoefficient> result = new ArrayList<>();
        
        if (t3List.size() <= 26) {
            // 如果总数不超过26个，全部加入
            for (T3 t3 : t3List) {
                result.add(new BallWithCoefficient(t3.getSlaveBallNumber(), t3.getLineCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 先加入前26个
        for (int i = 0; i < 26; i++) {
            T3 t3 = t3List.get(i);
            result.add(new BallWithCoefficient(t3.getSlaveBallNumber(), t3.getLineCoefficient(), masterBallNumber));
        }
        
        // 获取第26个球号的系数
        Double boundaryCoefficient = t3List.get(25).getLineCoefficient();
        
        // 继续查找后面系数相同的球号
        for (int i = 26; i < t3List.size(); i++) {
            T3 t3 = t3List.get(i);
            if (t3.getLineCoefficient().equals(boundaryCoefficient)) {
                result.add(new BallWithCoefficient(t3.getSlaveBallNumber(), t3.getLineCoefficient(), masterBallNumber));
            } else {
                break; // 系数不同，停止查找
            }
        }
        
        return result;
    }
    
    /**
     * 从T4表获取前26个球号和系数（如果第26个系数相同则一并加入）
     */
    private List<BallWithCoefficient> getTop26FromT4(Integer masterBallNumber) {
        List<T4> t4List = t4Mapper.selectList(
            new QueryWrapper<T4>()
                .eq("masterBallNumber", masterBallNumber)
                .orderByDesc("lineCoefficient"));
        
        if (CollectionUtils.isEmpty(t4List)) {
            log.warn("T4表中主球{}没有数据", masterBallNumber);
            return new ArrayList<>();
        }
        
        List<BallWithCoefficient> result = new ArrayList<>();
        
        if (t4List.size() <= 26) {
            // 如果总数不超过26个，全部加入
            for (T4 t4 : t4List) {
                result.add(new BallWithCoefficient(t4.getSlaveBallNumber(), t4.getLineCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 先加入前26个
        for (int i = 0; i < 26; i++) {
            T4 t4 = t4List.get(i);
            result.add(new BallWithCoefficient(t4.getSlaveBallNumber(), t4.getLineCoefficient(), masterBallNumber));
        }
        
        // 获取第26个球号的系数
        Double boundaryCoefficient = t4List.get(25).getLineCoefficient();
        
        // 继续查找后面系数相同的球号
        for (int i = 26; i < t4List.size(); i++) {
            T4 t4 = t4List.get(i);
            if (t4.getLineCoefficient().equals(boundaryCoefficient)) {
                result.add(new BallWithCoefficient(t4.getSlaveBallNumber(), t4.getLineCoefficient(), masterBallNumber));
            } else {
                break; // 系数不同，停止查找
            }
        }
        
        return result;
    }
    
    /**
     * 从history_top_100获取前3个球号（按点系数排行，处理边界相同系数）
     */
    private List<Integer> getTop3FromHistoryTop100() {
        List<HistoryTop100> historyTop100List = historyTop100Mapper.selectList(
            new QueryWrapper<HistoryTop100>()
                .orderByDesc("pointCoefficient"));
        
        if (CollectionUtils.isEmpty(historyTop100List)) {
            log.warn("百期排行表数据为空");
            return new ArrayList<>();
        }
        
        List<Integer> result = new ArrayList<>();
        int index = 0;
        int addedCount = 0;
        
        while (addedCount < 3 && index < historyTop100List.size()) {
            double currentCoefficient = historyTop100List.get(index).getPointCoefficient();
            List<Integer> sameCoefficientBalls = new ArrayList<>();
            
            // 收集所有相同系数的球号
            while (index < historyTop100List.size() && 
                   historyTop100List.get(index).getPointCoefficient().equals(currentCoefficient)) {
                sameCoefficientBalls.add(historyTop100List.get(index).getBallNumber());
                index++;
            }
            
            // 计算还需要多少个球
            int needCount = Math.min(3 - addedCount, sameCoefficientBalls.size());
            
            if (sameCoefficientBalls.size() == 1) {
                // 只有一个球号，直接加入
                result.add(sameCoefficientBalls.get(0));
                addedCount++;
            } else if (needCount == sameCoefficientBalls.size()) {
                // 需要选择的数量等于可用数量，全部加入
                result.addAll(sameCoefficientBalls);
                addedCount += sameCoefficientBalls.size();
            } else {
                // 需要从多个相同系数的球号中选择部分，处理边界冲突
                List<Integer> selectedBalls = handleSSQHistoryBoundaryConflicts(sameCoefficientBalls, needCount);
                result.addAll(selectedBalls);
                addedCount += selectedBalls.size();
            }
        }
        
        return result;
    }
    
    /**
     * 根据级别从T7表获取候选球号和系数
     */
    private List<BallWithCoefficient> getT7BallsByLevel(Integer masterBallNumber, String level) {
        List<T7> t7List = t7Mapper.selectList(
            new QueryWrapper<T7>()
                .eq("masterBallNumber", masterBallNumber)
                .orderByDesc("faceCoefficient"));
        
        if (CollectionUtils.isEmpty(t7List)) {
            log.warn("T7表中主球{}没有数据", masterBallNumber);
            return new ArrayList<>();
        }
        
        if ("H".equalsIgnoreCase(level)) {
            return getHighLevelBallsFromT7(t7List, masterBallNumber);
        } else if ("M".equalsIgnoreCase(level)) {
            return getMiddleLevelBallsFromT7(t7List, masterBallNumber);
        } else { // L
            return getLowLevelBallsFromT7(t7List, masterBallNumber);
        }
    }
    
    /**
     * 高位策略：从T7表获取系数最大的前10个球号（如果第10个系数相同则一并加入）
     */
    private List<BallWithCoefficient> getHighLevelBallsFromT7(List<T7> t7List, Integer masterBallNumber) {
        List<BallWithCoefficient> result = new ArrayList<>();
        
        if (t7List.size() <= 10) {
            // 如果总数不超过10个，全部加入
            for (T7 t7 : t7List) {
                result.add(new BallWithCoefficient(t7.getSlaveBallNumber(), t7.getFaceCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 先加入前10个
        for (int i = 0; i < 10; i++) {
            T7 t7 = t7List.get(i);
            result.add(new BallWithCoefficient(t7.getSlaveBallNumber(), t7.getFaceCoefficient(), masterBallNumber));
        }
        
        // 获取第10个球号的系数
        Double boundaryCoefficient = t7List.get(9).getFaceCoefficient();
        
        // 继续查找后面系数相同的球号
        for (int i = 10; i < t7List.size(); i++) {
            T7 t7 = t7List.get(i);
            if (t7.getFaceCoefficient().equals(boundaryCoefficient)) {
                result.add(new BallWithCoefficient(t7.getSlaveBallNumber(), t7.getFaceCoefficient(), masterBallNumber));
            } else {
                break; // 系数不同，停止查找
            }
        }
        
        return result;
    }
    
    /**
     * 中位策略：从T7表获取平均值附近10个球号（向上5个，向下4个，边界系数相同则一并加入）
     */
    private List<BallWithCoefficient> getMiddleLevelBallsFromT7(List<T7> t7List, Integer masterBallNumber) {
        if (t7List.size() < 10) {
            log.warn("T7表数据不足10条，实际{}条", t7List.size());
            List<BallWithCoefficient> result = new ArrayList<>();
            for (T7 t7 : t7List) {
                result.add(new BallWithCoefficient(t7.getSlaveBallNumber(), t7.getFaceCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 计算平均系数（保留两位小数，截断方式）
        double avgCoefficient = t7List.stream()
                .mapToDouble(T7::getFaceCoefficient)
                .average()
                .orElse(0.0);
        // 截断到两位小数
        avgCoefficient = Math.floor(avgCoefficient * 100) / 100;
        
        // 找到第一个比平均值大的位置（从下到上遍历）
        int avgPosition = -1;
        for (int i = t7List.size() - 1; i >= 0; i--) {
            if (t7List.get(i).getFaceCoefficient() >= avgCoefficient) {
                avgPosition = i;
                break;
            }
        }
        
        if (avgPosition == -1) {
            avgPosition = 0; // 如果没找到，取第一个
        }
        
        List<BallWithCoefficient> result = new ArrayList<>();
        
        // 先加入平均值位置的球号
        result.add(new BallWithCoefficient(t7List.get(avgPosition).getSlaveBallNumber(), 
                t7List.get(avgPosition).getFaceCoefficient(), masterBallNumber));
        
        // 向上取5个球号，处理边界系数相同情况
        int upCount = 0;
        Double upBoundaryCoeff = null;
        for (int i = avgPosition - 1; i >= 0 && upCount < 5; i--) {
            result.add(new BallWithCoefficient(t7List.get(i).getSlaveBallNumber(), 
                    t7List.get(i).getFaceCoefficient(), masterBallNumber));
            upCount++;
            if (upCount == 5) {
                upBoundaryCoeff = t7List.get(i).getFaceCoefficient();
            }
        }
        
        // 向上边界处理：继续添加与第5个球号系数相同的球号
        if (upBoundaryCoeff != null) {
            for (int i = avgPosition - 6; i >= 0; i--) {
                if (t7List.get(i).getFaceCoefficient().equals(upBoundaryCoeff)) {
                    result.add(new BallWithCoefficient(t7List.get(i).getSlaveBallNumber(), 
                            t7List.get(i).getFaceCoefficient(), masterBallNumber));
                } else {
                    break;
                }
            }
        }
        
        // 向下取4个球号，处理边界系数相同情况
        int downCount = 0;
        Double downBoundaryCoeff = null;
        for (int i = avgPosition + 1; i < t7List.size() && downCount < 4; i++) {
            result.add(new BallWithCoefficient(t7List.get(i).getSlaveBallNumber(), 
                    t7List.get(i).getFaceCoefficient(), masterBallNumber));
            downCount++;
            if (downCount == 4) {
                downBoundaryCoeff = t7List.get(i).getFaceCoefficient();
            }
        }
        
        // 向下边界处理：继续添加与第4个球号系数相同的球号
        if (downBoundaryCoeff != null) {
            for (int i = avgPosition + 5; i < t7List.size(); i++) {
                if (t7List.get(i).getFaceCoefficient().equals(downBoundaryCoeff)) {
                    result.add(new BallWithCoefficient(t7List.get(i).getSlaveBallNumber(), 
                            t7List.get(i).getFaceCoefficient(), masterBallNumber));
                } else {
                    break;
                }
            }
        }
        
        return result;
    }
    
    /**
     * 低位策略：从T7表获取最小值向上第3-12个球（共10个球，边界系数相同则一并加入）
     */
    private List<BallWithCoefficient> getLowLevelBallsFromT7(List<T7> t7List, Integer masterBallNumber) {
        if (t7List.size() < 12) {
            log.warn("T7表数据不足12条，实际{}条", t7List.size());
            List<BallWithCoefficient> result = new ArrayList<>();
            for (T7 t7 : t7List) {
                result.add(new BallWithCoefficient(t7.getSlaveBallNumber(), t7.getFaceCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 取最小值向上第3-12个球（t7List已按系数降序排列，最后的是最小的）
        // 最小值在最后，向上第3个就是值数组的第 size-3 个，向上第12个就是值数组的第 size-12 个
        List<BallWithCoefficient> result = new ArrayList<>();
        int startIndex = Math.max(0, t7List.size() - 12); // 第3位
        int endIndex = t7List.size() - 3; // 第12位
        
        // 先加入基本的10个球号
        for (int i = startIndex; i <= endIndex; i++) {
            T7 t7 = t7List.get(i);
            result.add(new BallWithCoefficient(t7.getSlaveBallNumber(), t7.getFaceCoefficient(), masterBallNumber));
        }
        
        // 处理起始边界：第1个球号（startIndex）系数相同情况
        if (startIndex > 0) {
            Double startBoundaryCoeff = t7List.get(startIndex).getFaceCoefficient();
            
            // 继续向前查找系数相同的球号
            for (int i = startIndex - 1; i >= 0; i--) {
                if (t7List.get(i).getFaceCoefficient().equals(startBoundaryCoeff)) {
                    result.add(new BallWithCoefficient(t7List.get(i).getSlaveBallNumber(), 
                            t7List.get(i).getFaceCoefficient(), masterBallNumber));
                } else {
                    break; // 系数不同，停止查找
                }
            }
        }
        
        // 处理结束边界：第10个球号（endIndex）系数相同情况
        if (endIndex < t7List.size() - 1) {
            Double endBoundaryCoeff = t7List.get(endIndex).getFaceCoefficient();
            
            // 继续向后查找系数相同的球号
            for (int i = endIndex + 1; i < t7List.size(); i++) {
                if (t7List.get(i).getFaceCoefficient().equals(endBoundaryCoeff)) {
                    result.add(new BallWithCoefficient(t7List.get(i).getSlaveBallNumber(), 
                            t7List.get(i).getFaceCoefficient(), masterBallNumber));
                } else {
                    break; // 系数不同，停止查找
                }
            }
        }
        
        return result;
    }
    
    /**
     * 处理SSQ历史排行边界冲突，选择指定数量的球号
     * @param candidateBalls 候选球号列表
     * @param selectCount 需要选择的数量
     * @return 选中的球号列表
     */
    private List<Integer> handleSSQHistoryBoundaryConflicts(List<Integer> candidateBalls, int selectCount) {
        if (CollectionUtils.isEmpty(candidateBalls) || selectCount <= 0) {
            return new ArrayList<>();
        }
        
        if (selectCount >= candidateBalls.size()) {
            return new ArrayList<>(candidateBalls);
        }
        
        // 使用history_top表进行筛选
        return selectFromHistoryTop(candidateBalls, selectCount);
    }
    
    /**
     * 从history_top表中选择指定数量的球号
     */
    private List<Integer> selectFromHistoryTop(List<Integer> candidateBalls, int selectCount) {
        if (CollectionUtils.isEmpty(candidateBalls) || selectCount <= 0) {
            return new ArrayList<>();
        }
        
        if (selectCount >= candidateBalls.size()) {
            return new ArrayList<>(candidateBalls);
        }
        
        // 获取在history_top表中的系数
        Map<Integer, Double> topCoefficients = new HashMap<>();
        for (Integer ball : candidateBalls) {
            HistoryTop record = historyTopMapper.selectOne(
                new QueryWrapper<HistoryTop>()
                    .eq("ballNumber", ball));
            if (record != null) {
                topCoefficients.put(ball, record.getPointCoefficient());
            } else {
                topCoefficients.put(ball, 0.0);
            }
        }
        
        // 按系数降序排序，选择前selectCount个
        List<Map.Entry<Integer, Double>> sortedByTop = topCoefficients.entrySet().stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .collect(Collectors.toList());
        
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < Math.min(selectCount, sortedByTop.size()); i++) {
            result.add(sortedByTop.get(i).getKey());
        }
        
        // 如果仍然不够，按原始顺序补充
        while (result.size() < selectCount && result.size() < candidateBalls.size()) {
            for (Integer ball : candidateBalls) {
                if (!result.contains(ball) && result.size() < selectCount) {
                    result.add(ball);
                }
            }
        }
        
        return result;
    }
    
    /**
     * 统计分析并生成结果
     */
    private List<SSQSecondStepResultVO.BallAnalysisResult> analyzeResults(
            List<Integer> allCandidateBalls, 
            Map<Integer, List<BallWithCoefficient>> ballCoefficientMap) {
        
        // 统计球号出现次数
        Map<Integer, Integer> ballFrequencyMap = new HashMap<>();
        for (Integer ball : allCandidateBalls) {
            ballFrequencyMap.put(ball, ballFrequencyMap.getOrDefault(ball, 0) + 1);
        }
        
        // 计算系数和
        Map<Integer, Double> ballCoefficientSumMap = new HashMap<>();
        for (Map.Entry<Integer, List<BallWithCoefficient>> entry : ballCoefficientMap.entrySet()) {
            Integer ballNumber = entry.getKey();
            List<BallWithCoefficient> coefficients = entry.getValue();
            double sum = coefficients.stream()
                    .mapToDouble(BallWithCoefficient::getCoefficient)
                    .sum();
            ballCoefficientSumMap.put(ballNumber, sum);
        }
        
        // 获取所有有排行数据的球号（包括频次为0的球号）
        Set<Integer> allBallsWithRanking = getAllBallsWithRanking();
        
        // 获取百期排位和历史排位
        Map<Integer, Integer> top100RankingMap = getTop100Rankings(allBallsWithRanking);
        Map<Integer, Integer> historyRankingMap = getHistoryRankings(allBallsWithRanking);
        
        // 组装结果
        List<SSQSecondStepResultVO.BallAnalysisResult> results = new ArrayList<>();
        for (Integer ballNumber : allBallsWithRanking) {
            SSQSecondStepResultVO.BallAnalysisResult result = SSQSecondStepResultVO.BallAnalysisResult.builder()
                    .ballNumber(ballNumber)
                    .frequency(ballFrequencyMap.getOrDefault(ballNumber, 0))
                    .coefficientSum(ballCoefficientSumMap.getOrDefault(ballNumber, 0.0))
                    .top100Ranking(top100RankingMap.get(ballNumber))
                    .historyRanking(historyRankingMap.get(ballNumber))
                    .build();
            results.add(result);
        }
        
        // 按出现次数降序排列，次数相同的按球号升序排列
        results.sort((a, b) -> {
            int frequencyCompare = b.getFrequency().compareTo(a.getFrequency());
            if (frequencyCompare != 0) {
                return frequencyCompare;
            }
            return a.getBallNumber().compareTo(b.getBallNumber());
        });
        
        return results;
    }
    
    /**
     * 获取所有有排行数据的球号（包括频次为0的球号）
     */
    private Set<Integer> getAllBallsWithRanking() {
        Set<Integer> allBalls = new HashSet<>();
        
        // 从百期排行表获取所有球号
        List<HistoryTop100> top100List = historyTop100Mapper.selectList(
            new QueryWrapper<HistoryTop100>());
        for (HistoryTop100 item : top100List) {
            allBalls.add(item.getBallNumber());
        }
        
        // 从历史排行表获取所有球号
        List<HistoryTop> historyTopList = historyTopMapper.selectList(
            new QueryWrapper<HistoryTop>());
        for (HistoryTop item : historyTopList) {
            allBalls.add(item.getBallNumber());
        }
        
        return allBalls;
    }
    
    /**
     * 获取球号在百期排行表中的排位
     */
    private Map<Integer, Integer> getTop100Rankings(Set<Integer> ballNumbers) {
        Map<Integer, Integer> result = new HashMap<>();
        
        // 直接查询指定球号的排行数据，使用表中的no字段作为排名
        List<HistoryTop100> top100List = historyTop100Mapper.selectList(
            new QueryWrapper<HistoryTop100>()
                .in("ballNumber", ballNumbers));
        
        // 使用表中的no字段作为排名
        for (HistoryTop100 item : top100List) {
            result.put(item.getBallNumber(), item.getNo());
        }
        
        // 对于没有在百期排行表中的球号，设置为null
        for (Integer ballNumber : ballNumbers) {
            if (!result.containsKey(ballNumber)) {
                result.put(ballNumber, null);
            }
        }
        
        return result;
    }
    
    /**
     * 获取球号在历史排行表中的排位
     */
    private Map<Integer, Integer> getHistoryRankings(Set<Integer> ballNumbers) {
        Map<Integer, Integer> result = new HashMap<>();
        
        // 直接查询指定球号的排行数据，使用表中的no字段作为排名
        List<HistoryTop> historyTopList = historyTopMapper.selectList(
            new QueryWrapper<HistoryTop>()
                .in("ballNumber", ballNumbers));
        
        // 使用表中的no字段作为排名
        for (HistoryTop item : historyTopList) {
            result.put(item.getBallNumber(), item.getNo());
        }
        
        // 对于没有在历史排行表中的球号，设置为null
        for (Integer ballNumber : ballNumbers) {
            if (!result.containsKey(ballNumber)) {
                result.put(ballNumber, null);
            }
        }
        
        return result;
    }
    
    /**
     * 参数验证
     */
    private void validateInputParams(String level, List<Integer> redBalls, Integer blueBall, Integer nextFirstBall) {
        if (!"H".equalsIgnoreCase(level) && !"M".equalsIgnoreCase(level) && !"L".equalsIgnoreCase(level)) {
            throw new IllegalArgumentException("位置级别必须是H/M/L之一");
        }
        
        if (CollectionUtils.isEmpty(redBalls) || redBalls.size() != 6) {
            throw new IllegalArgumentException("红球号码必须为6个");
        }
        
        if (blueBall == null || blueBall < 1 || blueBall > 16) {
            throw new IllegalArgumentException("蓝球号码范围应为1-16");
        }
        
        if (nextFirstBall == null || nextFirstBall < 1 || nextFirstBall > 33) {
            throw new IllegalArgumentException("下期首球号码范围应为1-33");
        }
        
        for (Integer redBall : redBalls) {
            if (redBall < 1 || redBall > 33) {
                throw new IllegalArgumentException("红球号码范围应为1-33");
            }
        }
    }
}
