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.DLTFirstStepResultVO;
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 FirstFrontBallAnalysis {
    
    @Autowired
    private D9Mapper d9Mapper;
    
    @Autowired
    private D12Mapper d12Mapper;
    
    @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 frontBalls 前区5个球号
     * @param backBalls 后区2个球号
     * @return 分析结果
     */
    public DLTFirstStepResultVO analyze(String level, List<Integer> frontBalls, List<Integer> backBalls) {
        // 参数验证
        validateInputParams(level, frontBalls, backBalls);
        
        log.info("开始精推大乐透第一步分析，策略：{}，前区：{}，后区：{}", level, frontBalls, backBalls);
        
        // 用于存储所有候选球号和对应的系数
        Map<Integer, List<BallWithCoefficient>> ballCoefficientMap = new HashMap<>();
        List<Integer> allCandidateBalls = new ArrayList<>();
        
        // Step 1: 根据5个前区球号从D9表获取候选球
        for (Integer frontBall : frontBalls) {
            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 = getTop3FromDltFrontendHistoryTop();
        allCandidateBalls.addAll(top3HistoryTop);
        
        // Step 3: 从dlt_frontend_history_top_100获取前3个球号
        List<Integer> top3HistoryTop100 = getTop3FromDltFrontendHistoryTop100();
        allCandidateBalls.addAll(top3HistoryTop100);
        
        // Step 4: 根据2个后区球号从D12表获取候选球
        for (Integer backBall : backBalls) {
            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: 统计分析并生成结果
        List<DLTFirstStepResultVO.BallAnalysisResult> results = analyzeResults(allCandidateBalls, ballCoefficientMap);
        
        return DLTFirstStepResultVO.builder()
                .results(results)
                .strategy(level)
                .frontBalls(frontBalls)
                .backBalls(backBalls)
                .build();
    }
    
    /**
     * 根据级别从D9表获取候选球号和系数
     */
    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<>();
        }
        
        if ("H".equalsIgnoreCase(level)) {
            return getHighLevelBallsFromD9(d9List, masterBallNumber);
        } else if ("M".equalsIgnoreCase(level)) {
            return getMiddleLevelBallsFromD9(d9List, masterBallNumber);
        } else { // L
            return getLowLevelBallsFromD9(d9List, masterBallNumber);
        }
    }
    
    /**
     * 根据级别从D12表获取候选球号和系数
     */
    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<>();
        }
        
        if ("H".equalsIgnoreCase(level)) {
            return getHighLevelBallsFromD12(d12List, masterBallNumber);
        } else if ("M".equalsIgnoreCase(level)) {
            return getMiddleLevelBallsFromD12(d12List, masterBallNumber);
        } else { // L
            return getLowLevelBallsFromD12(d12List, masterBallNumber);
        }
    }
    
    /**
     * 高位策略：从D9表获取系数最大的前17个球号（如果第17个系数相同则一并加入）
     */
    private List<BallWithCoefficient> getHighLevelBallsFromD9(List<D9> d9List, Integer masterBallNumber) {
        List<BallWithCoefficient> result = new ArrayList<>();
        
        if (d9List.size() <= 17) {
            // 如果总数不超过17个，全部加入
            for (D9 d9 : d9List) {
                result.add(new BallWithCoefficient(d9.getSlaveBallNumber(), d9.getCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 先加入前17个
        for (int i = 0; i < 17; i++) {
            D9 d9 = d9List.get(i);
            result.add(new BallWithCoefficient(d9.getSlaveBallNumber(), d9.getCoefficient(), masterBallNumber));
        }
        
        // 获取第17个球号的系数
        Double boundaryCoefficient = d9List.get(16).getCoefficient();
        
        // 继续查找后面系数相同的球号
        for (int i = 17; 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表获取系数最大的前17个球号（如果第17个系数相同则一并加入）
     */
    private List<BallWithCoefficient> getHighLevelBallsFromD12(List<D12> d12List, Integer masterBallNumber) {
        List<BallWithCoefficient> result = new ArrayList<>();
        
        if (d12List.size() <= 17) {
            // 如果总数不超过17个，全部加入
            for (D12 d12 : d12List) {
                result.add(new BallWithCoefficient(d12.getSlaveBallNumber(), d12.getCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 先加入前17个
        for (int i = 0; i < 17; i++) {
            D12 d12 = d12List.get(i);
            result.add(new BallWithCoefficient(d12.getSlaveBallNumber(), d12.getCoefficient(), masterBallNumber));
        }
        
        // 获取第17个球号的系数
        Double boundaryCoefficient = d12List.get(16).getCoefficient();
        
        // 继续查找后面系数相同的球号
        for (int i = 17; 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;
    }
    
    /**
     * 中位策略：从D9表获取平均值附近的17个球号（向上8个，向下8个，边界系数相同则一并加入）
     */
    private List<BallWithCoefficient> getMiddleLevelBallsFromD9(List<D9> d9List, Integer masterBallNumber) {
        if (d9List.size() < 17) {
            log.warn("D9表数据不足17条，实际{}条", d9List.size());
            List<BallWithCoefficient> result = new ArrayList<>();
            for (D9 d9 : d9List) {
                result.add(new BallWithCoefficient(d9.getSlaveBallNumber(), d9.getCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 计算平均系数（保留两位小数，截断方式）
        double avgCoefficient = d9List.stream()
                .mapToDouble(D9::getCoefficient)
                .average()
                .orElse(0.0);
        // 截断到两位小数
        avgCoefficient = Math.floor(avgCoefficient * 100) / 100;
        
        // 找到第一个比平均值大的位置（从下到上遍历）
        int avgPosition = -1;
        for (int i = d9List.size() - 1; i >= 0; i--) {
            if (d9List.get(i).getCoefficient() >= avgCoefficient) {
                avgPosition = i;
                break;
            }
        }
        
        if (avgPosition == -1) {
            avgPosition = 0; // 如果没找到，取第一个
        }
        
        List<BallWithCoefficient> result = new ArrayList<>();
        
        // 先加入平均值位置的球号
        result.add(new BallWithCoefficient(d9List.get(avgPosition).getSlaveBallNumber(), 
                d9List.get(avgPosition).getCoefficient(), masterBallNumber));
        
        // 向上取8个球号，处理边界系数相同情况
        int upCount = 0;
        Double upBoundaryCoeff = null;
        for (int i = avgPosition - 1; i >= 0 && upCount < 8; i--) {
            result.add(new BallWithCoefficient(d9List.get(i).getSlaveBallNumber(), 
                    d9List.get(i).getCoefficient(), masterBallNumber));
            upCount++;
            if (upCount == 8) {
                upBoundaryCoeff = d9List.get(i).getCoefficient();
            }
        }
        
        // 向上边界处理：继续添加与第8个球号系数相同的球号
        if (upBoundaryCoeff != null) {
            for (int i = avgPosition - 9; i >= 0; i--) {
                if (d9List.get(i).getCoefficient().equals(upBoundaryCoeff)) {
                    result.add(new BallWithCoefficient(d9List.get(i).getSlaveBallNumber(), 
                            d9List.get(i).getCoefficient(), masterBallNumber));
                } else {
                    break;
                }
            }
        }
        
        // 向下取8个球号，处理边界系数相同情况
        int downCount = 0;
        Double downBoundaryCoeff = null;
        for (int i = avgPosition + 1; i < d9List.size() && downCount < 8; i++) {
            result.add(new BallWithCoefficient(d9List.get(i).getSlaveBallNumber(), 
                    d9List.get(i).getCoefficient(), masterBallNumber));
            downCount++;
            if (downCount == 8) {
                downBoundaryCoeff = d9List.get(i).getCoefficient();
            }
        }
        
        // 向下边界处理：继续添加与第8个球号系数相同的球号
        if (downBoundaryCoeff != null) {
            for (int i = avgPosition + 9; i < d9List.size(); i++) {
                if (d9List.get(i).getCoefficient().equals(downBoundaryCoeff)) {
                    result.add(new BallWithCoefficient(d9List.get(i).getSlaveBallNumber(), 
                            d9List.get(i).getCoefficient(), masterBallNumber));
                } else {
                    break;
                }
            }
        }
        
        return result;
    }
    
    /**
     * 中位策略：从D12表获取平均值附近的17个球号（向上8个，向下8个，边界系数相同则一并加入）
     */
    private List<BallWithCoefficient> getMiddleLevelBallsFromD12(List<D12> d12List, Integer masterBallNumber) {
        if (d12List.size() < 17) {
            log.warn("D12表数据不足17条，实际{}条", d12List.size());
            List<BallWithCoefficient> result = new ArrayList<>();
            for (D12 d12 : d12List) {
                result.add(new BallWithCoefficient(d12.getSlaveBallNumber(), d12.getCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 计算平均系数（保留两位小数，截断方式）
        double avgCoefficient = d12List.stream()
                .mapToDouble(D12::getCoefficient)
                .average()
                .orElse(0.0);
        // 截断到两位小数
        avgCoefficient = Math.floor(avgCoefficient * 100) / 100;
        
        // 找到第一个比平均值大的位置（从下到上遍历）
        int avgPosition = -1;
        for (int i = d12List.size() - 1; i >= 0; i--) {
            if (d12List.get(i).getCoefficient() >= avgCoefficient) {
                avgPosition = i;
                break;
            }
        }
        
        if (avgPosition == -1) {
            avgPosition = 0; // 如果没找到，取第一个
        }
        
        List<BallWithCoefficient> result = new ArrayList<>();
        
        // 先加入平均值位置的球号
        result.add(new BallWithCoefficient(d12List.get(avgPosition).getSlaveBallNumber(), 
                d12List.get(avgPosition).getCoefficient(), masterBallNumber));
        
        // 向上取8个球号，处理边界系数相同情况
        int upCount = 0;
        Double upBoundaryCoeff = null;
        for (int i = avgPosition - 1; i >= 0 && upCount < 8; i--) {
            result.add(new BallWithCoefficient(d12List.get(i).getSlaveBallNumber(), 
                    d12List.get(i).getCoefficient(), masterBallNumber));
            upCount++;
            if (upCount == 8) {
                upBoundaryCoeff = d12List.get(i).getCoefficient();
            }
        }
        
        // 向上边界处理：继续添加与第8个球号系数相同的球号
        if (upBoundaryCoeff != null) {
            for (int i = avgPosition - 9; i >= 0; i--) {
                if (d12List.get(i).getCoefficient().equals(upBoundaryCoeff)) {
                    result.add(new BallWithCoefficient(d12List.get(i).getSlaveBallNumber(), 
                            d12List.get(i).getCoefficient(), masterBallNumber));
                } else {
                    break;
                }
            }
        }
        
        // 向下取8个球号，处理边界系数相同情况
        int downCount = 0;
        Double downBoundaryCoeff = null;
        for (int i = avgPosition + 1; i < d12List.size() && downCount < 8; i++) {
            result.add(new BallWithCoefficient(d12List.get(i).getSlaveBallNumber(), 
                    d12List.get(i).getCoefficient(), masterBallNumber));
            downCount++;
            if (downCount == 8) {
                downBoundaryCoeff = d12List.get(i).getCoefficient();
            }
        }
        
        // 向下边界处理：继续添加与第8个球号系数相同的球号
        if (downBoundaryCoeff != null) {
            for (int i = avgPosition + 9; i < d12List.size(); i++) {
                if (d12List.get(i).getCoefficient().equals(downBoundaryCoeff)) {
                    result.add(new BallWithCoefficient(d12List.get(i).getSlaveBallNumber(), 
                            d12List.get(i).getCoefficient(), masterBallNumber));
                } else {
                    break;
                }
            }
        }
        
        return result;
    }
    
    /**
     * 低位策略：从D9表获取最小值向上17个球号（含最小值，第1个系数相同则一并加入）
     */
    private List<BallWithCoefficient> getLowLevelBallsFromD9(List<D9> d9List, Integer masterBallNumber) {
        if (d9List.size() < 17) {
            log.warn("D9表数据不足17条，实际{}条", d9List.size());
            List<BallWithCoefficient> result = new ArrayList<>();
            for (D9 d9 : d9List) {
                result.add(new BallWithCoefficient(d9.getSlaveBallNumber(), d9.getCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 从最小值开始向上取17个（d9List已按系数降序排列，最后17个就是最小的）
        List<BallWithCoefficient> result = new ArrayList<>();
        int startIndex = Math.max(0, d9List.size() - 17);
        
        // 先加入基本的17个球号
        for (int i = startIndex; i < d9List.size(); i++) {
            D9 d9 = d9List.get(i);
            result.add(new BallWithCoefficient(d9.getSlaveBallNumber(), d9.getCoefficient(), masterBallNumber));
        }
        
        // 处理第1个球号（系数最大的）边界相同情况
        if (startIndex > 0) {
            Double firstBallCoeff = d9List.get(startIndex).getCoefficient();
            
            // 继续向前查找系数相同的球号
            for (int i = startIndex - 1; i >= 0; i--) {
                if (d9List.get(i).getCoefficient().equals(firstBallCoeff)) {
                    result.add(new BallWithCoefficient(d9List.get(i).getSlaveBallNumber(), 
                            d9List.get(i).getCoefficient(), masterBallNumber));
                } else {
                    break; // 系数不同，停止查找
                }
            }
        }
        
        return result;
    }
    
    /**
     * 低位策略：从D12表获取最小值向上17个球号（含最小值，第1个系数相同则一并加入）
     */
    private List<BallWithCoefficient> getLowLevelBallsFromD12(List<D12> d12List, Integer masterBallNumber) {
        if (d12List.size() < 17) {
            log.warn("D12表数据不足17条，实际{}条", d12List.size());
            List<BallWithCoefficient> result = new ArrayList<>();
            for (D12 d12 : d12List) {
                result.add(new BallWithCoefficient(d12.getSlaveBallNumber(), d12.getCoefficient(), masterBallNumber));
            }
            return result;
        }
        
        // 从最小值开始向上取17个（d12List已按系数降序排列，最后17个就是最小的）
        List<BallWithCoefficient> result = new ArrayList<>();
        int startIndex = Math.max(0, d12List.size() - 17);
        
        // 先加入基本的17个球号
        for (int i = startIndex; i < d12List.size(); i++) {
            D12 d12 = d12List.get(i);
            result.add(new BallWithCoefficient(d12.getSlaveBallNumber(), d12.getCoefficient(), masterBallNumber));
        }
        
        // 处理第1个球号（系数最大的）边界相同情况
        if (startIndex > 0) {
            Double firstBallCoeff = d12List.get(startIndex).getCoefficient();
            
            // 继续向前查找系数相同的球号
            for (int i = startIndex - 1; i >= 0; i--) {
                if (d12List.get(i).getCoefficient().equals(firstBallCoeff)) {
                    result.add(new BallWithCoefficient(d12List.get(i).getSlaveBallNumber(), 
                            d12List.get(i).getCoefficient(), masterBallNumber));
                } else {
                    break; // 系数不同，停止查找
                }
            }
        }
        
        return result;
    }
    
    /**
     * 从dlt_frontend_history_top获取前3个球号（按点系数排行，处理边界相同系数）
     */
    private List<Integer> getTop3FromDltFrontendHistoryTop() {
        List<DltFrontendHistoryTop> historyTopList = dltFrontendHistoryTopMapper.selectList(
            new QueryWrapper<DltFrontendHistoryTop>()
                .orderByDesc("activeCoefficient"));
        
        if (CollectionUtils.isEmpty(historyTopList)) {
            log.warn("dlt_frontend_history_top数据为空");
            return new ArrayList<>();
        }
        
        List<Integer> result = new ArrayList<>();
        int index = 0;
        int addedCount = 0;
        
        while (addedCount < 3 && index < historyTopList.size()) {
            double currentCoefficient = historyTopList.get(index).getActiveCoefficient();
            List<Integer> sameCoefficientBalls = new ArrayList<>();
            
            // 收集所有相同系数的球号
            while (index < historyTopList.size() && 
                   historyTopList.get(index).getActiveCoefficient().equals(currentCoefficient)) {
                sameCoefficientBalls.add(historyTopList.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 = handleFrontendHistoryBoundaryConflicts(sameCoefficientBalls, needCount);
                result.addAll(selectedBalls);
                addedCount += selectedBalls.size();
            }
        }
        
        return result;
    }
    
    /**
     * 从dlt_frontend_history_top_100获取前3个球号（按点系数排行，处理边界相同系数）
     */
    private List<Integer> getTop3FromDltFrontendHistoryTop100() {
        List<DltFrontendHistoryTop100> historyTop100List = dltFrontendHistoryTop100Mapper.selectList(
            new QueryWrapper<DltFrontendHistoryTop100>()
                .orderByDesc("activeCoefficient"));
        
        if (CollectionUtils.isEmpty(historyTop100List)) {
            log.warn("dlt_frontend_history_top_100数据为空");
            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).getActiveCoefficient();
            List<Integer> sameCoefficientBalls = new ArrayList<>();
            
            // 收集所有相同系数的球号
            while (index < historyTop100List.size() && 
                   historyTop100List.get(index).getActiveCoefficient().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 = handleFrontendHistoryBoundaryConflicts(sameCoefficientBalls, needCount);
                result.addAll(selectedBalls);
                addedCount += selectedBalls.size();
            }
        }
        
        return result;
    }
    
    /**
     * 处理前区历史排行边界冲突，选择指定数量的球号
     * @param candidateBalls 候选球号列表
     * @param selectCount 需要选择的数量
     * @return 选中的球号列表
     */
    private List<Integer> handleFrontendHistoryBoundaryConflicts(List<Integer> candidateBalls, int selectCount) {
        if (CollectionUtils.isEmpty(candidateBalls) || selectCount <= 0) {
            return new ArrayList<>();
        }
        
        if (selectCount >= candidateBalls.size()) {
            return new ArrayList<>(candidateBalls);
        }
        
        // 1. 先从dlt_frontend_history_top_100比较
        Map<Integer, Double> top100Coefficients = new HashMap<>();
        for (Integer ball : candidateBalls) {
            DltFrontendHistoryTop100 record = dltFrontendHistoryTop100Mapper.selectOne(
                new QueryWrapper<DltFrontendHistoryTop100>()
                    .eq("ballNumber", ball));
            if (record != null) {
                top100Coefficients.put(ball, record.getActiveCoefficient());
            } else {
                top100Coefficients.put(ball, 0.0);
            }
        }
        
        // 按系数降序排序
        List<Map.Entry<Integer, Double>> sortedByTop100 = top100Coefficients.entrySet().stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .collect(Collectors.toList());
        
        List<Integer> result = new ArrayList<>();
        
        // 按系数分组处理
        int currentIndex = 0;
        while (result.size() < selectCount && currentIndex < sortedByTop100.size()) {
            Double currentCoefficient = sortedByTop100.get(currentIndex).getValue();
            List<Integer> sameTop100CoefficientBalls = new ArrayList<>();
            
            // 收集相同系数的球号
            while (currentIndex < sortedByTop100.size() && 
                   sortedByTop100.get(currentIndex).getValue().equals(currentCoefficient)) {
                sameTop100CoefficientBalls.add(sortedByTop100.get(currentIndex).getKey());
                currentIndex++;
            }
            
            int needFromThisGroup = Math.min(selectCount - result.size(), sameTop100CoefficientBalls.size());
            
            if (sameTop100CoefficientBalls.size() == 1 || needFromThisGroup == sameTop100CoefficientBalls.size()) {
                // 只有一个球或者需要全部选择
                for (int i = 0; i < needFromThisGroup; i++) {
                    result.add(sameTop100CoefficientBalls.get(i));
                }
            } else {
                // 需要进一步筛选，使用dlt_frontend_history_top表
                List<Integer> selectedFromTop = selectFromFrontendHistoryTop(sameTop100CoefficientBalls, needFromThisGroup);
                result.addAll(selectedFromTop);
            }
        }
        
        return result;
    }
    
    /**
     * 从dlt_frontend_history_top表中选择指定数量的球号
     */
    private List<Integer> selectFromFrontendHistoryTop(List<Integer> candidateBalls, int selectCount) {
        if (CollectionUtils.isEmpty(candidateBalls) || selectCount <= 0) {
            return new ArrayList<>();
        }
        
        if (selectCount >= candidateBalls.size()) {
            return new ArrayList<>(candidateBalls);
        }
        
        // 获取在dlt_frontend_history_top表中的系数
        Map<Integer, Double> topCoefficients = new HashMap<>();
        for (Integer ball : candidateBalls) {
            DltFrontendHistoryTop record = dltFrontendHistoryTopMapper.selectOne(
                new QueryWrapper<DltFrontendHistoryTop>()
                    .eq("ballNumber", ball));
            if (record != null) {
                topCoefficients.put(ball, record.getActiveCoefficient());
            } 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<DLTFirstStepResultVO.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<DLTFirstStepResultVO.BallAnalysisResult> results = new ArrayList<>();
        for (Integer ballNumber : allBallsWithRanking) {
            DLTFirstStepResultVO.BallAnalysisResult result = DLTFirstStepResultVO.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> frontBalls, List<Integer> backBalls) {
        if (!"H".equalsIgnoreCase(level) && !"M".equalsIgnoreCase(level) && !"L".equalsIgnoreCase(level)) {
            throw new IllegalArgumentException("位置级别必须是H/M/L之一");
        }
        
        if (CollectionUtils.isEmpty(frontBalls) || frontBalls.size() != 5) {
            throw new IllegalArgumentException("前区球号必须为5个");
        }
        
        if (CollectionUtils.isEmpty(backBalls) || backBalls.size() != 2) {
            throw new IllegalArgumentException("后区球号必须为2个");
        }
        
        for (Integer frontBall : frontBalls) {
            if (frontBall < 1 || frontBall > 35) {
                throw new IllegalArgumentException("前区球号范围应为1-35");
            }
        }
        
        for (Integer backBall : backBalls) {
            if (backBall < 1 || backBall > 12) {
                throw new IllegalArgumentException("后区球号范围应为1-12");
            }
        }
    }
}
