<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;
use App\Models\StudentKnowledgeMastery;
use App\Models\MistakeRecord;
use App\Models\KnowledgePoint;
use App\Models\Paper;
use App\Models\PaperQuestion;
use App\Models\Question;
use Illuminate\Support\Facades\DB;

class ExamTypeStrategy
{
    protected QuestionExpansionService $questionExpansionService;
    protected QuestionLocalService $questionLocalService;

    public function __construct(QuestionExpansionService $questionExpansionService, QuestionLocalService $questionLocalService = null)
    {
        $this->questionExpansionService = $questionExpansionService;
        $this->questionLocalService = $questionLocalService ?? app(QuestionLocalService::class);
    }

    /**
     * 根据组卷类型构建参数
     * assembleType: 0-摸底, 1-智能组卷, 2-知识点组卷, 3-教材组卷, 4-通用, 5-错题本, 6-按知识点组卷
     */
    public function buildParams(array $baseParams, int $assembleType): array
    {
        Log::info('ExamTypeStrategy: 构建组卷参数', [
            'assemble_type' => $assembleType,
            'base_params_keys' => array_keys($baseParams)
        ]);

        return match($assembleType) {
            0 => $this->applyDifficultyDistribution($this->buildDiagnosticParams($baseParams)), // 摸底
            1 => $this->applyDifficultyDistribution($this->buildIntelligentAssembleParams($baseParams)), // 智能组卷
            2 => $this->applyDifficultyDistribution($this->buildKnowledgePointAssembleParams($baseParams)), // 知识点组卷
            3 => $this->applyDifficultyDistribution($this->buildTextbookAssembleParams($baseParams)), // 教材组卷
            4 => $this->applyDifficultyDistribution($this->buildGeneralParams($baseParams)), // 通用
            5 => $this->buildMistakeParams($baseParams), // 错题本不应用难度分布
            6 => $this->applyDifficultyDistribution($this->buildKnowledgePointsParams($baseParams)), // 按知识点组卷
            default => $this->applyDifficultyDistribution($this->buildGeneralParams($baseParams))
        };
    }

    /**
     * 根据组卷类型构建参数（兼容旧版 exam_type 参数）
     * @deprecated 使用 buildParams(array, int) 替代
     */
    public function buildParamsLegacy(array $baseParams, string $examType): array
    {
        // 兼容旧版 exam_type 参数
        $assembleType = match($examType) {
            'diagnostic' => 0,
            'general' => 4,
            'practice' => 5,
            'mistake' => 5,
            'textbook' => 3,
            'knowledge' => 2,
            'knowledge_points' => 6,
            default => 4
        };

        return $this->buildParams($baseParams, $assembleType);
    }

    /**
     * 通用智能出卷（原有行为）
     */
    private function buildGeneralParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 通用智能出卷参数', $params);

