<?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' => $difficultyCategory,
        ]);

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

        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' => array_slice($kpCodes, 0, 5)
        ]);

        // 摸底测试：平衡所有难度，覆盖多个知识点
        $enhanced = array_merge($params, [
            'kp_codes' => $kpCodes,
            'textbook_id' => $textbookId,
            'grade' => $grade,
            'catalog_chapter_ids' => $catalogChapterIds,
            // 难度配比：相对平衡，基础题稍多
            'difficulty_ratio' => [
                '基础' => 40,
                '中等' => 40,
                '拔高' => 20,
            ],
            // 题型配比：选择题多一些，便于快速评估
            '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
        ]);

        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);

        // 组装增强参数
        $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')),
            // 错题本：保持原有题型配比
            'question_type_ratio' => [
                '选择题' => 35,
                '填空题' => 30,
                '解答题' => 35,
            ],
            // 错题本不应用难度分布
            'is_mistake_exam' => true,
            'is_paper_based_mistake' => true, // 标记是基于卷子的错题本
            'mistake_count' => count($mistakeQuestionIds),
            'knowledge_points_count' => count($mistakeKnowledgePoints),
        ]);

        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;

        // 根据强度调整难度配比
        $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)
            ]);
        }

        // 优先使用薄弱点知识点，如果没有则使用用户选择的知识点
        $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, [
            'difficulty_ratio' => $difficultyRatio,
            '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_ratio' => $enhanced['difficulty_ratio'],
            'kp_codes_count' => count($enhanced['kp_codes']),
            'weakness_count' => count($weaknessFilter)
        ]);

        return $enhanced;
    }

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

        // 教材同步：按章节顺序，难度递增
        $textbookOptions = $params['textbook_options'] ?? [];

        $enhanced = array_merge($params, [
            // 教材同步：基础和中等题为主
            'difficulty_ratio' => [
                '基础' => 50,
                '中等' => 40,
                '拔高' => 10,
            ],
            'question_type_ratio' => [
                '选择题' => 40,
                '填空题' => 30,
                '解答题' => 30,
            ],
            'paper_name' => $params['paper_name'] ?? ('教材同步_' . now()->format('Ymd_His')),
            'textbook_options' => $textbookOptions,
        ]);

        return $enhanced;
    }

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

        // 知识点专练：深度挖掘，多角度考查
        $knowledgeOptions = $params['knowledge_options'] ?? [];

        $enhanced = array_merge($params, [
            // 知识点专练：难度分布更均匀
            'difficulty_ratio' => [
                '基础' => 35,
                '中等' => 45,
                '拔高' => 20,
            ],
            'question_type_ratio' => [
                '选择题' => 30,
                '填空题' => 35,
                '解答题' => 35,
            ],
            'paper_name' => $params['paper_name'] ?? ('知识点专练_' . now()->format('Ymd_His')),
            'knowledge_options' => $knowledgeOptions,
        ]);

        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 查询课本章节，获取知识点，然后组卷
     */
    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)) {
            Log::warning('ExamTypeStrategy: 教材组卷需要 chapter_id_list 参数');
            return $this->buildGeneralParams($params);
        }

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

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

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

        Log::info('ExamTypeStrategy: 获取章节知识点', [
            'kp_count' => count($kpCodes),
            'kp_codes' => array_slice($kpCodes, 0, 5)
        ]);

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

        // 组装增强参数
        $enhanced = array_merge($params, [
            'kp_codes' => $kpCodes,
            'chapter_id_list' => $chapterIdList,
            '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,
        ]);

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

        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列表获取知识点代码列表
     */
    private function getKnowledgePointsFromChapters(array $chapterIds, int $limit = 25): array
    {
        try {
            // 查询 textbook_chapter_knowledge_relation 表
            $kpCodes = DB::table('textbook_chapter_knowledge_relation')
                ->whereIn('catalog_chapter_id', $chapterIds)
                ->limit($limit)
                ->distinct()
                ->pluck('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 表
            $questionIds = DB::table('student_answer_questions')
                ->where('student_id', $studentId)
                ->whereIn('kp_code', $kpCodes)
                ->distinct()
                ->pluck('question_id')
                ->toArray();

            Log::debug('ExamTypeStrategy: 查询学生已答题目', [
                'student_id' => $studentId,
                'kp_count' => count($kpCodes),
                'answered_count' => count($questionIds)
            ]);

            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 [];
        }
    }
}
