| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290 |
- <?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);
- // 组装增强参数
- $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;
- // 根据强度调整难度配比
- $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列表获取知识点代码列表(均等抽样版本)
- * 使用"知识点均等抽样"算法,确保覆盖全书章节
- *
- * @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);
- }
- }
- /**
- * 原有逻辑(保留作为回退方案)
- */
- private function getKnowledgePointsFromChaptersLegacy(array $chapterIds, int $limit = 25): array
- {
- try {
- // 查询 textbook_chapter_knowledge_relation 表(修复:添加排序避免数据偏向)
- $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)
- ->orderBy('tcn.sort_order', 'asc')
- ->orderBy('tckr.kp_code', 'asc')
- ->limit($limit)
- ->distinct()
- ->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 表
- $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 [];
- }
- }
- }
|