        // 返回原始参数，难度分布逻辑在 buildParams 中统一处理
        return $params;
    }

    /**
     * 应用难度系数分布逻辑
     * 根据 difficulty_category 参数实现分层选题策略
     *
     * @param array $params 基础参数
     * @param bool $forceApply 是否强制应用（默认false，不对错题本类型应用）
     * @return array 增强后的参数
     */
    private function applyDifficultyDistribution(array $params, bool $forceApply = false): array
    {
        // 检查是否为排除类型（错题本 assembleType=5）
        $assembleType = (int) ($params['assemble_type'] ?? 4);
        $isExcludedType = ($assembleType === 5); // 只有错题本类型不应用难度分布

        // 如果不是强制应用且为排除类型，则不应用难度分布
        if (!$forceApply && $isExcludedType) {
            Log::info('ExamTypeStrategy: 跳过难度分布（错题本类型）', [
                'assemble_type' => $assembleType
            ]);
            return $params;
        }

        $difficultyCategory = (int) ($params['difficulty_category'] ?? 1);
        $totalQuestions = (int) ($params['total_questions'] ?? 20);

        Log::info('ExamTypeStrategy: 应用难度系数分布', [
            'difficulty_category' => $difficultyCategory,
            'total_questions' => $totalQuestions,
            'assemble_type' => $assembleType
        ]);

        // 根据难度类别计算题目分布
        $distribution = $this->calculateDifficultyDistribution($difficultyCategory, $totalQuestions);

        // 构建难度分布配置
        $difficultyDistributionConfig = [
            'strategy' => 'difficulty分层选题',
            'category' => $difficultyCategory,
            'total_questions' => $totalQuestions,
            'distribution' => $distribution,
            'ranges' => $this->getDifficultyRanges($difficultyCategory),
            'use_question_local_service' => true, // 标记使用新的独立方法
        ];

        $enhanced = array_merge($params, [
            'difficulty_distribution_config' => $difficultyDistributionConfig,
            // 保留原有的 difficulty_ratio 以兼容性
            'difficulty_ratio' => [
                '基础' => $distribution['low']['percentage'],
                '中等' => $distribution['medium']['percentage'],
                '拔高' => $distribution['high']['percentage'],
            ],
            // 启用难度分布选题标志
            'enable_difficulty_distribution' => true,
            // 【重要】保持原始的 difficulty_category，不修改
            'difficulty_category' => $difficultyCategory,
        ]);

        Log::info('ExamTypeStrategy: 难度分布应用完成', [
            'category' => $difficultyCategory,
            'distribution' => $distribution
        ]);

        return $enhanced;
    }

    /**
     * 应用难度分布到题目集合
     * 这是一个独立的公共方法，供外部调用
     *
     * @param array $questions 候选题目数组
     * @param int $totalQuestions 总题目数
     * @param int $difficultyCategory 难度类别 (1-4)
     * @param array $filters 其他筛选条件
     * @return array 分布后的题目
     */
    public function applyDifficultyDistributionToQuestions(array $questions, int $totalQuestions, int $difficultyCategory = 1, array $filters = []): array
    {
        Log::info('ExamTypeStrategy: 应用难度分布到题目集合', [
            'total_questions' => $totalQuestions,
            'difficulty_category' => $difficultyCategory,
            'input_questions' => count($questions)
        ]);

        // 使用 QuestionLocalService 的独立方法
        return $this->questionLocalService->selectQuestionsByDifficultyDistribution(
            $questions,
            $totalQuestions,
            $difficultyCategory,
            $filters
        );
    }

    /**
     * 根据难度类别计算题目分布
     *
     * @param int $category 难度类别 (1-4)
     * @param int $totalQuestions 总题目数
     * @return array 分布配置
     */
    private function calculateDifficultyDistribution(int $category, int $totalQuestions): array
    {
        // 标准化：25% 低级，50% 基准，25% 拔高
        $lowPercentage = 25;
        $mediumPercentage = 50;
        $highPercentage = 25;

        // 根据难度类别调整分布
        switch ($category) {
            case 1:
                // 基础型：0-0.25占50%，其他占50%
                $mediumPercentage = 50; // 0-0.25作为基准
                $lowPercentage = 25;    // 其他低难度
                $highPercentage = 25;   // 其他高难度
                break;

            case 2:
                // 进阶型：0.25-0.5占50%，<0.25占25%，>0.5占25%
                $mediumPercentage = 50; // 0.25-0.5作为基准
                $lowPercentage = 25;    // <0.25
                $highPercentage = 25;   // >0.5
                break;

            case 3:
                // 中等型：0.5-0.75占50%，<0.5占25%，>0.75占25%
                $mediumPercentage = 50; // 0.5-0.75作为基准
                $lowPercentage = 25;    // <0.5
                $highPercentage = 25;   // >0.75
                break;

            case 4:
                // 拔高型：0.75-1占50%，其他占50%
                $mediumPercentage = 50; // 0.75-1作为基准
                $lowPercentage = 25;    // 其他低难度
                $highPercentage = 25;   // 其他高难度
                break;
        }

        // 计算题目数量
        $lowCount = (int) round($totalQuestions * $lowPercentage / 100);
        $mediumCount = (int) round($totalQuestions * $mediumPercentage / 100);
        $highCount = $totalQuestions - $lowCount - $mediumCount;

        return [
            'low' => [
                'percentage' => $lowPercentage,
                'count' => $lowCount,
                'label' => '低级难度'
            ],
            'medium' => [
                'percentage' => $mediumPercentage,
                'count' => $mediumCount,
                'label' => '基准难度'
            ],
            'high' => [
                'percentage' => $highPercentage,
                'count' => $highCount,
                'label' => '拔高难度'
            ]
        ];
    }

    /**
     * 获取难度范围配置
     *
     * @param int $category 难度类别
     * @return array 难度范围配置
     */
    private function getDifficultyRanges(int $category): array
    {
        switch ($category) {
            case 1:
                return [
                    'primary' => ['min' => 0.0, 'max' => 0.25, 'percentage' => 50],
                    'secondary' => ['min' => 0.25, 'max' => 1.0, 'percentage' => 50],
                    'description' => '基础型：0-0.25占比50%，其他占比50%'
                ];

            case 2:
                return [
                    'primary' => ['min' => 0.25, 'max' => 0.5, 'percentage' => 50],
                    'low' => ['min' => 0.0, 'max' => 0.25, 'percentage' => 25],
                    'high' => ['min' => 0.5, 'max' => 1.0, 'percentage' => 25],
                    'description' => '进阶型：0.25-0.5占比50%，<0.25占比25%，>0.5占比25%'
                ];

            case 3:
                return [
                    'primary' => ['min' => 0.5, 'max' => 0.75, 'percentage' => 50],
                    'low' => ['min' => 0.0, 'max' => 0.5, 'percentage' => 25],
                    'high' => ['min' => 0.75, 'max' => 1.0, 'percentage' => 25],
                    'description' => '中等型：0.5-0.75占比50%，<0.5占比25%，>0.75占比25%'
                ];

            case 4:
                return [
                    'primary' => ['min' => 0.75, 'max' => 1.0, 'percentage' => 50],
                    'secondary' => ['min' => 0.0, 'max' => 0.75, 'percentage' => 50],
                    'description' => '拔高型：0.75-1占比50%，其他占比50%'
                ];

            default:
                return [
                    'primary' => ['min' => 0.0, 'max' => 1.0, 'percentage' => 100],
                    'description' => '默认：全难度范围'
                ];
        }
    }

    /**
     * 摸底测试：评估当前水平
     */
    private function buildDiagnosticParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建摸底测试参数', $params);

        $textbookId = $params['textbook_id'] ?? null;
        $grade = $params['grade'] ?? null;
        $totalQuestions = $params['total_questions'] ?? 20;

        if (!$textbookId) {
            Log::warning('ExamTypeStrategy: 摸底测试需要 textbook_id 参数');
            return $this->buildGeneralParams($params);
        }

        // 第一步：根据 textbook_id 查询章节
        $catalogChapterIds = $this->getTextbookChapterIds($textbookId);

        if (empty($catalogChapterIds)) {
            Log::warning('ExamTypeStrategy: 未找到课本章节', ['textbook_id' => $textbookId]);
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 获取到课本章节（摸底测试）', [
            'textbook_id' => $textbookId,
            'chapter_count' => count($catalogChapterIds)
        ]);

        // 第二步：根据章节ID查询知识点关联
        $kpCodes = $this->getKnowledgePointsFromChapters($catalogChapterIds, 25);

        if (empty($kpCodes)) {
            Log::warning('ExamTypeStrategy: 未找到知识点关联', ['textbook_id' => $textbookId]);
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 获取到知识点（摸底测试）', [
            'kp_count' => count($kpCodes),
            'kp_codes' => $kpCodes,
            'textbook_id' => $textbookId,
            'grade' => $grade,
            'note' => '知识点数量将直接影响题目多样性'
        ]);

        // 摸底测试：平衡所有难度，覆盖多个知识点
        // 【修复】移除硬编码难度配比，使用difficulty_category参数动态计算
        $enhanced = array_merge($params, [
            'kp_codes' => $kpCodes,
            'textbook_id' => $textbookId,
            'grade' => $grade,
            'catalog_chapter_ids' => $catalogChapterIds,
            // 题型配比：选择题多一些，便于快速评估
            'question_type_ratio' => [
                '选择题' => 50,
                '填空题' => 25,
                '解答题' => 25,
            ],
            'question_category' => 1, // question_category=1 代表摸底题目
            'paper_name' => $params['paper_name'] ?? ('摸底测试_' . now()->format('Ymd_His')),
        ]);

        Log::info('ExamTypeStrategy: 摸底测试参数构建完成（未应用难度分布）', [
            'textbook_id' => $textbookId,
            'kp_count' => count($kpCodes),
            'total_questions' => $totalQuestions,
            'difficulty_category' => $params['difficulty_category'] ?? 1,
            'note' => '将在buildParams中应用difficulty_category难度分布'
        ]);

        return $enhanced;
    }

    /**
     * 错题本 (assembleType=5)
     * 根据 paper_ids 数组查询卷子中的错题，组合成新卷子
     * 不需要 total_questions 参数
     */
    private function buildMistakeParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建错题本参数', $params);

        $paperIds = $params['paper_ids'] ?? [];
        $studentId = $params['student_id'] ?? null;

        // 检查是否有 paper_ids 参数
        if (empty($paperIds)) {
            Log::warning('ExamTypeStrategy: 错题本需要 paper_ids 参数');
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 错题本组卷', [
            'paper_ids' => $paperIds,
            'student_id' => $studentId,
            'paper_count' => count($paperIds)
        ]);

        // 通过 paper_ids 查询卷子中的错题
        $mistakeQuestionIds = $this->getMistakeQuestionsFromPapers($paperIds, $studentId);

        if (empty($mistakeQuestionIds)) {
            Log::warning('ExamTypeStrategy: 未找到错题', [
                'paper_ids' => $paperIds
            ]);
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 获取到错题', [
            'paper_count' => count($paperIds),
            'mistake_count' => count($mistakeQuestionIds),
            'mistake_question_ids' => array_slice($mistakeQuestionIds, 0, 10) // 只记录前10个
        ]);

        // 获取错题知识点
        $mistakeKnowledgePoints = $this->getKnowledgePointsFromQuestions($mistakeQuestionIds);

        // 组装增强参数
        $mistakeCount = count($mistakeQuestionIds);
        $maxQuestions = 50; // 错题本最大题目数限制

        // 如果错题超过最大值，截取到最大值
        if ($mistakeCount > $maxQuestions) {
            Log::warning('ExamTypeStrategy: 错题数量超过最大值限制，已截取', [
                'mistake_count' => $mistakeCount,
                'max_limit' => $maxQuestions,
                'truncated_count' => $maxQuestions
            ]);
            $mistakeQuestionIds = array_slice($mistakeQuestionIds, 0, $maxQuestions);
            $mistakeCount = $maxQuestions;
        }

        $enhanced = array_merge($params, [
            'mistake_question_ids' => $mistakeQuestionIds,
            'paper_ids' => $paperIds,
            'priority_knowledge_points' => array_values($mistakeKnowledgePoints),
            'paper_name' => $params['paper_name'] ?? ('错题本_' . now()->format('Ymd_His')),
            'total_questions' => $mistakeCount, // 错题本题目数量由实际错题数量决定
            // 错题本：保持原有题型配比
            'question_type_ratio' => [
                '选择题' => 35,
                '填空题' => 30,
                '解答题' => 35,
            ],
            // 错题本不应用难度分布
            'is_mistake_exam' => true,
            'is_paper_based_mistake' => true, // 标记是基于卷子的错题本
            'mistake_count' => $mistakeCount,
            'knowledge_points_count' => count($mistakeKnowledgePoints),
            'max_questions_limit' => $maxQuestions,
        ]);

        Log::info('ExamTypeStrategy: 错题本参数构建完成', [
            'paper_count' => count($paperIds),
            'mistake_count' => count($mistakeQuestionIds),
            'knowledge_points_count' => count($mistakeKnowledgePoints)
        ]);

        return $enhanced;
    }

    /**
     * 专项练习：针对特定技能或知识点练习
     */
    private function buildPracticeParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建专项练习参数', $params);

        $studentId = $params['student_id'] ?? null;
        $practiceOptions = $params['practice_options'] ?? [];
        $weaknessThreshold = $practiceOptions['weakness_threshold'] ?? 0.7;
        $intensity = $practiceOptions['intensity'] ?? 'medium';
        $focusWeaknesses = $practiceOptions['focus_weaknesses'] ?? true;

        // 【修复】移除硬编码难度配比，专项练习使用difficulty_category参数
        // 注意：强度调节逻辑已移除，统一使用difficulty_category控制难度分布

        // 获取学生薄弱点
        $weaknessFilter = [];
        if ($studentId && $focusWeaknesses) {
            $weaknessFilter = $this->getStudentWeaknesses($studentId, $weaknessThreshold);
            Log::info('ExamTypeStrategy: 获取到学生薄弱点', [
                'student_id' => $studentId,
                'weakness_threshold' => $weaknessThreshold,
                'weakness_count' => count($weaknessFilter)
            ]);
        }

        // 优先使用薄弱点知识点，如果没有则使用用户选择的知识点
        $kpCodes = $params['kp_codes'] ?? [];
        if ($studentId && empty($kpCodes) && !empty($weaknessFilter)) {
            $kpCodes = array_column($weaknessFilter, 'kp_code');
            Log::info('ExamTypeStrategy: 使用薄弱点作为知识点', [
                'kp_codes' => $kpCodes
            ]);
        }

        $enhanced = array_merge($params, [
            'kp_codes' => $kpCodes,
            // 专项练习更注重题型覆盖
            'question_type_ratio' => [
                '选择题' => 40,
                '填空题' => 30,
                '解答题' => 30,
            ],
            'paper_name' => $params['paper_name'] ?? ('专项练习_' . now()->format('Ymd_His')),
            // 标记这是专项练习，用于后续处理
            'is_practice_exam' => true,
            'weakness_filter' => $weaknessFilter,
        ]);

        Log::info('ExamTypeStrategy: 专项练习参数构建完成（未应用难度分布）', [
            'intensity' => $intensity,
            'difficulty_category' => $params['difficulty_category'] ?? 1,
            'kp_codes_count' => count($enhanced['kp_codes']),
            'weakness_count' => count($weaknessFilter),
            'note' => '将在buildParams中应用difficulty_category难度分布'
        ]);

        return $enhanced;
    }

    /**
     * 教材同步：按教材章节出题
     */
    private function buildTextbookParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建教材同步参数', $params);

        // 教材同步：按章节顺序，难度递增
        // 【修复】移除硬编码难度配比，使用difficulty_category参数
        $textbookOptions = $params['textbook_options'] ?? [];

        $enhanced = array_merge($params, [
            'question_type_ratio' => [
                '选择题' => 40,
                '填空题' => 30,
                '解答题' => 30,
            ],
            'paper_name' => $params['paper_name'] ?? ('教材同步_' . now()->format('Ymd_His')),
            'textbook_options' => $textbookOptions,
        ]);

        Log::info('ExamTypeStrategy: 教材同步参数构建完成（未应用难度分布）', [
            'difficulty_category' => $params['difficulty_category'] ?? 1,
            'note' => '将在buildParams中应用difficulty_category难度分布'
        ]);

        return $enhanced;
    }

    /**
     * 知识点专练：单个或少量知识点深练
     */
    private function buildKnowledgeParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建知识点专练参数', $params);

        // 知识点专练：深度挖掘，多角度考查
        // 【修复】移除硬编码难度配比，使用difficulty_category参数
        $knowledgeOptions = $params['knowledge_options'] ?? [];

        $enhanced = array_merge($params, [
            'question_type_ratio' => [
                '选择题' => 30,
                '填空题' => 35,
                '解答题' => 35,
            ],
            'paper_name' => $params['paper_name'] ?? ('知识点专练_' . now()->format('Ymd_His')),
            'knowledge_options' => $knowledgeOptions,
        ]);

        Log::info('ExamTypeStrategy: 知识点专练参数构建完成（未应用难度分布）', [
            'difficulty_category' => $params['difficulty_category'] ?? 1,
            'note' => '将在buildParams中应用difficulty_category难度分布'
        ]);

        return $enhanced;
    }

    /**
     * 按知识点组卷：根据指定知识点数组智能选题
     * 优先级策略：
     * 1. 直接关联知识点题目（来自输入数组）
     * 2. 相同知识点其他题目
     * 3. 子知识点题目（下探1层）
     * 4. 薄弱点题目比例调整
     * 5. 子知识点题目（下探2层）
     */
    private function buildKnowledgePointsParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建按知识点组卷参数', $params);

        $studentId = $params['student_id'] ?? null;
        $totalQuestions = $params['total_questions'] ?? 20;
        $knowledgePointsOptions = $params['knowledge_points_options'] ?? [];
        $weaknessThreshold = $knowledgePointsOptions['weakness_threshold'] ?? 0.7;
        $focusWeaknesses = $knowledgePointsOptions['focus_weaknesses'] ?? true;
        $intensity = $knowledgePointsOptions['intensity'] ?? 'medium';

        // 获取用户指定的知识点数组
        $targetKnowledgePoints = $params['kp_codes'] ?? [];
        if (empty($targetKnowledgePoints)) {
            Log::warning('ExamTypeStrategy: 未指定知识点数组，使用默认策略');
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 目标知识点数组', [
            'target_knowledge_points' => $targetKnowledgePoints,
            'count' => count($targetKnowledgePoints)
        ]);

        // 根据强度调整难度配比
        $difficultyRatio = match($intensity) {
            'low' => [
                '基础' => 60,
                '中等' => 35,
                '拔高' => 5,
            ],
            'medium' => [
                '基础' => 45,
                '中等' => 40,
                '拔高' => 15,
            ],
            'high' => [
                '基础' => 30,
                '中等' => 45,
                '拔高' => 25,
            ],
            default => [
                '基础' => 45,
                '中等' => 40,
                '拔高' => 15,
            ]
        };

        // 获取学生薄弱点（用于判断目标知识点是否为薄弱点）
        $weaknessFilter = [];
        if ($studentId && $focusWeaknesses) {
            $weaknessFilter = $this->getStudentWeaknesses($studentId, $weaknessThreshold);
            Log::info('ExamTypeStrategy: 获取到学生薄弱点', [
                'student_id' => $studentId,
                'weakness_threshold' => $weaknessThreshold,
                'weakness_count' => count($weaknessFilter)
            ]);
        }

        // 检查目标知识点中哪些是薄弱点
        $weaknessKpCodes = array_column($weaknessFilter, 'kp_code');
        $targetWeaknessKps = array_intersect($targetKnowledgePoints, $weaknessKpCodes);

        Log::info('ExamTypeStrategy: 目标知识点中的薄弱点', [
            'target_weakness_kps' => $targetWeaknessKps,
            'weakness_count' => count($targetWeaknessKps)
        ]);

        // 使用 QuestionExpansionService 按知识点优先级扩展题目
        // 修改 expandQuestions 支持直接传入知识点数组
        $questionStrategy = $this->questionExpansionService->expandQuestionsByKnowledgePoints(
            $params,
            $studentId,
            $targetKnowledgePoints,
            $weaknessFilter,
            $totalQuestions
        );

        // 获取扩展统计
        $expansionStats = $this->questionExpansionService->getExpansionStats($questionStrategy);

        $enhanced = array_merge($params, [
            'difficulty_ratio' => $difficultyRatio,
            'kp_codes' => $targetKnowledgePoints, // 确保使用目标知识点
            'mistake_question_ids' => $questionStrategy['mistake_question_ids'] ?? [],
            // 优先级知识点：目标知识点 + 薄弱点
            'priority_knowledge_points' => array_merge(
                array_values($targetKnowledgePoints),
                array_column($weaknessFilter, 'kp_code')
            ),
            'question_type_ratio' => [
                '选择题' => 35,
                '填空题' => 30,
                '解答题' => 35,
            ],
            'paper_name' => $params['paper_name'] ?? ('知识点组卷_' . now()->format('Ymd_His')),
            // 标记这是按知识点组卷，用于后续处理
            'is_knowledge_points_exam' => true,
            'weakness_filter' => $weaknessFilter,
            // 目标知识点中的薄弱点（用于调整题目数量）
            'target_weakness_kps' => array_values($targetWeaknessKps),
            // 题目扩展统计
            'question_expansion_stats' => $expansionStats
        ]);

        Log::info('ExamTypeStrategy: 按知识点组卷参数构建完成', [
            'intensity' => $intensity,
            'target_knowledge_points_count' => count($targetKnowledgePoints),
            'target_weakness_kps_count' => count($targetWeaknessKps),
            'mistake_question_ids_count' => count($enhanced['mistake_question_ids']),
            'priority_knowledge_points_count' => count($enhanced['priority_knowledge_points']),
            'question_expansion_stats' => $enhanced['question_expansion_stats'],
            'weakness_count' => count($weaknessFilter)
        ]);

        return $enhanced;
    }

    /**
     * 为摸底测试扩展知识点（确保覆盖全面）
     */
    private function expandKpCodesForDiagnostic(array $kpCodes): array
    {
        if (!empty($kpCodes)) {
            return $kpCodes;
        }

        // 如果没有指定知识点，返回一些通用的数学知识点
        return [
            '一元二次方程',
            '二次函数',
            '旋转',
            '圆',
            '概率初步',
        ];
    }

    /**
     * 获取学生薄弱点
     */
    private function getStudentWeaknesses(string $studentId, float $threshold): array
    {
        try {
            // 使用 StudentKnowledgeMastery 模型获取掌握度低于阈值的知识点
            $weaknessRecords = StudentKnowledgeMastery::forStudent($studentId)
                ->weaknesses($threshold)
                ->orderByMastery('asc')
                ->limit(20)
                ->with('knowledgePoint') // 预加载知识点信息
                ->get();

            // 转换为统一格式
            return $weaknessRecords->map(function ($record) {
                return [
                    'kp_code' => $record->kp_code,
                    'kp_name' => $record->knowledgePoint->name ?? $record->kp_code,
                    'mastery' => (float) ($record->mastery_level ?? 0),
                    'attempts' => (int) ($record->total_attempts ?? 0),
                    'correct' => (int) ($record->correct_attempts ?? 0),
                    'incorrect' => (int) ($record->incorrect_attempts ?? 0),
                    'confidence' => (float) ($record->confidence_level ?? 0),
                    'trend' => $record->mastery_trend ?? 'stable',
                ];
            })->toArray();

        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 获取学生薄弱点失败', [
                'student_id' => $studentId,
                'threshold' => $threshold,
                'error' => $e->getMessage()
            ]);

            return [];
        }
    }

    /**
     * 智能组卷 (assembleType=1)
     * 根据 textbook_id 查询章节，获取知识点，然后组卷
     * 增加年级概念选题逻辑
     */
    private function buildIntelligentAssembleParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建智能组卷参数', $params);

        $textbookId = $params['textbook_id'] ?? null;
        $grade = $params['grade'] ?? null; // 年级信息
        $totalQuestions = $params['total_questions'] ?? 20;

        if (!$textbookId) {
            Log::warning('ExamTypeStrategy: 智能组卷需要 textbook_id 参数');
            return $this->buildGeneralParams($params);
        }

        // 第一步：根据 textbook_id 查询章节
        $catalogChapterIds = $this->getTextbookChapterIds($textbookId);

        if (empty($catalogChapterIds)) {
            Log::warning('ExamTypeStrategy: 未找到课本章节', ['textbook_id' => $textbookId]);
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 获取到课本章节', [
            'textbook_id' => $textbookId,
            'chapter_count' => count($catalogChapterIds)
        ]);

        // 第二步：根据章节ID查询知识点关联
        $kpCodes = $this->getKnowledgePointsFromChapters($catalogChapterIds, 25);

        if (empty($kpCodes)) {
            Log::warning('ExamTypeStrategy: 未找到知识点关联', [
                'textbook_id' => $textbookId,
                'chapter_ids' => $catalogChapterIds
            ]);
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 获取到知识点', [
            'kp_count' => count($kpCodes),
            'kp_codes' => array_slice($kpCodes, 0, 5) // 只记录前5个
        ]);

        // 组装增强参数
        $enhanced = array_merge($params, [
            'kp_codes' => $kpCodes,
            'textbook_id' => $textbookId,
            'grade' => $grade,
            'catalog_chapter_ids' => $catalogChapterIds,
            'paper_name' => $params['paper_name'] ?? ('智能组卷_' . now()->format('Ymd_His')),
            // 智能组卷：平衡的题型和难度配比
            'question_type_ratio' => [
                '选择题' => 40,
                '填空题' => 30,
                '解答题' => 30,
            ],
            'difficulty_ratio' => [
                '基础' => 25,
                '中等' => 50,
                '拔高' => 25,
            ],
            'question_category' => 0, // question_category=0 代表普通题目（智能组卷）
            'is_intelligent_assemble' => true,
        ]);

        Log::info('ExamTypeStrategy: 智能组卷参数构建完成', [
            'textbook_id' => $textbookId,
            'grade' => $grade,
            'kp_count' => count($kpCodes),
            'total_questions' => $totalQuestions
        ]);

        return $enhanced;
    }

    /**
     * 知识点组卷 (assembleType=2)
     * 直接根据 kp_code_list 查询题目，排除已做过的题目
     */
    private function buildKnowledgePointAssembleParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建知识点组卷参数', $params);

        $kpCodeList = $params['kp_code_list'] ?? [];
        $studentId = $params['student_id'] ?? null;
        $totalQuestions = $params['total_questions'] ?? 20;

        if (empty($kpCodeList)) {
            Log::warning('ExamTypeStrategy: 知识点组卷需要 kp_code_list 参数');
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 知识点组卷', [
            'kp_code_list' => $kpCodeList,
            'student_id' => $studentId,
            'total_questions' => $totalQuestions
        ]);

        // 如果有学生ID，获取已做过的题目ID列表（用于排除）
        $answeredQuestionIds = [];
        if ($studentId) {
            $answeredQuestionIds = $this->getStudentAnsweredQuestionIds($studentId, $kpCodeList);
            Log::info('ExamTypeStrategy: 获取学生已答题目', [
                'student_id' => $studentId,
                'answered_count' => count($answeredQuestionIds)
            ]);
        }

        // 组装增强参数
        $enhanced = array_merge($params, [
            'kp_codes' => $kpCodeList,
            'exclude_question_ids' => $answeredQuestionIds,
            'paper_name' => $params['paper_name'] ?? ('知识点组卷_' . now()->format('Ymd_His')),
            // 知识点组卷：注重题型平衡（恢复原有配比）
            'question_type_ratio' => [
                '选择题' => 35,
                '填空题' => 30,
                '解答题' => 35,
            ],
            'difficulty_ratio' => [
                '基础' => 25,
                '中等' => 50,
                '拔高' => 25,
            ],
            'question_category' => 0, // question_category=0 代表普通题目
            'is_knowledge_point_assemble' => true,
        ]);

        Log::info('ExamTypeStrategy: 知识点组卷参数构建完成', [
            'kp_count' => count($kpCodeList),
            'exclude_count' => count($answeredQuestionIds),
            'total_questions' => $totalQuestions
        ]);

        return $enhanced;
    }

    /**
     * 教材组卷 (assembleType=3)
     * 根据 chapter_id_list 查询课本章节，获取知识点，然后组卷
     * 优化：按textbook_catalog_node_id筛选题目，添加章节知识点数量统计
     */
    private function buildTextbookAssembleParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建教材组卷参数', $params);

        $chapterIdList = $params['chapter_id_list'] ?? [];
        $studentId = $params['student_id'] ?? null;
        $totalQuestions = $params['total_questions'] ?? 20;

        // 【优化】如果用户没有指定章节，自动从教材所有有题目的章节中选择
        if (empty($chapterIdList) && !empty($params['textbook_id'])) {
            Log::info('ExamTypeStrategy: 用户未指定章节，自动从教材选择', [
                'textbook_id' => $params['textbook_id']
            ]);

            // 【修复】先查询教材下的所有章节，再筛选有题目的章节
            // 步骤1：根据textbook_id获取该教材下的所有章节ID
            $allChapterIds = DB::table('textbook_catalog_nodes')
                ->where('textbook_id', $params['textbook_id'])
                ->where('node_type', 'section')
                ->pluck('id')
                ->toArray();

            if (empty($allChapterIds)) {
                Log::warning('ExamTypeStrategy: 教材下未找到章节', [
                    'textbook_id' => $params['textbook_id']
                ]);
            } else {
                // 步骤2：从这些章节中筛选出有题目的章节
                $chapterIdList = DB::table('questions')
                    ->whereIn('textbook_catalog_nodes_id', $allChapterIds)
                    ->whereNotNull('textbook_catalog_nodes_id')
                    ->where('textbook_catalog_nodes_id', '!=', '')
                    ->distinct()
                    ->pluck('textbook_catalog_nodes_id')
                    ->toArray();

                Log::info('ExamTypeStrategy: 自动选择的章节列表', [
                    'textbook_id' => $params['textbook_id'],
                    'total_chapters' => count($allChapterIds),
                    'chapters_with_questions' => count($chapterIdList),
                    'chapter_ids' => $chapterIdList
                ]);
            }
        }

        // 【新增】如果用户指定了章节，解析章节节点类型并获取所有section/subsection节点
        if (!empty($chapterIdList)) {
            Log::info('ExamTypeStrategy: 用户指定了章节，开始解析节点类型', [
                'input_chapter_ids' => $chapterIdList
            ]);

            // 解析用户传入的chapter_id_list，获取所有section/subsection节点
            $resolvedSectionIds = $this->resolveSectionNodesFromChapters($chapterIdList);

            if (!empty($resolvedSectionIds)) {
                // 使用解析后的section/subsection节点ID替换原有的chapterIdList
                $originalChapterCount = count($chapterIdList);
                $chapterIdList = $resolvedSectionIds;

                Log::info('ExamTypeStrategy: 章节节点解析完成，使用解析后的节点', [
                    'original_count' => $originalChapterCount,
                    'resolved_count' => count($chapterIdList),
                    'resolved_ids' => $chapterIdList
                ]);
            } else {
                Log::warning('ExamTypeStrategy: 章节节点解析失败，使用原始节点列表', [
                    'chapter_id_list' => $chapterIdList
                ]);
            }
        }

        if (empty($chapterIdList)) {
            Log::warning('ExamTypeStrategy: 教材组卷需要 chapter_id_list 参数或有效的textbook_id');
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 教材组卷', [
            'chapter_id_list' => $chapterIdList,
            'student_id' => $studentId,
            'total_questions' => $totalQuestions
        ]);

        // 【修复】第一步：根据章节ID查询知识点关联，并统计每个章节的知识点数量
        $kpCodes = $this->getKnowledgePointsFromChapters($chapterIdList);

        // 【新增】获取每个章节对应的知识点数量统计
        $chapterKnowledgePointStats = $this->getChapterKnowledgePointStats($chapterIdList);

        Log::info('ExamTypeStrategy: 获取章节知识点统计', [
            'chapter_stats' => $chapterKnowledgePointStats,
            'total_chapters' => count($chapterIdList)
        ]);

        // 【重要】教材组卷严格限制知识点数量，不进行任何扩展
        if (empty($kpCodes)) {
            Log::warning('ExamTypeStrategy: 未找到章节知识点关联，但保留章节筛选参数', [
                'chapter_id_list' => $chapterIdList,
                'note' => '将在LearningAnalyticsService中按textbook_catalog_nodes_id字段筛选题目'
            ]);
        } else {
            Log::info('ExamTypeStrategy: 获取章节知识点（教材组卷严格限制）', [
                'kp_count' => count($kpCodes),
                'kp_codes' => $kpCodes,
                'note' => '教材组卷只返回章节关联的知识点，不进行扩展'
            ]);
        }

        // 第二步：如果有学生ID，获取已做过的题目ID列表（用于排除）
        $answeredQuestionIds = [];
        if ($studentId) {
            $answeredQuestionIds = $this->getStudentAnsweredQuestionIds($studentId, $kpCodes);
            Log::info('ExamTypeStrategy: 获取学生已答题目', [
                'student_id' => $studentId,
                'answered_count' => count($answeredQuestionIds)
            ]);
        }

        // 【优化】第三步：按textbook_catalog_node_id筛选题目，添加筛选条件
        // 在LearningAnalyticsService中会使用这些参数进行题目筛选
        $textbookCatalogNodeIds = $chapterIdList; // 直接使用章节ID作为textbook_catalog_node_id筛选条件

        // 组装增强参数
        $enhanced = array_merge($params, [
            'kp_codes' => $kpCodes, // 可能为空，但仍保留
            'chapter_id_list' => $chapterIdList,
            'textbook_catalog_node_ids' => $textbookCatalogNodeIds, // 【重要】即使kpCodes为空也设置此参数
            'exclude_question_ids' => $answeredQuestionIds,
            'paper_name' => $params['paper_name'] ?? ('教材组卷_' . now()->format('Ymd_His')),
            // 教材组卷：按教材特点分配题型
            'question_type_ratio' => [
                '选择题' => 40,
                '填空题' => 30,
                '解答题' => 30,
            ],
            'difficulty_ratio' => [
                '基础' => 25,
                '中等' => 50,
                '拔高' => 25,
            ],
            'question_category' => 0, // question_category=0 代表普通题目
            'is_textbook_assemble' => true,
            // 【新增】章节知识点数量统计
            'chapter_knowledge_point_stats' => $chapterKnowledgePointStats,
        ]);

        Log::info('ExamTypeStrategy: 教材组卷参数构建完成', [
            'chapter_count' => count($chapterIdList),
            'kp_count' => count($kpCodes),
            'exclude_count' => count($answeredQuestionIds),
            'total_questions' => $totalQuestions,
            'chapter_stats' => $chapterKnowledgePointStats
        ]);

        return $enhanced;
    }

    /**
     * 根据课本ID获取章节ID列表
     */
    private function getTextbookChapterIds(int $textbookId): array
    {
        try {
            // 查询 text_book_catalog_nodes 表
            $chapterIds = DB::table('textbook_catalog_nodes')
                ->where('textbook_id', $textbookId)
                ->where('node_type', 'section') // nodeType='section'
                ->orderBy('sort_order')
                ->pluck('id')
                ->toArray();

            Log::debug('ExamTypeStrategy: 查询课本章节ID', [
                'textbook_id' => $textbookId,
                'found_count' => count($chapterIds)
            ]);

            return $chapterIds;
        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 查询课本章节ID失败', [
                'textbook_id' => $textbookId,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 根据章节ID列表获取知识点代码列表（均等抽样版本）
     * 使用"知识点均等抽样"算法，确保覆盖全书章节
     *
     * @param array $chapterIds 章节ID列表
     * @param int $limit 目标题目数量（默认25）
     * @return array 抽样后的知识点代码列表
     */
    private function getKnowledgePointsFromChapters(array $chapterIds, int $limit = 25): array
    {
        try {
            // 如果章节数较少，使用原有逻辑
            if (count($chapterIds) <= 5) {
                Log::info('ExamTypeStrategy: 章节数较少，使用原有逻辑', [
                    'chapter_count' => count($chapterIds)
                ]);
                return $this->getKnowledgePointsFromChaptersLegacy($chapterIds, $limit);
            }

            // ========== 步骤1: 构建全量有序池 ==========
            // 查询所有知识点，按章节顺序排列，去重后得到有序数组
            $allKpData = DB::table('textbook_chapter_knowledge_relation as tckr')
                ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
                ->whereIn('tckr.catalog_chapter_id', $chapterIds)
                ->select('tckr.kp_code', 'tcn.sort_order', 'tcn.id as chapter_id', 'tcn.title as chapter_title')
                ->orderBy('tcn.sort_order', 'asc')
                ->orderBy('tckr.kp_code', 'asc')
                ->get();

            // 去重并构建有序数组
            $allKpCodes = [];
            $chapterInfo = [];
            foreach ($allKpData as $row) {
                if (!in_array($row->kp_code, $allKpCodes)) {
                    $allKpCodes[] = $row->kp_code;
                    $chapterInfo[$row->kp_code] = [
                        'chapter_id' => $row->chapter_id,
                        'chapter_title' => $row->chapter_title,
                        'sort_order' => $row->sort_order
                    ];
                }
            }

            $totalKps = count($allKpCodes);

            Log::info('ExamTypeStrategy: 构建全量有序池完成', [
                'chapter_count' => count($chapterIds),
                'total_knowledge_points' => $totalKps,
                'target_questions' => $limit
            ]);

            // ========== 步骤2: 计算抽样步长 ==========
            $step = $totalKps > 0 ? $totalKps / $limit : 1;
            Log::info('ExamTypeStrategy: 计算抽样步长', [
                'step' => $step
            ]);

            // ========== 步骤3: 等距取样 ==========
            $selectedKps = [];
            $selectedCount = 0;
            $currentIndex = 0;

            while ($selectedCount < $limit && $selectedCount < $totalKps) {
                $index = (int) floor($currentIndex);
                if ($index < $totalKps && isset($allKpCodes[$index])) {
                    $kpCode = $allKpCodes[$index];
                    if (!in_array($kpCode, $selectedKps)) {
                        $selectedKps[] = $kpCode;
                        $selectedCount++;
                    }
                }
                $currentIndex += $step;
            }

            // 如果数量不足，循环取样
            if (count($selectedKps) < $limit && $totalKps > 0) {
                Log::info('ExamTypeStrategy: 第一次抽样不足，进行循环取样', [
                    'selected_count' => count($selectedKps),
                    'target_count' => $limit
                ]);

                $needed = $limit - count($selectedKps);
                $startIndex = 0;

                for ($i = 0; $i < $needed && count($selectedKps) < $limit; $i++) {
                    $index = ($startIndex + $i) % $totalKps;
                    $kpCode = $allKpCodes[$index];
                    if (!in_array($kpCode, $selectedKps)) {
                        $selectedKps[] = $kpCode;
                    }
                }
            }

            // ========== 步骤4: 记录抽样统计 ==========
            $chapterDistribution = [];
            foreach ($selectedKps as $kpCode) {
                if (isset($chapterInfo[$kpCode])) {
                    $chapterId = $chapterInfo[$kpCode]['chapter_id'];
                    if (!isset($chapterDistribution[$chapterId])) {
                        $chapterDistribution[$chapterId] = [
                            'count' => 0,
                            'title' => $chapterInfo[$kpCode]['chapter_title']
                        ];
                    }
                    $chapterDistribution[$chapterId]['count']++;
                }
            }

            Log::info('ExamTypeStrategy: 等距抽样完成', [
                'total_kps' => $totalKps,
                'selected_kps' => count($selectedKps),
                'step' => $step,
                'chapter_distribution' => $chapterDistribution,
                'sample_kp_codes' => array_slice($selectedKps, 0, 10)
            ]);

            return array_filter($selectedKps);

        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 均等抽样获取章节知识点失败，使用原有逻辑', [
                'chapter_ids' => $chapterIds,
                'error' => $e->getMessage()
            ]);

            // 失败时回退到原有逻辑
            return $this->getKnowledgePointsFromChaptersLegacy($chapterIds, $limit);
        }
    }

    /**
     * 原有逻辑（保留作为回退方案）
     * 修复：解决DISTINCT和ORDER BY冲突问题
     */
    private function getKnowledgePointsFromChaptersLegacy(array $chapterIds, int $limit = 25): array
    {
        try {
            // 修复方案1：使用GROUP BY替代DISTINCT，并选择需要的字段
            $kpCodes = DB::table('textbook_chapter_knowledge_relation as tckr')
                ->leftJoin('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
                ->whereIn('tckr.catalog_chapter_id', $chapterIds)
                ->select('tckr.kp_code', 'tcn.sort_order')
                ->orderBy('tcn.sort_order', 'asc')
                ->orderBy('tckr.kp_code', 'asc')
                ->limit($limit)
                ->groupBy('tckr.kp_code')
                ->pluck('tckr.kp_code')
                ->toArray();

            Log::debug('ExamTypeStrategy: 查询章节知识点（原有逻辑）', [
                'chapter_count' => count($chapterIds),
                'found_kp_count' => count($kpCodes)
            ]);

            return array_filter($kpCodes); // 移除空值
        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 查询章节知识点失败', [
                'chapter_ids' => $chapterIds,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 获取学生已答题目ID列表（用于排除）
     */
    private function getStudentAnsweredQuestionIds(string $studentId, array $kpCodes): array
    {
        try {
            // 【修复】查询 student_answer_questions 表，不使用 kp_code 过滤（该字段可能不存在）
            $query = DB::table('student_answer_questions')
                ->where('student_id', $studentId)
                ->distinct();

            // 如果有 question_id 字段，直接查询
            $questionIds = $query->pluck('question_id')->toArray();

            Log::debug('ExamTypeStrategy: 查询学生已答题目', [
                'student_id' => $studentId,
                'kp_count' => count($kpCodes),
                'answered_count' => count($questionIds),
                'note' => '只按学生ID过滤，不按kp_code过滤'
            ]);

            return array_filter($questionIds); // 移除空值
        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 查询学生已答题目失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 通过卷子ID列表查询错题
     * 注意：paper_ids 使用的是 papers 表中的 paper_id 字段，不是 id 字段
     * 错题数据从 mistake_records 表中获取，该表已包含 paper_id 字段
     * 注意：不按学生ID过滤，因为卷子可能包含其他同学的错题，需要收集所有错题
     */
    private function getMistakeQuestionsFromPapers(array $paperIds, ?string $studentId = null): array
    {
        try {
            // 使用 Eloquent 模型查询，从 mistake_records 表中获取错题记录
            // 不按 student_id 过滤，因为要收集所有学生的错题
            $mistakeRecords = MistakeRecord::query()
                ->whereIn('paper_id', $paperIds)
                ->get();

            if ($mistakeRecords->isEmpty()) {
                Log::warning('ExamTypeStrategy: 卷子中未找到错题记录', [
                    'paper_ids' => $paperIds
                ]);
                return [];
            }

            // 收集所有错题的 question_id
            $questionIds = $mistakeRecords->pluck('question_id')
                ->filter()
                ->unique()
                ->values()
                ->toArray();

            Log::info('ExamTypeStrategy: 查询卷子错题完成', [
                'paper_count' => count($paperIds),
                'paper_ids_input' => $paperIds,
                'mistake_record_count' => $mistakeRecords->count(),
                'unique_question_count' => count($questionIds),
                'question_ids' => array_slice($questionIds, 0, 20), // 最多记录20个ID
                'per_paper_stats' => $mistakeRecords->groupBy('paper_id')->map->count()->toArray()
            ]);

            return array_filter($questionIds);

        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 查询卷子错题失败', [
                'paper_ids' => $paperIds,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 通过题目ID列表获取知识点代码列表
     */
    private function getKnowledgePointsFromQuestions(array $questionIds): array
    {
        try {
            // 使用 Eloquent 模型查询，获取题目的知识点
            $questions = Question::whereIn('id', $questionIds)
                ->whereNotNull('kp_code')
                ->where('kp_code', '!=', '')
                ->distinct()
                ->pluck('kp_code')
                ->toArray();

            Log::debug('ExamTypeStrategy: 查询题目知识点', [
                'question_count' => count($questionIds),
                'kp_count' => count($questions)
            ]);

            return array_filter($questions);
        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 查询题目知识点失败', [
                'question_ids' => array_slice($questionIds, 0, 10), // 只记录前10个
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 【新增】获取每个章节对应的知识点数量统计
     * 通过textbook_chapter_knowledge_relation表关联查询
     *
     * @param array $chapterIdList 章节ID列表
     * @return array 章节知识点数量统计
     */
    private function getChapterKnowledgePointStats(array $chapterIdList): array
    {
        try {
            // 查询每个章节对应的知识点数量
            $stats = DB::table('textbook_chapter_knowledge_relation as tckr')
                ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
                ->whereIn('tckr.catalog_chapter_id', $chapterIdList)
                ->select(
                    'tckr.catalog_chapter_id as chapter_id',
                    'tcn.title as chapter_title',
                    DB::raw('COUNT(DISTINCT tckr.kp_code) as knowledge_point_count')
                )
                ->groupBy('tckr.catalog_chapter_id', 'tcn.title')
                ->orderBy('tckr.catalog_chapter_id')
                ->get();

            // 转换为数组格式
            $result = [];
            foreach ($stats as $stat) {
                $result[] = [
                    'chapter_id' => $stat->chapter_id,
                    'chapter_title' => $stat->chapter_title,
                    'knowledge_point_count' => (int) $stat->knowledge_point_count
                ];
            }

            Log::debug('ExamTypeStrategy: 获取章节知识点统计', [
                'chapter_count' => count($chapterIdList),
                'stats_count' => count($result),
                'stats' => $result
            ]);

            return $result;

        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 获取章节知识点统计失败', [
                'chapter_id_list' => $chapterIdList,
                'error' => $e->getMessage()
            ]);

            // 返回空数组，不影响组卷流程
            return [];
        }
    }

    /**
     * 【新增】递归获取section节点ID列表
     * 根据用户传入的chapter_id_list，自动识别节点类型：
     * - 如果是chapter节点，查找其下的所有section子节点（不包含subsection）
     * - 如果是section节点，直接使用
     *
     * @param array $chapterIdList 用户传入的章节ID列表
     * @return array 最终用于查询知识点的section节点ID列表
     */
    private function resolveSectionNodesFromChapters(array $chapterIdList): array
    {
        try {
            if (empty($chapterIdList)) {
                return [];
            }

            Log::info('ExamTypeStrategy: 开始解析章节节点', [
                'input_chapter_ids' => $chapterIdList
            ]);

            $finalSectionIds = [];

            foreach ($chapterIdList as $nodeId) {
                // 查询节点信息
                $node = DB::table('textbook_catalog_nodes')
                    ->where('id', $nodeId)
                    ->first();

                if (!$node) {
                    Log::warning('ExamTypeStrategy: 未找到节点', ['node_id' => $nodeId]);
                    continue;
                }

                Log::debug('ExamTypeStrategy: 处理节点', [
                    'node_id' => $nodeId,
                    'node_type' => $node->node_type,
                    'title' => $node->title
                ]);

                // 根据节点类型处理
                switch ($node->node_type) {
                    case 'chapter':
                        // 如果是chapter节点，查找其下的所有section子节点
                        $childNodes = DB::table('textbook_catalog_nodes')
                            ->where('parent_id', $nodeId)
                            ->where('node_type', 'section')
                            ->orderBy('sort_order')
                            ->get();

                        Log::info('ExamTypeStrategy: 解析chapter节点', [
                            'chapter_id' => $nodeId,
                            'chapter_title' => $node->title,
                            'section_count' => count($childNodes)
                        ]);

                        foreach ($childNodes as $child) {
                            if (!in_array($child->id, $finalSectionIds)) {
                                $finalSectionIds[] = $child->id;
                                Log::debug('ExamTypeStrategy: 添加section子节点', [
                                    'parent_chapter' => $nodeId,
                                    'child_node_id' => $child->id,
                                    'child_title' => $child->title,
                                    'child_type' => $child->node_type
                                ]);
                            }
                        }
                        break;

                    case 'section':
                        // 如果是section节点，直接使用
                        if (!in_array($nodeId, $finalSectionIds)) {
                            $finalSectionIds[] = $nodeId;
                            Log::debug('ExamTypeStrategy: 直接使用section节点', [
                                'node_id' => $nodeId,
                                'title' => $node->title,
                                'node_type' => $node->node_type
                            ]);
                        }
                        break;

                    case 'subsection':
                        // 如果是subsection节点，需要找到其父级section节点
                        $parentSection = DB::table('textbook_catalog_nodes')
                            ->where('id', $node->parent_id)
                            ->where('node_type', 'section')
                            ->first();

                        if ($parentSection && !in_array($parentSection->id, $finalSectionIds)) {
                            $finalSectionIds[] = $parentSection->id;
                            Log::debug('ExamTypeStrategy: 通过subsection找到父级section', [
                                'subsection_id' => $nodeId,
                                'subsection_title' => $node->title,
                                'parent_section_id' => $parentSection->id,
                                'parent_section_title' => $parentSection->title
                            ]);
                        }
                        break;

                    default:
                        Log::warning('ExamTypeStrategy: 未知节点类型', [
                            'node_id' => $nodeId,
                            'node_type' => $node->node_type
                        ]);
                        break;
                }
            }

            Log::info('ExamTypeStrategy: 章节节点解析完成', [
                'input_count' => count($chapterIdList),
                'output_section_count' => count($finalSectionIds),
                'section_ids' => $finalSectionIds
            ]);

            return $finalSectionIds;

        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 解析章节节点失败', [
                'chapter_id_list' => $chapterIdList,
                'error' => $e->getMessage()
            ]);

            // 出错时返回空数组
            return [];
        }
    }
}
