package com.xy.xyaicpzs.jt.jtdlt;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xy.xyaicpzs.domain.entity.*;
import com.xy.xyaicpzs.domain.vo.DLTSecondStepResultVO;
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 FollowFrontBallAnalysis {
    
    @Autowired
    private D9Mapper d9Mapper;
    
    @Autowired
    private D12Mapper d12Mapper;
    
    @Autowired
    private D5Mapper d5Mapper;
    
    @Autowired
    private DltFrontendHistoryTopMapper dltFrontendHistoryTopMapper;
    
    @Autowired
    private DltFrontendHistoryTop100Mapper dltFrontendHistoryTop100Mapper;
    
    /**
     * 球号和系数的关联类
     */
    @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 previousFrontBalls 上期前区5个球号
     * @param previousBackBalls 上期后区2个球号
     * @param currentFirstBall 本期首球号码
     * @return 分析结果
     */
    public DLTSecondStepResultVO analyze(String level, List<Integer> previousFrontBalls, 
                                         List<Integer> previousBackBalls, Integer currentFirstBall) {
        // 参数验证
        validateInputParams(level, previousFrontBalls, previousBackBalls, currentFirstBall);
        
        log.info("开始精推大乐透第二步分析，策略：{}，上期前区：{}，上期后区：{}，本期首球：{}", 
                level, previousFrontBalls, previousBackBalls, currentFirstBall);
        
        // 用于存储所有候选球号和对应的系数
        Map<Integer, List<BallWithCoefficient>> ballCoefficientMap = new HashMap<>();
        List<Integer> allCandidateBalls = new ArrayList<>();
        
        // Step 1: 根据5个上期前区球号从D9表获取候选球（取30个）
        for (Integer frontBall : previousFrontBalls) {
            List<BallWithCoefficient> ballsWithCoefficients = getD9BallsByLevel(frontBall, level);
            for (BallWithCoefficient ball : ballsWithCoefficients) {
                ballCoefficientMap.computeIfAbsent(ball.getBallNumber(), k -> new ArrayList<>()).add(ball);
                allCandidateBalls.add(ball.getBallNumber());
            }
        }
        
        // Step 2: 从dlt_frontend_history_top取平均值向上连续3个球号
        List<Integer> top3HistoryTop = getTop3FromDltFrontendHistoryTopByAvg();
        allCandidateBalls.addAll(top3HistoryTop);
        
        // Step 3: 从dlt_frontend_history_top_100取平均值向上连续3个球号
        List<Integer> top3HistoryTop100 = getTop3FromDltFrontendHistoryTop100ByAvg();
        allCandidateBalls.addAll(top3HistoryTop100);
        
        // Step 4: 根据2个上期后区球号从D12表获取候选球（取30个）
        for (Integer backBall : previousBackBalls) {
            List<BallWithCoefficient> ballsWithCoefficients = getD12BallsByLevel(backBall, level);
            for (BallWithCoefficient ball : ballsWithCoefficients) {
                ballCoefficientMap.computeIfAbsent(ball.getBallNumber(), k -> new ArrayList<>()).add(ball);
                allCandidateBalls.add(ball.getBallNumber());
            }
        }
        
        // Step 5: 根据本期首球从D5表获取候选球（取11个）
        List<BallWithCoefficient> ballsFromD5 = getD5BallsByLevel(currentFirstBall, level);
        for (BallWithCoefficient ball : ballsFromD5) {
            ballCoefficientMap.computeIfAbsent(ball.getBallNumber(), k -> new ArrayList<>()).add(ball);
            allCandidateBalls.add(ball.getBallNumber());
        }
        
        // Step 6: 统计分析并生成结果
        List<DLTSecondStepResultVO.BallAnalysisResult> results = analyzeResults(allCandidateBalls, ballCoefficientMap);
        
        return DLTSecondStepResultVO.builder()
                .results(results)
                .strategy(level)
                .previousFrontBalls(previousFrontBalls)
                .previousBackBalls(previousBackBalls)
                .currentFirstBall(currentFirstBall)
                .build();
    }
    
    /**
     * 根据级别从D9表获取候选球号和系数（取30个，如果第30个系数相同则一并加入）
     */
    private List<BallWithCoefficient> getD9BallsByLevel(Integer masterBallNumber, String level) {
        List<D9> d9List = d9Mapper.selectList(
            new QueryWrapper<D9>()
                .eq("masterBallNumber", masterBallNumber)
                .orderByDesc("coefficient"));
        
        if (CollectionUtils.isEmpty(d9List)) {
            log.warn("D9表中主球{}没有数据", masterBallNumber);
            return new ArrayList<>();
        }
        
        // 所有策略都取前30个，如果第30个系数相同则一并加入
        List<BallWithCoefficient> result = new ArrayList<>();
        
        if (d9List.size() <= 30) {
            // 如果总数不超过30个，全部加入
            for (D9 d9 : d9List) {
                result.add(new BallWithCoefficient(d9.getSlaveBallNumber(), d9.getCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 先加入前30个
        for (int i = 0; i < 30; i++) {
            D9 d9 = d9List.get(i);
            result.add(new BallWithCoefficient(d9.getSlaveBallNumber(), d9.getCoefficient(), masterBallNumber));
        }
        
        // 获取第30个球号的系数
        Double boundaryCoefficient = d9List.get(29).getCoefficient();
        
        // 继续查找后面系数相同的球号
        for (int i = 30; i < d9List.size(); i++) {
            D9 d9 = d9List.get(i);
            if (d9.getCoefficient().equals(boundaryCoefficient)) {
                result.add(new BallWithCoefficient(d9.getSlaveBallNumber(), d9.getCoefficient(), masterBallNumber));
            } else {
                break; // 系数不同，停止查找
            }
        }
        
        return result;
    }
    
    /**
     * 根据级别从D12表获取候选球号和系数（取30个，如果第30个系数相同则一并加入）
     */
    private List<BallWithCoefficient> getD12BallsByLevel(Integer masterBallNumber, String level) {
        List<D12> d12List = d12Mapper.selectList(
            new QueryWrapper<D12>()
                .eq("masterBallNumber", masterBallNumber)
                .orderByDesc("coefficient"));
        
        if (CollectionUtils.isEmpty(d12List)) {
            log.warn("D12表中主球{}没有数据", masterBallNumber);
            return new ArrayList<>();
        }
        
        // 所有策略都取前30个，如果第30个系数相同则一并加入
        List<BallWithCoefficient> result = new ArrayList<>();
        
        if (d12List.size() <= 30) {
            // 如果总数不超过30个，全部加入
            for (D12 d12 : d12List) {
                result.add(new BallWithCoefficient(d12.getSlaveBallNumber(), d12.getCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 先加入前30个
        for (int i = 0; i < 30; i++) {
            D12 d12 = d12List.get(i);
            result.add(new BallWithCoefficient(d12.getSlaveBallNumber(), d12.getCoefficient(), masterBallNumber));
        }
        
        // 获取第30个球号的系数
        Double boundaryCoefficient = d12List.get(29).getCoefficient();
        
        // 继续查找后面系数相同的球号
        for (int i = 30; i < d12List.size(); i++) {
            D12 d12 = d12List.get(i);
            if (d12.getCoefficient().equals(boundaryCoefficient)) {
                result.add(new BallWithCoefficient(d12.getSlaveBallNumber(), d12.getCoefficient(), masterBallNumber));
            } else {
                break; // 系数不同，停止查找
            }
        }
        
        return result;
    }
    
    /**
     * 根据级别从D5表获取候选球号和系数（取11个）
     */
    private List<BallWithCoefficient> getD5BallsByLevel(Integer masterBallNumber, String level) {
        List<D5> d5List = d5Mapper.selectList(
            new QueryWrapper<D5>()
                .eq("masterBallNumber", masterBallNumber)
                .orderByDesc("coefficient"));
        
        if (CollectionUtils.isEmpty(d5List)) {
            log.warn("D5表中主球{}没有数据", masterBallNumber);
            return new ArrayList<>();
        }
        
        if ("H".equalsIgnoreCase(level)) {
            return getHighLevelBallsFromD5(d5List, masterBallNumber);
        } else if ("M".equalsIgnoreCase(level)) {
            return getMiddleLevelBallsFromD5(d5List, masterBallNumber);
        } else { // L
            return getLowLevelBallsFromD5(d5List, masterBallNumber);
        }
    }
    
    /**
     * 高位策略：从D5表获取系数最大的前11个球号（如果第11个系数相同则一并加入）
     */
    private List<BallWithCoefficient> getHighLevelBallsFromD5(List<D5> d5List, Integer masterBallNumber) {
        List<BallWithCoefficient> result = new ArrayList<>();
        
        if (d5List.size() <= 11) {
            // 如果总数不超过11个，全部加入
            for (D5 d5 : d5List) {
                result.add(new BallWithCoefficient(d5.getSlaveBallNumber(), d5.getCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 先加入前11个
        for (int i = 0; i < 11; i++) {
            D5 d5 = d5List.get(i);
            result.add(new BallWithCoefficient(d5.getSlaveBallNumber(), d5.getCoefficient(), masterBallNumber));
        }
        
        // 获取第11个球号的系数
        Double boundaryCoefficient = d5List.get(10).getCoefficient();
        
        // 继续查找后面系数相同的球号
        for (int i = 11; i < d5List.size(); i++) {
            D5 d5 = d5List.get(i);
            if (d5.getCoefficient().equals(boundaryCoefficient)) {
                result.add(new BallWithCoefficient(d5.getSlaveBallNumber(), d5.getCoefficient(), masterBallNumber));
            } else {
                break; // 系数不同，停止查找
            }
        }
        
        return result;
    }
    
    /**
     * 中位策略：从D5表获取平均值附近的11个球号（向上5个，向下5个，边界系数相同则一并加入）
     */
    private List<BallWithCoefficient> getMiddleLevelBallsFromD5(List<D5> d5List, Integer masterBallNumber) {
        if (d5List.size() < 11) {
            log.warn("D5表数据不足11条，实际{}条", d5List.size());
            List<BallWithCoefficient> result = new ArrayList<>();
            for (D5 d5 : d5List) {
                result.add(new BallWithCoefficient(d5.getSlaveBallNumber(), d5.getCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 计算平均系数（保留两位小数，截断方式）
        double avgCoefficient = d5List.stream()
                .mapToDouble(D5::getCoefficient)
                .average()
                .orElse(0.0);
        // 截断到两位小数
        avgCoefficient = Math.floor(avgCoefficient * 100) / 100;
        
        // 找到第一个比平均值大的位置（从下到上遍历）
        int avgPosition = -1;
        for (int i = d5List.size() - 1; i >= 0; i--) {
            if (d5List.get(i).getCoefficient() >= avgCoefficient) {
                avgPosition = i;
                break;
            }
        }
        
        if (avgPosition == -1) {
            avgPosition = 0; // 如果没找到，取第一个
        }
        
        List<BallWithCoefficient> result = new ArrayList<>();
        
        // 先加入平均值位置的球号
        result.add(new BallWithCoefficient(d5List.get(avgPosition).getSlaveBallNumber(), 
                d5List.get(avgPosition).getCoefficient(), masterBallNumber));
        
        // 向上取5个球号，处理边界系数相同情况
        int upCount = 0;
        Double upBoundaryCoeff = null;
        for (int i = avgPosition - 1; i >= 0 && upCount < 5; i--) {
            result.add(new BallWithCoefficient(d5List.get(i).getSlaveBallNumber(), 
                    d5List.get(i).getCoefficient(), masterBallNumber));
            upCount++;
            if (upCount == 5) {
                upBoundaryCoeff = d5List.get(i).getCoefficient();
            }
        }
        
        // 向上边界处理：继续添加与第5个球号系数相同的球号
        if (upBoundaryCoeff != null) {
            for (int i = avgPosition - 6; i >= 0; i--) {
                if (d5List.get(i).getCoefficient().equals(upBoundaryCoeff)) {
                    result.add(new BallWithCoefficient(d5List.get(i).getSlaveBallNumber(), 
                            d5List.get(i).getCoefficient(), masterBallNumber));
                } else {
                    break;
                }
            }
        }
        
        // 向下取5个球号，处理边界系数相同情况
        int downCount = 0;
        Double downBoundaryCoeff = null;
        for (int i = avgPosition + 1; i < d5List.size() && downCount < 5; i++) {
            result.add(new BallWithCoefficient(d5List.get(i).getSlaveBallNumber(), 
                    d5List.get(i).getCoefficient(), masterBallNumber));
            downCount++;
            if (downCount == 5) {
                downBoundaryCoeff = d5List.get(i).getCoefficient();
            }
        }
        
        // 向下边界处理：继续添加与第5个球号系数相同的球号
        if (downBoundaryCoeff != null) {
            for (int i = avgPosition + 6; i < d5List.size(); i++) {
                if (d5List.get(i).getCoefficient().equals(downBoundaryCoeff)) {
                    result.add(new BallWithCoefficient(d5List.get(i).getSlaveBallNumber(), 
                            d5List.get(i).getCoefficient(), masterBallNumber));
                } else {
                    break;
                }
            }
        }
        
        return result;
    }
    
    /**
     * 低位策略：从D5表获取系数最小值（含最小值）向上第3-13的球，共11个球号（边界系数相同则一并加入）
     */
    private List<BallWithCoefficient> getLowLevelBallsFromD5(List<D5> d5List, Integer masterBallNumber) {
        if (d5List.size() < 13) {
            log.warn("D5表数据不足13条，实际{}条", d5List.size());
            List<BallWithCoefficient> result = new ArrayList<>();
            for (D5 d5 : d5List) {
                result.add(new BallWithCoefficient(d5.getSlaveBallNumber(), d5.getCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 从最小值向上第3-13的球（d5List已按系数降序排列）
        // 最小值在最后，向上第3-13就是从倒数第13个到倒数第3个
        List<BallWithCoefficient> result = new ArrayList<>();
        int size = d5List.size();
        int startIndex = size - 13; // 倒数第13个
        int endIndex = size - 3;     // 倒数第3个
        
        // 先加入基本的11个球号
        for (int i = startIndex; i <= endIndex; i++) {
            D5 d5 = d5List.get(i);
            result.add(new BallWithCoefficient(d5.getSlaveBallNumber(), d5.getCoefficient(), masterBallNumber));
        }
        
        // 处理起始边界：第1个球号（startIndex）系数相同情况
        if (startIndex > 0) {
            Double startBoundaryCoeff = d5List.get(startIndex).getCoefficient();
            
            // 继续向前查找系数相同的球号
            for (int i = startIndex - 1; i >= 0; i--) {
                if (d5List.get(i).getCoefficient().equals(startBoundaryCoeff)) {
                    result.add(new BallWithCoefficient(d5List.get(i).getSlaveBallNumber(), 
                            d5List.get(i).getCoefficient(), masterBallNumber));
                } else {
                    break; // 系数不同，停止查找
                }
            }
        }
        
        // 处理结束边界：第11个球号（endIndex）系数相同情况
        if (endIndex < d5List.size() - 1) {
            Double endBoundaryCoeff = d5List.get(endIndex).getCoefficient();
            
            // 继续向后查找系数相同的球号
            for (int i = endIndex + 1; i < d5List.size(); i++) {
                if (d5List.get(i).getCoefficient().equals(endBoundaryCoeff)) {
                    result.add(new BallWithCoefficient(d5List.get(i).getSlaveBallNumber(), 
                            d5List.get(i).getCoefficient(), masterBallNumber));
                } else {
                    break; // 系数不同，停止查找
                }
            }
        }
        
        return result;
    }
    
    /**
     * 从dlt_frontend_history_top取平均值向上连续3个球号（按系数排行，处理边界相同系数）
     */
    private List<Integer> getTop3FromDltFrontendHistoryTopByAvg() {
        List<DltFrontendHistoryTop> allHistoryTopList = dltFrontendHistoryTopMapper.selectList(
            new QueryWrapper<DltFrontendHistoryTop>()
                .orderByDesc("activeCoefficient"));
        
        if (CollectionUtils.isEmpty(allHistoryTopList)) {
            return new ArrayList<>();
        }
        
        // 计算平均系数（保留两位小数，截断方式）
        final double avgCoefficient = Math.floor(allHistoryTopList.stream()
                .mapToDouble(DltFrontendHistoryTop::getActiveCoefficient)
                .average()
                .orElse(0.0) * 100) / 100;
        
        // 筛选出大于或等于平均值的球，并按差值排序
        List<DltFrontendHistoryTop> aboveAvgBalls = allHistoryTopList.stream()
                .filter(ball -> ball.getActiveCoefficient() >= avgCoefficient)
                .sorted(Comparator.comparingDouble(ball -> ball.getActiveCoefficient() - avgCoefficient))
                .collect(Collectors.toList());
        
        // 如果没有大于或等于平均值的球号，返回空列表
        if (aboveAvgBalls.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 逐层添加球号，直到达到3个或更多（相同差值的要一起加入）
        List<Integer> result = new ArrayList<>();
        double currentDiff = -1;
        
        for (DltFrontendHistoryTop ball : aboveAvgBalls) {
            double diff = ball.getActiveCoefficient() - avgCoefficient;
            
            // 如果已经有3个球了，且当前差值与之前不同，则停止
            if (result.size() >= 3 && diff != currentDiff) {
                break;
            }
            
            result.add(ball.getBallNumber());
            currentDiff = diff;
        }
        
        return result;
    }
    
    /**
     * 从dlt_frontend_history_top_100取平均值向上连续3个球号（按系数排行，处理边界相同系数）
     */
    private List<Integer> getTop3FromDltFrontendHistoryTop100ByAvg() {
        List<DltFrontendHistoryTop100> allHistoryTop100List = dltFrontendHistoryTop100Mapper.selectList(
            new QueryWrapper<DltFrontendHistoryTop100>()
                .orderByDesc("activeCoefficient"));
        
        if (CollectionUtils.isEmpty(allHistoryTop100List)) {
            return new ArrayList<>();
        }
        
        // 计算平均系数（保留两位小数，截断方式）
        final double avgCoefficient = Math.floor(allHistoryTop100List.stream()
                .mapToDouble(DltFrontendHistoryTop100::getActiveCoefficient)
                .average()
                .orElse(0.0) * 100) / 100;
        
        // 筛选出大于或等于平均值的球，并按差值排序
        List<DltFrontendHistoryTop100> aboveAvgBalls = allHistoryTop100List.stream()
                .filter(ball -> ball.getActiveCoefficient() >= avgCoefficient)
                .sorted(Comparator.comparingDouble(ball -> ball.getActiveCoefficient() - avgCoefficient))
                .collect(Collectors.toList());
        
        // 如果没有大于或等于平均值的球号，返回空列表
        if (aboveAvgBalls.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 逐层添加球号，直到达到3个或更多（相同差值的要一起加入）
        List<Integer> result = new ArrayList<>();
        double currentDiff = -1;
        
        for (DltFrontendHistoryTop100 ball : aboveAvgBalls) {
            double diff = ball.getActiveCoefficient() - avgCoefficient;
            
            // 如果已经有3个球了，且当前差值与之前不同，则停止
            if (result.size() >= 3 && diff != currentDiff) {
                break;
            }
            
            result.add(ball.getBallNumber());
            currentDiff = diff;
        }
        
        // 如果结果球号数量 > 3，通过dlt_frontend_history_top表筛选
        if (result.size() > 3) {
            return selectTop3FromDltFrontendHistoryTop(result);
        }
        
        return result;
    }
    
    /**
     * 从dlt_frontend_history_top表中选择前3个球号
     */
    private List<Integer> selectTop3FromDltFrontendHistoryTop(List<Integer> candidateBalls) {
        // 获取候选球号在dlt_frontend_history_top表中的活跃系数
        Map<Integer, Double> ballCoefficientMap = new HashMap<>();
        for (Integer ballNumber : candidateBalls) {
            DltFrontendHistoryTop record = dltFrontendHistoryTopMapper.selectOne(
                new QueryWrapper<DltFrontendHistoryTop>()
                    .eq("ballNumber", ballNumber));
            double coefficient = (record != null) ? record.getActiveCoefficient() : 0.0;
            ballCoefficientMap.put(ballNumber, coefficient);
        }
        
        // 按活跃系数降序排序，选择前3个
        List<Map.Entry<Integer, Double>> sortedEntries = ballCoefficientMap.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(3, sortedEntries.size()); i++) {
            result.add(sortedEntries.get(i).getKey());
        }
        
        return result;
    }
    
    /**
     * 统计分析并生成结果
     */
    private List<DLTSecondStepResultVO.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<DLTSecondStepResultVO.BallAnalysisResult> results = new ArrayList<>();
        for (Integer ballNumber : allBallsWithRanking) {
            DLTSecondStepResultVO.BallAnalysisResult result = DLTSecondStepResultVO.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<>();
        
        // 从DLT前区百期排行表获取所有球号
        List<DltFrontendHistoryTop100> top100List = dltFrontendHistoryTop100Mapper.selectList(
            new QueryWrapper<DltFrontendHistoryTop100>());
        for (DltFrontendHistoryTop100 item : top100List) {
            allBalls.add(item.getBallNumber());
        }
        
        // 从DLT前区历史排行表获取所有球号
        List<DltFrontendHistoryTop> historyTopList = dltFrontendHistoryTopMapper.selectList(
            new QueryWrapper<DltFrontendHistoryTop>());
        for (DltFrontendHistoryTop item : historyTopList) {
            allBalls.add(item.getBallNumber());
        }
        
        return allBalls;
    }
    
    /**
     * 获取球号在百期排行表中的排位
     */
    private Map<Integer, Integer> getTop100Rankings(Set<Integer> ballNumbers) {
        Map<Integer, Integer> result = new HashMap<>();
        
        // 直接查询指定球号的排行数据，使用表中的ranking字段作为排名
        List<DltFrontendHistoryTop100> top100List = dltFrontendHistoryTop100Mapper.selectList(
            new QueryWrapper<DltFrontendHistoryTop100>()
                .in("ballNumber", ballNumbers));
        
        // 使用表中的ranking字段作为排名
        for (DltFrontendHistoryTop100 item : top100List) {
            result.put(item.getBallNumber(), item.getRanking());
        }
        
        // 对于没有在百期排行表中的球号，设置为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<>();
        
        // 直接查询指定球号的排行数据，使用表中的ranking字段作为排名
        List<DltFrontendHistoryTop> historyTopList = dltFrontendHistoryTopMapper.selectList(
            new QueryWrapper<DltFrontendHistoryTop>()
                .in("ballNumber", ballNumbers));
        
        // 使用表中的ranking字段作为排名
        for (DltFrontendHistoryTop item : historyTopList) {
            result.put(item.getBallNumber(), item.getRanking());
        }
        
        // 对于没有在历史排行表中的球号，设置为null
        for (Integer ballNumber : ballNumbers) {
            if (!result.containsKey(ballNumber)) {
                result.put(ballNumber, null);
            }
        }
        
        return result;
    }
    
    /**
     * 参数验证
     */
    private void validateInputParams(String level, List<Integer> previousFrontBalls, 
                                    List<Integer> previousBackBalls, Integer currentFirstBall) {
        if (!"H".equalsIgnoreCase(level) && !"M".equalsIgnoreCase(level) && !"L".equalsIgnoreCase(level)) {
            throw new IllegalArgumentException("位置级别必须是H/M/L之一");
        }
        
        if (CollectionUtils.isEmpty(previousFrontBalls) || previousFrontBalls.size() != 5) {
            throw new IllegalArgumentException("上期前区球号必须为5个");
        }
        
        if (CollectionUtils.isEmpty(previousBackBalls) || previousBackBalls.size() != 2) {
            throw new IllegalArgumentException("上期后区球号必须为2个");
        }
        
        if (currentFirstBall == null || currentFirstBall < 1 || currentFirstBall > 35) {
            throw new IllegalArgumentException("本期首球号码范围应为1-35");
        }
        
        for (Integer frontBall : previousFrontBalls) {
            if (frontBall < 1 || frontBall > 35) {
                throw new IllegalArgumentException("上期前区球号范围应为1-35");
            }
        }
        
        for (Integer backBall : previousBackBalls) {
            if (backBall < 1 || backBall > 12) {
                throw new IllegalArgumentException("上期后区球号范围应为1-12");
            }
        }
    }
}
