ExamTypeStrategy.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Log;
  4. use App\Models\StudentKnowledgeMastery;
  5. use App\Models\MistakeRecord;
  6. use App\Models\KnowledgePoint;
  7. use App\Models\Paper;
  8. use App\Models\PaperQuestion;
  9. use App\Models\Question;
  10. use Illuminate\Support\Facades\DB;
  11. class ExamTypeStrategy
  12. {
  13. protected QuestionExpansionService $questionExpansionService;
  14. protected QuestionLocalService $questionLocalService;
  15. public function __construct(QuestionExpansionService $questionExpansionService, QuestionLocalService $questionLocalService = null)
  16. {
  17. $this->questionExpansionService = $questionExpansionService;
  18. $this->questionLocalService = $questionLocalService ?? app(QuestionLocalService::class);
  19. }
  20. /**
  21. * 根据组卷类型构建参数
  22. * assembleType: 0-摸底, 1-智能组卷, 2-知识点组卷, 3-教材组卷, 4-通用, 5-错题本, 6-按知识点组卷
  23. */
  24. public function buildParams(array $baseParams, int $assembleType): array
  25. {
  26. Log::info('ExamTypeStrategy: 构建组卷参数', [
  27. 'assemble_type' => $assembleType,
  28. 'base_params_keys' => array_keys($baseParams)
  29. ]);
  30. return match($assembleType) {
  31. 0 => $this->applyDifficultyDistribution($this->buildDiagnosticParams($baseParams)), // 摸底
  32. 1 => $this->applyDifficultyDistribution($this->buildIntelligentAssembleParams($baseParams)), // 智能组卷
  33. 2 => $this->applyDifficultyDistribution($this->buildKnowledgePointAssembleParams($baseParams)), // 知识点组卷
  34. 3 => $this->applyDifficultyDistribution($this->buildTextbookAssembleParams($baseParams)), // 教材组卷
  35. 4 => $this->applyDifficultyDistribution($this->buildGeneralParams($baseParams)), // 通用
  36. 5 => $this->buildMistakeParams($baseParams), // 错题本不应用难度分布
  37. 6 => $this->applyDifficultyDistribution($this->buildKnowledgePointsParams($baseParams)), // 按知识点组卷
  38. default => $this->applyDifficultyDistribution($this->buildGeneralParams($baseParams))
  39. };
  40. }
  41. /**
  42. * 根据组卷类型构建参数(兼容旧版 exam_type 参数)
  43. * @deprecated 使用 buildParams(array, int) 替代
  44. */
  45. public function buildParamsLegacy(array $baseParams, string $examType): array
  46. {
  47. // 兼容旧版 exam_type 参数
  48. $assembleType = match($examType) {
  49. 'diagnostic' => 0,
  50. 'general' => 4,
  51. 'practice' => 5,
  52. 'mistake' => 5,
  53. 'textbook' => 3,
  54. 'knowledge' => 2,
  55. 'knowledge_points' => 6,
  56. default => 4
  57. };
  58. return $this->buildParams($baseParams, $assembleType);
  59. }
  60. /**
  61. * 通用智能出卷(原有行为)
  62. */
  63. private function buildGeneralParams(array $params): array
  64. {
  65. Log::info('ExamTypeStrategy: 通用智能出卷参数', $params);
  66. // 返回原始参数,难度分布逻辑在 buildParams 中统一处理
  67. return $params;
  68. }
  69. /**
  70. * 应用难度系数分布逻辑
  71. * 根据 difficulty_category 参数实现分层选题策略
  72. *
  73. * @param array $params 基础参数
  74. * @param bool $forceApply 是否强制应用(默认false,不对错题本类型应用)
  75. * @return array 增强后的参数
  76. */
  77. private function applyDifficultyDistribution(array $params, bool $forceApply = false): array
  78. {
  79. // 检查是否为排除类型(错题本 assembleType=5)
  80. $assembleType = (int) ($params['assemble_type'] ?? 4);
  81. $isExcludedType = ($assembleType === 5); // 只有错题本类型不应用难度分布
  82. // 如果不是强制应用且为排除类型,则不应用难度分布
  83. if (!$forceApply && $isExcludedType) {
  84. Log::info('ExamTypeStrategy: 跳过难度分布(错题本类型)', [
  85. 'assemble_type' => $assembleType
  86. ]);
  87. return $params;
  88. }
  89. $difficultyCategory = (int) ($params['difficulty_category'] ?? 1);
  90. $totalQuestions = (int) ($params['total_questions'] ?? 20);
  91. Log::info('ExamTypeStrategy: 应用难度系数分布', [
  92. 'difficulty_category' => $difficultyCategory,
  93. 'total_questions' => $totalQuestions,
  94. 'assemble_type' => $assembleType
  95. ]);
  96. // 根据难度类别计算题目分布
  97. $distribution = $this->calculateDifficultyDistribution($difficultyCategory, $totalQuestions);
  98. // 构建难度分布配置
  99. $difficultyDistributionConfig = [
  100. 'strategy' => 'difficulty分层选题',
  101. 'category' => $difficultyCategory,
  102. 'total_questions' => $totalQuestions,
  103. 'distribution' => $distribution,
  104. 'ranges' => $this->getDifficultyRanges($difficultyCategory),
  105. 'use_question_local_service' => true, // 标记使用新的独立方法
  106. ];
  107. $enhanced = array_merge($params, [
  108. 'difficulty_distribution_config' => $difficultyDistributionConfig,
  109. // 保留原有的 difficulty_ratio 以兼容性
  110. 'difficulty_ratio' => [
  111. '基础' => $distribution['low']['percentage'],
  112. '中等' => $distribution['medium']['percentage'],
  113. '拔高' => $distribution['high']['percentage'],
  114. ],
  115. // 新增:启用难度分布选题标志
  116. 'enable_difficulty_distribution' => true,
  117. 'difficulty_category' => $difficultyCategory,
  118. ]);
  119. Log::info('ExamTypeStrategy: 难度分布应用完成', [
  120. 'category' => $difficultyCategory,
  121. 'distribution' => $distribution,
  122. 'ranges' => $difficultyDistributionConfig['ranges']
  123. ]);
  124. return $enhanced;
  125. }
  126. /**
  127. * 应用难度分布到题目集合
  128. * 这是一个独立的公共方法,供外部调用
  129. *
  130. * @param array $questions 候选题目数组
  131. * @param int $totalQuestions 总题目数
  132. * @param int $difficultyCategory 难度类别 (1-4)
  133. * @param array $filters 其他筛选条件
  134. * @return array 分布后的题目
  135. */
  136. public function applyDifficultyDistributionToQuestions(array $questions, int $totalQuestions, int $difficultyCategory = 1, array $filters = []): array
  137. {
  138. Log::info('ExamTypeStrategy: 应用难度分布到题目集合', [
  139. 'total_questions' => $totalQuestions,
  140. 'difficulty_category' => $difficultyCategory,
  141. 'input_questions' => count($questions)
  142. ]);
  143. // 使用 QuestionLocalService 的独立方法
  144. return $this->questionLocalService->selectQuestionsByDifficultyDistribution(
  145. $questions,
  146. $totalQuestions,
  147. $difficultyCategory,
  148. $filters
  149. );
  150. }
  151. /**
  152. * 根据难度类别计算题目分布
  153. *
  154. * @param int $category 难度类别 (1-4)
  155. * @param int $totalQuestions 总题目数
  156. * @return array 分布配置
  157. */
  158. private function calculateDifficultyDistribution(int $category, int $totalQuestions): array
  159. {
  160. // 标准化:25% 低级,50% 基准,25% 拔高
  161. $lowPercentage = 25;
  162. $mediumPercentage = 50;
  163. $highPercentage = 25;
  164. // 根据难度类别调整分布
  165. switch ($category) {
  166. case 1:
  167. // 基础型:0-0.25占50%,其他占50%
  168. $mediumPercentage = 50; // 0-0.25作为基准
  169. $lowPercentage = 25; // 其他低难度
  170. $highPercentage = 25; // 其他高难度
  171. break;
  172. case 2:
  173. // 进阶型:0.25-0.5占50%,<0.25占25%,>0.5占25%
  174. $mediumPercentage = 50; // 0.25-0.5作为基准
  175. $lowPercentage = 25; // <0.25
  176. $highPercentage = 25; // >0.5
  177. break;
  178. case 3:
  179. // 中等型:0.5-0.75占50%,<0.5占25%,>0.75占25%
  180. $mediumPercentage = 50; // 0.5-0.75作为基准
  181. $lowPercentage = 25; // <0.5
  182. $highPercentage = 25; // >0.75
  183. break;
  184. case 4:
  185. // 拔高型:0.75-1占50%,其他占50%
  186. $mediumPercentage = 50; // 0.75-1作为基准
  187. $lowPercentage = 25; // 其他低难度
  188. $highPercentage = 25; // 其他高难度
  189. break;
  190. }
  191. // 计算题目数量
  192. $lowCount = (int) round($totalQuestions * $lowPercentage / 100);
  193. $mediumCount = (int) round($totalQuestions * $mediumPercentage / 100);
  194. $highCount = $totalQuestions - $lowCount - $mediumCount;
  195. return [
  196. 'low' => [
  197. 'percentage' => $lowPercentage,
  198. 'count' => $lowCount,
  199. 'label' => '低级难度'
  200. ],
  201. 'medium' => [
  202. 'percentage' => $mediumPercentage,
  203. 'count' => $mediumCount,
  204. 'label' => '基准难度'
  205. ],
  206. 'high' => [
  207. 'percentage' => $highPercentage,
  208. 'count' => $highCount,
  209. 'label' => '拔高难度'
  210. ]
  211. ];
  212. }
  213. /**
  214. * 获取难度范围配置
  215. *
  216. * @param int $category 难度类别
  217. * @return array 难度范围配置
  218. */
  219. private function getDifficultyRanges(int $category): array
  220. {
  221. switch ($category) {
  222. case 1:
  223. return [
  224. 'primary' => ['min' => 0.0, 'max' => 0.25, 'percentage' => 50],
  225. 'secondary' => ['min' => 0.25, 'max' => 1.0, 'percentage' => 50],
  226. 'description' => '基础型:0-0.25占比50%,其他占比50%'
  227. ];
  228. case 2:
  229. return [
  230. 'primary' => ['min' => 0.25, 'max' => 0.5, 'percentage' => 50],
  231. 'low' => ['min' => 0.0, 'max' => 0.25, 'percentage' => 25],
  232. 'high' => ['min' => 0.5, 'max' => 1.0, 'percentage' => 25],
  233. 'description' => '进阶型:0.25-0.5占比50%,<0.25占比25%,>0.5占比25%'
  234. ];
  235. case 3:
  236. return [
  237. 'primary' => ['min' => 0.5, 'max' => 0.75, 'percentage' => 50],
  238. 'low' => ['min' => 0.0, 'max' => 0.5, 'percentage' => 25],
  239. 'high' => ['min' => 0.75, 'max' => 1.0, 'percentage' => 25],
  240. 'description' => '中等型:0.5-0.75占比50%,<0.5占比25%,>0.75占比25%'
  241. ];
  242. case 4:
  243. return [
  244. 'primary' => ['min' => 0.75, 'max' => 1.0, 'percentage' => 50],
  245. 'secondary' => ['min' => 0.0, 'max' => 0.75, 'percentage' => 50],
  246. 'description' => '拔高型:0.75-1占比50%,其他占比50%'
  247. ];
  248. default:
  249. return [
  250. 'primary' => ['min' => 0.0, 'max' => 1.0, 'percentage' => 100],
  251. 'description' => '默认:全难度范围'
  252. ];
  253. }
  254. }
  255. /**
  256. * 摸底测试:评估当前水平
  257. */
  258. private function buildDiagnosticParams(array $params): array
  259. {
  260. Log::info('ExamTypeStrategy: 构建摸底测试参数', $params);
  261. $textbookId = $params['textbook_id'] ?? null;
  262. $grade = $params['grade'] ?? null;
  263. $totalQuestions = $params['total_questions'] ?? 20;
  264. if (!$textbookId) {
  265. Log::warning('ExamTypeStrategy: 摸底测试需要 textbook_id 参数');
  266. return $this->buildGeneralParams($params);
  267. }
  268. // 第一步:根据 textbook_id 查询章节
  269. $catalogChapterIds = $this->getTextbookChapterIds($textbookId);
  270. if (empty($catalogChapterIds)) {
  271. Log::warning('ExamTypeStrategy: 未找到课本章节', ['textbook_id' => $textbookId]);
  272. return $this->buildGeneralParams($params);
  273. }
  274. Log::info('ExamTypeStrategy: 获取到课本章节(摸底测试)', [
  275. 'textbook_id' => $textbookId,
  276. 'chapter_count' => count($catalogChapterIds)
  277. ]);
  278. // 第二步:根据章节ID查询知识点关联
  279. $kpCodes = $this->getKnowledgePointsFromChapters($catalogChapterIds, 25);
  280. if (empty($kpCodes)) {
  281. Log::warning('ExamTypeStrategy: 未找到知识点关联', ['textbook_id' => $textbookId]);
  282. return $this->buildGeneralParams($params);
  283. }
  284. Log::info('ExamTypeStrategy: 获取到知识点(摸底测试)', [
  285. 'kp_count' => count($kpCodes),
  286. 'kp_codes' => array_slice($kpCodes, 0, 5)
  287. ]);
  288. // 摸底测试:平衡所有难度,覆盖多个知识点
  289. $enhanced = array_merge($params, [
  290. 'kp_codes' => $kpCodes,
  291. 'textbook_id' => $textbookId,
  292. 'grade' => $grade,
  293. 'catalog_chapter_ids' => $catalogChapterIds,
  294. // 难度配比:相对平衡,基础题稍多
  295. 'difficulty_ratio' => [
  296. '基础' => 40,
  297. '中等' => 40,
  298. '拔高' => 20,
  299. ],
  300. // 题型配比:选择题多一些,便于快速评估
  301. 'question_type_ratio' => [
  302. '选择题' => 50,
  303. '填空题' => 25,
  304. '解答题' => 25,
  305. ],
  306. 'question_category' => 1, // question_category=1 代表摸底题目
  307. 'paper_name' => $params['paper_name'] ?? ('摸底测试_' . now()->format('Ymd_His')),
  308. ]);
  309. Log::info('ExamTypeStrategy: 摸底测试参数构建完成', [
  310. 'textbook_id' => $textbookId,
  311. 'kp_count' => count($kpCodes),
  312. 'total_questions' => $totalQuestions
  313. ]);
  314. return $enhanced;
  315. }
  316. /**
  317. * 错题本 (assembleType=5)
  318. * 根据 paper_ids 数组查询卷子中的错题,组合成新卷子
  319. * 不需要 total_questions 参数
  320. */
  321. private function buildMistakeParams(array $params): array
  322. {
  323. Log::info('ExamTypeStrategy: 构建错题本参数', $params);
  324. $paperIds = $params['paper_ids'] ?? [];
  325. $studentId = $params['student_id'] ?? null;
  326. // 检查是否有 paper_ids 参数
  327. if (empty($paperIds)) {
  328. Log::warning('ExamTypeStrategy: 错题本需要 paper_ids 参数');
  329. return $this->buildGeneralParams($params);
  330. }
  331. Log::info('ExamTypeStrategy: 错题本组卷', [
  332. 'paper_ids' => $paperIds,
  333. 'student_id' => $studentId,
  334. 'paper_count' => count($paperIds)
  335. ]);
  336. // 通过 paper_ids 查询卷子中的错题
  337. $mistakeQuestionIds = $this->getMistakeQuestionsFromPapers($paperIds, $studentId);
  338. if (empty($mistakeQuestionIds)) {
  339. Log::warning('ExamTypeStrategy: 未找到错题', [
  340. 'paper_ids' => $paperIds
  341. ]);
  342. return $this->buildGeneralParams($params);
  343. }
  344. Log::info('ExamTypeStrategy: 获取到错题', [
  345. 'paper_count' => count($paperIds),
  346. 'mistake_count' => count($mistakeQuestionIds),
  347. 'mistake_question_ids' => array_slice($mistakeQuestionIds, 0, 10) // 只记录前10个
  348. ]);
  349. // 获取错题知识点
  350. $mistakeKnowledgePoints = $this->getKnowledgePointsFromQuestions($mistakeQuestionIds);
  351. // 组装增强参数
  352. $mistakeCount = count($mistakeQuestionIds);
  353. $maxQuestions = 50; // 错题本最大题目数限制
  354. // 如果错题超过最大值,截取到最大值
  355. if ($mistakeCount > $maxQuestions) {
  356. Log::warning('ExamTypeStrategy: 错题数量超过最大值限制,已截取', [
  357. 'mistake_count' => $mistakeCount,
  358. 'max_limit' => $maxQuestions,
  359. 'truncated_count' => $maxQuestions
  360. ]);
  361. $mistakeQuestionIds = array_slice($mistakeQuestionIds, 0, $maxQuestions);
  362. $mistakeCount = $maxQuestions;
  363. }
  364. $enhanced = array_merge($params, [
  365. 'mistake_question_ids' => $mistakeQuestionIds,
  366. 'paper_ids' => $paperIds,
  367. 'priority_knowledge_points' => array_values($mistakeKnowledgePoints),
  368. 'paper_name' => $params['paper_name'] ?? ('错题本_' . now()->format('Ymd_His')),
  369. 'total_questions' => $mistakeCount, // 错题本题目数量由实际错题数量决定
  370. // 错题本:保持原有题型配比
  371. 'question_type_ratio' => [
  372. '选择题' => 35,
  373. '填空题' => 30,
  374. '解答题' => 35,
  375. ],
  376. // 错题本不应用难度分布
  377. 'is_mistake_exam' => true,
  378. 'is_paper_based_mistake' => true, // 标记是基于卷子的错题本
  379. 'mistake_count' => $mistakeCount,
  380. 'knowledge_points_count' => count($mistakeKnowledgePoints),
  381. 'max_questions_limit' => $maxQuestions,
  382. ]);
  383. Log::info('ExamTypeStrategy: 错题本参数构建完成', [
  384. 'paper_count' => count($paperIds),
  385. 'mistake_count' => count($mistakeQuestionIds),
  386. 'knowledge_points_count' => count($mistakeKnowledgePoints)
  387. ]);
  388. return $enhanced;
  389. }
  390. /**
  391. * 专项练习:针对特定技能或知识点练习
  392. */
  393. private function buildPracticeParams(array $params): array
  394. {
  395. Log::info('ExamTypeStrategy: 构建专项练习参数', $params);
  396. $studentId = $params['student_id'] ?? null;
  397. $practiceOptions = $params['practice_options'] ?? [];
  398. $weaknessThreshold = $practiceOptions['weakness_threshold'] ?? 0.7;
  399. $intensity = $practiceOptions['intensity'] ?? 'medium';
  400. $focusWeaknesses = $practiceOptions['focus_weaknesses'] ?? true;
  401. // 根据强度调整难度配比
  402. $difficultyRatio = match($intensity) {
  403. 'low' => [
  404. '基础' => 60,
  405. '中等' => 35,
  406. '拔高' => 5,
  407. ],
  408. 'medium' => [
  409. '基础' => 45,
  410. '中等' => 40,
  411. '拔高' => 15,
  412. ],
  413. 'high' => [
  414. '基础' => 30,
  415. '中等' => 45,
  416. '拔高' => 25,
  417. ],
  418. default => [
  419. '基础' => 45,
  420. '中等' => 40,
  421. '拔高' => 15,
  422. ]
  423. };
  424. // 获取学生薄弱点
  425. $weaknessFilter = [];
  426. if ($studentId && $focusWeaknesses) {
  427. $weaknessFilter = $this->getStudentWeaknesses($studentId, $weaknessThreshold);
  428. Log::info('ExamTypeStrategy: 获取到学生薄弱点', [
  429. 'student_id' => $studentId,
  430. 'weakness_threshold' => $weaknessThreshold,
  431. 'weakness_count' => count($weaknessFilter)
  432. ]);
  433. }
  434. // 优先使用薄弱点知识点,如果没有则使用用户选择的知识点
  435. $kpCodes = $params['kp_codes'] ?? [];
  436. if ($studentId && empty($kpCodes) && !empty($weaknessFilter)) {
  437. $kpCodes = array_column($weaknessFilter, 'kp_code');
  438. Log::info('ExamTypeStrategy: 使用薄弱点作为知识点', [
  439. 'kp_codes' => $kpCodes
  440. ]);
  441. }
  442. $enhanced = array_merge($params, [
  443. 'difficulty_ratio' => $difficultyRatio,
  444. 'kp_codes' => $kpCodes,
  445. // 专项练习更注重题型覆盖
  446. 'question_type_ratio' => [
  447. '选择题' => 40,
  448. '填空题' => 30,
  449. '解答题' => 30,
  450. ],
  451. 'paper_name' => $params['paper_name'] ?? ('专项练习_' . now()->format('Ymd_His')),
  452. // 标记这是专项练习,用于后续处理
  453. 'is_practice_exam' => true,
  454. 'weakness_filter' => $weaknessFilter,
  455. ]);
  456. Log::info('ExamTypeStrategy: 专项练习参数构建完成', [
  457. 'intensity' => $intensity,
  458. 'difficulty_ratio' => $enhanced['difficulty_ratio'],
  459. 'kp_codes_count' => count($enhanced['kp_codes']),
  460. 'weakness_count' => count($weaknessFilter)
  461. ]);
  462. return $enhanced;
  463. }
  464. /**
  465. * 教材同步:按教材章节出题
  466. */
  467. private function buildTextbookParams(array $params): array
  468. {
  469. Log::info('ExamTypeStrategy: 构建教材同步参数', $params);
  470. // 教材同步:按章节顺序,难度递增
  471. $textbookOptions = $params['textbook_options'] ?? [];
  472. $enhanced = array_merge($params, [
  473. // 教材同步:基础和中等题为主
  474. 'difficulty_ratio' => [
  475. '基础' => 50,
  476. '中等' => 40,
  477. '拔高' => 10,
  478. ],
  479. 'question_type_ratio' => [
  480. '选择题' => 40,
  481. '填空题' => 30,
  482. '解答题' => 30,
  483. ],
  484. 'paper_name' => $params['paper_name'] ?? ('教材同步_' . now()->format('Ymd_His')),
  485. 'textbook_options' => $textbookOptions,
  486. ]);
  487. return $enhanced;
  488. }
  489. /**
  490. * 知识点专练:单个或少量知识点深练
  491. */
  492. private function buildKnowledgeParams(array $params): array
  493. {
  494. Log::info('ExamTypeStrategy: 构建知识点专练参数', $params);
  495. // 知识点专练:深度挖掘,多角度考查
  496. $knowledgeOptions = $params['knowledge_options'] ?? [];
  497. $enhanced = array_merge($params, [
  498. // 知识点专练:难度分布更均匀
  499. 'difficulty_ratio' => [
  500. '基础' => 35,
  501. '中等' => 45,
  502. '拔高' => 20,
  503. ],
  504. 'question_type_ratio' => [
  505. '选择题' => 30,
  506. '填空题' => 35,
  507. '解答题' => 35,
  508. ],
  509. 'paper_name' => $params['paper_name'] ?? ('知识点专练_' . now()->format('Ymd_His')),
  510. 'knowledge_options' => $knowledgeOptions,
  511. ]);
  512. return $enhanced;
  513. }
  514. /**
  515. * 按知识点组卷:根据指定知识点数组智能选题
  516. * 优先级策略:
  517. * 1. 直接关联知识点题目(来自输入数组)
  518. * 2. 相同知识点其他题目
  519. * 3. 子知识点题目(下探1层)
  520. * 4. 薄弱点题目比例调整
  521. * 5. 子知识点题目(下探2层)
  522. */
  523. private function buildKnowledgePointsParams(array $params): array
  524. {
  525. Log::info('ExamTypeStrategy: 构建按知识点组卷参数', $params);
  526. $studentId = $params['student_id'] ?? null;
  527. $totalQuestions = $params['total_questions'] ?? 20;
  528. $knowledgePointsOptions = $params['knowledge_points_options'] ?? [];
  529. $weaknessThreshold = $knowledgePointsOptions['weakness_threshold'] ?? 0.7;
  530. $focusWeaknesses = $knowledgePointsOptions['focus_weaknesses'] ?? true;
  531. $intensity = $knowledgePointsOptions['intensity'] ?? 'medium';
  532. // 获取用户指定的知识点数组
  533. $targetKnowledgePoints = $params['kp_codes'] ?? [];
  534. if (empty($targetKnowledgePoints)) {
  535. Log::warning('ExamTypeStrategy: 未指定知识点数组,使用默认策略');
  536. return $this->buildGeneralParams($params);
  537. }
  538. Log::info('ExamTypeStrategy: 目标知识点数组', [
  539. 'target_knowledge_points' => $targetKnowledgePoints,
  540. 'count' => count($targetKnowledgePoints)
  541. ]);
  542. // 根据强度调整难度配比
  543. $difficultyRatio = match($intensity) {
  544. 'low' => [
  545. '基础' => 60,
  546. '中等' => 35,
  547. '拔高' => 5,
  548. ],
  549. 'medium' => [
  550. '基础' => 45,
  551. '中等' => 40,
  552. '拔高' => 15,
  553. ],
  554. 'high' => [
  555. '基础' => 30,
  556. '中等' => 45,
  557. '拔高' => 25,
  558. ],
  559. default => [
  560. '基础' => 45,
  561. '中等' => 40,
  562. '拔高' => 15,
  563. ]
  564. };
  565. // 获取学生薄弱点(用于判断目标知识点是否为薄弱点)
  566. $weaknessFilter = [];
  567. if ($studentId && $focusWeaknesses) {
  568. $weaknessFilter = $this->getStudentWeaknesses($studentId, $weaknessThreshold);
  569. Log::info('ExamTypeStrategy: 获取到学生薄弱点', [
  570. 'student_id' => $studentId,
  571. 'weakness_threshold' => $weaknessThreshold,
  572. 'weakness_count' => count($weaknessFilter)
  573. ]);
  574. }
  575. // 检查目标知识点中哪些是薄弱点
  576. $weaknessKpCodes = array_column($weaknessFilter, 'kp_code');
  577. $targetWeaknessKps = array_intersect($targetKnowledgePoints, $weaknessKpCodes);
  578. Log::info('ExamTypeStrategy: 目标知识点中的薄弱点', [
  579. 'target_weakness_kps' => $targetWeaknessKps,
  580. 'weakness_count' => count($targetWeaknessKps)
  581. ]);
  582. // 使用 QuestionExpansionService 按知识点优先级扩展题目
  583. // 修改 expandQuestions 支持直接传入知识点数组
  584. $questionStrategy = $this->questionExpansionService->expandQuestionsByKnowledgePoints(
  585. $params,
  586. $studentId,
  587. $targetKnowledgePoints,
  588. $weaknessFilter,
  589. $totalQuestions
  590. );
  591. // 获取扩展统计
  592. $expansionStats = $this->questionExpansionService->getExpansionStats($questionStrategy);
  593. $enhanced = array_merge($params, [
  594. 'difficulty_ratio' => $difficultyRatio,
  595. 'kp_codes' => $targetKnowledgePoints, // 确保使用目标知识点
  596. 'mistake_question_ids' => $questionStrategy['mistake_question_ids'] ?? [],
  597. // 优先级知识点:目标知识点 + 薄弱点
  598. 'priority_knowledge_points' => array_merge(
  599. array_values($targetKnowledgePoints),
  600. array_column($weaknessFilter, 'kp_code')
  601. ),
  602. 'question_type_ratio' => [
  603. '选择题' => 35,
  604. '填空题' => 30,
  605. '解答题' => 35,
  606. ],
  607. 'paper_name' => $params['paper_name'] ?? ('知识点组卷_' . now()->format('Ymd_His')),
  608. // 标记这是按知识点组卷,用于后续处理
  609. 'is_knowledge_points_exam' => true,
  610. 'weakness_filter' => $weaknessFilter,
  611. // 目标知识点中的薄弱点(用于调整题目数量)
  612. 'target_weakness_kps' => array_values($targetWeaknessKps),
  613. // 题目扩展统计
  614. 'question_expansion_stats' => $expansionStats
  615. ]);
  616. Log::info('ExamTypeStrategy: 按知识点组卷参数构建完成', [
  617. 'intensity' => $intensity,
  618. 'target_knowledge_points_count' => count($targetKnowledgePoints),
  619. 'target_weakness_kps_count' => count($targetWeaknessKps),
  620. 'mistake_question_ids_count' => count($enhanced['mistake_question_ids']),
  621. 'priority_knowledge_points_count' => count($enhanced['priority_knowledge_points']),
  622. 'question_expansion_stats' => $enhanced['question_expansion_stats'],
  623. 'weakness_count' => count($weaknessFilter)
  624. ]);
  625. return $enhanced;
  626. }
  627. /**
  628. * 为摸底测试扩展知识点(确保覆盖全面)
  629. */
  630. private function expandKpCodesForDiagnostic(array $kpCodes): array
  631. {
  632. if (!empty($kpCodes)) {
  633. return $kpCodes;
  634. }
  635. // 如果没有指定知识点,返回一些通用的数学知识点
  636. return [
  637. '一元二次方程',
  638. '二次函数',
  639. '旋转',
  640. '圆',
  641. '概率初步',
  642. ];
  643. }
  644. /**
  645. * 获取学生薄弱点
  646. */
  647. private function getStudentWeaknesses(string $studentId, float $threshold): array
  648. {
  649. try {
  650. // 使用 StudentKnowledgeMastery 模型获取掌握度低于阈值的知识点
  651. $weaknessRecords = StudentKnowledgeMastery::forStudent($studentId)
  652. ->weaknesses($threshold)
  653. ->orderByMastery('asc')
  654. ->limit(20)
  655. ->with('knowledgePoint') // 预加载知识点信息
  656. ->get();
  657. // 转换为统一格式
  658. return $weaknessRecords->map(function ($record) {
  659. return [
  660. 'kp_code' => $record->kp_code,
  661. 'kp_name' => $record->knowledgePoint->name ?? $record->kp_code,
  662. 'mastery' => (float) ($record->mastery_level ?? 0),
  663. 'attempts' => (int) ($record->total_attempts ?? 0),
  664. 'correct' => (int) ($record->correct_attempts ?? 0),
  665. 'incorrect' => (int) ($record->incorrect_attempts ?? 0),
  666. 'confidence' => (float) ($record->confidence_level ?? 0),
  667. 'trend' => $record->mastery_trend ?? 'stable',
  668. ];
  669. })->toArray();
  670. } catch (\Exception $e) {
  671. Log::error('ExamTypeStrategy: 获取学生薄弱点失败', [
  672. 'student_id' => $studentId,
  673. 'threshold' => $threshold,
  674. 'error' => $e->getMessage()
  675. ]);
  676. return [];
  677. }
  678. }
  679. /**
  680. * 智能组卷 (assembleType=1)
  681. * 根据 textbook_id 查询章节,获取知识点,然后组卷
  682. * 增加年级概念选题逻辑
  683. */
  684. private function buildIntelligentAssembleParams(array $params): array
  685. {
  686. Log::info('ExamTypeStrategy: 构建智能组卷参数', $params);
  687. $textbookId = $params['textbook_id'] ?? null;
  688. $grade = $params['grade'] ?? null; // 年级信息
  689. $totalQuestions = $params['total_questions'] ?? 20;
  690. if (!$textbookId) {
  691. Log::warning('ExamTypeStrategy: 智能组卷需要 textbook_id 参数');
  692. return $this->buildGeneralParams($params);
  693. }
  694. // 第一步:根据 textbook_id 查询章节
  695. $catalogChapterIds = $this->getTextbookChapterIds($textbookId);
  696. if (empty($catalogChapterIds)) {
  697. Log::warning('ExamTypeStrategy: 未找到课本章节', ['textbook_id' => $textbookId]);
  698. return $this->buildGeneralParams($params);
  699. }
  700. Log::info('ExamTypeStrategy: 获取到课本章节', [
  701. 'textbook_id' => $textbookId,
  702. 'chapter_count' => count($catalogChapterIds)
  703. ]);
  704. // 第二步:根据章节ID查询知识点关联
  705. $kpCodes = $this->getKnowledgePointsFromChapters($catalogChapterIds, 25);
  706. if (empty($kpCodes)) {
  707. Log::warning('ExamTypeStrategy: 未找到知识点关联', [
  708. 'textbook_id' => $textbookId,
  709. 'chapter_ids' => $catalogChapterIds
  710. ]);
  711. return $this->buildGeneralParams($params);
  712. }
  713. Log::info('ExamTypeStrategy: 获取到知识点', [
  714. 'kp_count' => count($kpCodes),
  715. 'kp_codes' => array_slice($kpCodes, 0, 5) // 只记录前5个
  716. ]);
  717. // 组装增强参数
  718. $enhanced = array_merge($params, [
  719. 'kp_codes' => $kpCodes,
  720. 'textbook_id' => $textbookId,
  721. 'grade' => $grade,
  722. 'catalog_chapter_ids' => $catalogChapterIds,
  723. 'paper_name' => $params['paper_name'] ?? ('智能组卷_' . now()->format('Ymd_His')),
  724. // 智能组卷:平衡的题型和难度配比
  725. 'question_type_ratio' => [
  726. '选择题' => 40,
  727. '填空题' => 30,
  728. '解答题' => 30,
  729. ],
  730. 'difficulty_ratio' => [
  731. '基础' => 25,
  732. '中等' => 50,
  733. '拔高' => 25,
  734. ],
  735. 'question_category' => 0, // question_category=0 代表普通题目(智能组卷)
  736. 'is_intelligent_assemble' => true,
  737. ]);
  738. Log::info('ExamTypeStrategy: 智能组卷参数构建完成', [
  739. 'textbook_id' => $textbookId,
  740. 'grade' => $grade,
  741. 'kp_count' => count($kpCodes),
  742. 'total_questions' => $totalQuestions
  743. ]);
  744. return $enhanced;
  745. }
  746. /**
  747. * 知识点组卷 (assembleType=2)
  748. * 直接根据 kp_code_list 查询题目,排除已做过的题目
  749. */
  750. private function buildKnowledgePointAssembleParams(array $params): array
  751. {
  752. Log::info('ExamTypeStrategy: 构建知识点组卷参数', $params);
  753. $kpCodeList = $params['kp_code_list'] ?? [];
  754. $studentId = $params['student_id'] ?? null;
  755. $totalQuestions = $params['total_questions'] ?? 20;
  756. if (empty($kpCodeList)) {
  757. Log::warning('ExamTypeStrategy: 知识点组卷需要 kp_code_list 参数');
  758. return $this->buildGeneralParams($params);
  759. }
  760. Log::info('ExamTypeStrategy: 知识点组卷', [
  761. 'kp_code_list' => $kpCodeList,
  762. 'student_id' => $studentId,
  763. 'total_questions' => $totalQuestions
  764. ]);
  765. // 如果有学生ID,获取已做过的题目ID列表(用于排除)
  766. $answeredQuestionIds = [];
  767. if ($studentId) {
  768. $answeredQuestionIds = $this->getStudentAnsweredQuestionIds($studentId, $kpCodeList);
  769. Log::info('ExamTypeStrategy: 获取学生已答题目', [
  770. 'student_id' => $studentId,
  771. 'answered_count' => count($answeredQuestionIds)
  772. ]);
  773. }
  774. // 组装增强参数
  775. $enhanced = array_merge($params, [
  776. 'kp_codes' => $kpCodeList,
  777. 'exclude_question_ids' => $answeredQuestionIds,
  778. 'paper_name' => $params['paper_name'] ?? ('知识点组卷_' . now()->format('Ymd_His')),
  779. // 知识点组卷:注重题型平衡
  780. 'question_type_ratio' => [
  781. '选择题' => 35,
  782. '填空题' => 30,
  783. '解答题' => 35,
  784. ],
  785. 'difficulty_ratio' => [
  786. '基础' => 25,
  787. '中等' => 50,
  788. '拔高' => 25,
  789. ],
  790. 'question_category' => 0, // question_category=0 代表普通题目
  791. 'is_knowledge_point_assemble' => true,
  792. ]);
  793. Log::info('ExamTypeStrategy: 知识点组卷参数构建完成', [
  794. 'kp_count' => count($kpCodeList),
  795. 'exclude_count' => count($answeredQuestionIds),
  796. 'total_questions' => $totalQuestions
  797. ]);
  798. return $enhanced;
  799. }
  800. /**
  801. * 教材组卷 (assembleType=3)
  802. * 根据 chapter_id_list 查询课本章节,获取知识点,然后组卷
  803. */
  804. private function buildTextbookAssembleParams(array $params): array
  805. {
  806. Log::info('ExamTypeStrategy: 构建教材组卷参数', $params);
  807. $chapterIdList = $params['chapter_id_list'] ?? [];
  808. $studentId = $params['student_id'] ?? null;
  809. $totalQuestions = $params['total_questions'] ?? 20;
  810. if (empty($chapterIdList)) {
  811. Log::warning('ExamTypeStrategy: 教材组卷需要 chapter_id_list 参数');
  812. return $this->buildGeneralParams($params);
  813. }
  814. Log::info('ExamTypeStrategy: 教材组卷', [
  815. 'chapter_id_list' => $chapterIdList,
  816. 'student_id' => $studentId,
  817. 'total_questions' => $totalQuestions
  818. ]);
  819. // 第一步:根据章节ID查询知识点关联
  820. $kpCodes = $this->getKnowledgePointsFromChapters($chapterIdList);
  821. if (empty($kpCodes)) {
  822. Log::warning('ExamTypeStrategy: 未找到章节知识点关联', [
  823. 'chapter_id_list' => $chapterIdList
  824. ]);
  825. return $this->buildGeneralParams($params);
  826. }
  827. Log::info('ExamTypeStrategy: 获取章节知识点', [
  828. 'kp_count' => count($kpCodes),
  829. 'kp_codes' => array_slice($kpCodes, 0, 5)
  830. ]);
  831. // 第二步:如果有学生ID,获取已做过的题目ID列表(用于排除)
  832. $answeredQuestionIds = [];
  833. if ($studentId) {
  834. $answeredQuestionIds = $this->getStudentAnsweredQuestionIds($studentId, $kpCodes);
  835. Log::info('ExamTypeStrategy: 获取学生已答题目', [
  836. 'student_id' => $studentId,
  837. 'answered_count' => count($answeredQuestionIds)
  838. ]);
  839. }
  840. // 组装增强参数
  841. $enhanced = array_merge($params, [
  842. 'kp_codes' => $kpCodes,
  843. 'chapter_id_list' => $chapterIdList,
  844. 'exclude_question_ids' => $answeredQuestionIds,
  845. 'paper_name' => $params['paper_name'] ?? ('教材组卷_' . now()->format('Ymd_His')),
  846. // 教材组卷:按教材特点分配题型
  847. 'question_type_ratio' => [
  848. '选择题' => 40,
  849. '填空题' => 30,
  850. '解答题' => 30,
  851. ],
  852. 'difficulty_ratio' => [
  853. '基础' => 25,
  854. '中等' => 50,
  855. '拔高' => 25,
  856. ],
  857. 'question_category' => 0, // question_category=0 代表普通题目
  858. 'is_textbook_assemble' => true,
  859. ]);
  860. Log::info('ExamTypeStrategy: 教材组卷参数构建完成', [
  861. 'chapter_count' => count($chapterIdList),
  862. 'kp_count' => count($kpCodes),
  863. 'exclude_count' => count($answeredQuestionIds),
  864. 'total_questions' => $totalQuestions
  865. ]);
  866. return $enhanced;
  867. }
  868. /**
  869. * 根据课本ID获取章节ID列表
  870. */
  871. private function getTextbookChapterIds(int $textbookId): array
  872. {
  873. try {
  874. // 查询 text_book_catalog_nodes 表
  875. $chapterIds = DB::table('textbook_catalog_nodes')
  876. ->where('textbook_id', $textbookId)
  877. ->where('node_type', 'section') // nodeType='section'
  878. ->orderBy('sort_order')
  879. ->pluck('id')
  880. ->toArray();
  881. Log::debug('ExamTypeStrategy: 查询课本章节ID', [
  882. 'textbook_id' => $textbookId,
  883. 'found_count' => count($chapterIds)
  884. ]);
  885. return $chapterIds;
  886. } catch (\Exception $e) {
  887. Log::error('ExamTypeStrategy: 查询课本章节ID失败', [
  888. 'textbook_id' => $textbookId,
  889. 'error' => $e->getMessage()
  890. ]);
  891. return [];
  892. }
  893. }
  894. /**
  895. * 根据章节ID列表获取知识点代码列表(均等抽样版本)
  896. * 使用"知识点均等抽样"算法,确保覆盖全书章节
  897. *
  898. * @param array $chapterIds 章节ID列表
  899. * @param int $limit 目标题目数量(默认25)
  900. * @return array 抽样后的知识点代码列表
  901. */
  902. private function getKnowledgePointsFromChapters(array $chapterIds, int $limit = 25): array
  903. {
  904. try {
  905. // 如果章节数较少,使用原有逻辑
  906. if (count($chapterIds) <= 5) {
  907. Log::info('ExamTypeStrategy: 章节数较少,使用原有逻辑', [
  908. 'chapter_count' => count($chapterIds)
  909. ]);
  910. return $this->getKnowledgePointsFromChaptersLegacy($chapterIds, $limit);
  911. }
  912. // ========== 步骤1: 构建全量有序池 ==========
  913. // 查询所有知识点,按章节顺序排列,去重后得到有序数组
  914. $allKpData = DB::table('textbook_chapter_knowledge_relation as tckr')
  915. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  916. ->whereIn('tckr.catalog_chapter_id', $chapterIds)
  917. ->select('tckr.kp_code', 'tcn.sort_order', 'tcn.id as chapter_id', 'tcn.title as chapter_title')
  918. ->orderBy('tcn.sort_order', 'asc')
  919. ->orderBy('tckr.kp_code', 'asc')
  920. ->get();
  921. // 去重并构建有序数组
  922. $allKpCodes = [];
  923. $chapterInfo = [];
  924. foreach ($allKpData as $row) {
  925. if (!in_array($row->kp_code, $allKpCodes)) {
  926. $allKpCodes[] = $row->kp_code;
  927. $chapterInfo[$row->kp_code] = [
  928. 'chapter_id' => $row->chapter_id,
  929. 'chapter_title' => $row->chapter_title,
  930. 'sort_order' => $row->sort_order
  931. ];
  932. }
  933. }
  934. $totalKps = count($allKpCodes);
  935. Log::info('ExamTypeStrategy: 构建全量有序池完成', [
  936. 'chapter_count' => count($chapterIds),
  937. 'total_knowledge_points' => $totalKps,
  938. 'target_questions' => $limit
  939. ]);
  940. // ========== 步骤2: 计算抽样步长 ==========
  941. $step = $totalKps > 0 ? $totalKps / $limit : 1;
  942. Log::info('ExamTypeStrategy: 计算抽样步长', [
  943. 'step' => $step
  944. ]);
  945. // ========== 步骤3: 等距取样 ==========
  946. $selectedKps = [];
  947. $selectedCount = 0;
  948. $currentIndex = 0;
  949. while ($selectedCount < $limit && $selectedCount < $totalKps) {
  950. $index = (int) floor($currentIndex);
  951. if ($index < $totalKps && isset($allKpCodes[$index])) {
  952. $kpCode = $allKpCodes[$index];
  953. if (!in_array($kpCode, $selectedKps)) {
  954. $selectedKps[] = $kpCode;
  955. $selectedCount++;
  956. }
  957. }
  958. $currentIndex += $step;
  959. }
  960. // 如果数量不足,循环取样
  961. if (count($selectedKps) < $limit && $totalKps > 0) {
  962. Log::info('ExamTypeStrategy: 第一次抽样不足,进行循环取样', [
  963. 'selected_count' => count($selectedKps),
  964. 'target_count' => $limit
  965. ]);
  966. $needed = $limit - count($selectedKps);
  967. $startIndex = 0;
  968. for ($i = 0; $i < $needed && count($selectedKps) < $limit; $i++) {
  969. $index = ($startIndex + $i) % $totalKps;
  970. $kpCode = $allKpCodes[$index];
  971. if (!in_array($kpCode, $selectedKps)) {
  972. $selectedKps[] = $kpCode;
  973. }
  974. }
  975. }
  976. // ========== 步骤4: 记录抽样统计 ==========
  977. $chapterDistribution = [];
  978. foreach ($selectedKps as $kpCode) {
  979. if (isset($chapterInfo[$kpCode])) {
  980. $chapterId = $chapterInfo[$kpCode]['chapter_id'];
  981. if (!isset($chapterDistribution[$chapterId])) {
  982. $chapterDistribution[$chapterId] = [
  983. 'count' => 0,
  984. 'title' => $chapterInfo[$kpCode]['chapter_title']
  985. ];
  986. }
  987. $chapterDistribution[$chapterId]['count']++;
  988. }
  989. }
  990. Log::info('ExamTypeStrategy: 等距抽样完成', [
  991. 'total_kps' => $totalKps,
  992. 'selected_kps' => count($selectedKps),
  993. 'step' => $step,
  994. 'chapter_distribution' => $chapterDistribution,
  995. 'sample_kp_codes' => array_slice($selectedKps, 0, 10)
  996. ]);
  997. return array_filter($selectedKps);
  998. } catch (\Exception $e) {
  999. Log::error('ExamTypeStrategy: 均等抽样获取章节知识点失败,使用原有逻辑', [
  1000. 'chapter_ids' => $chapterIds,
  1001. 'error' => $e->getMessage()
  1002. ]);
  1003. // 失败时回退到原有逻辑
  1004. return $this->getKnowledgePointsFromChaptersLegacy($chapterIds, $limit);
  1005. }
  1006. }
  1007. /**
  1008. * 原有逻辑(保留作为回退方案)
  1009. */
  1010. private function getKnowledgePointsFromChaptersLegacy(array $chapterIds, int $limit = 25): array
  1011. {
  1012. try {
  1013. // 查询 textbook_chapter_knowledge_relation 表(修复:添加排序避免数据偏向)
  1014. $kpCodes = DB::table('textbook_chapter_knowledge_relation as tckr')
  1015. ->leftJoin('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  1016. ->whereIn('tckr.catalog_chapter_id', $chapterIds)
  1017. ->orderBy('tcn.sort_order', 'asc')
  1018. ->orderBy('tckr.kp_code', 'asc')
  1019. ->limit($limit)
  1020. ->distinct()
  1021. ->pluck('tckr.kp_code')
  1022. ->toArray();
  1023. Log::debug('ExamTypeStrategy: 查询章节知识点(原有逻辑)', [
  1024. 'chapter_count' => count($chapterIds),
  1025. 'found_kp_count' => count($kpCodes)
  1026. ]);
  1027. return array_filter($kpCodes); // 移除空值
  1028. } catch (\Exception $e) {
  1029. Log::error('ExamTypeStrategy: 查询章节知识点失败', [
  1030. 'chapter_ids' => $chapterIds,
  1031. 'error' => $e->getMessage()
  1032. ]);
  1033. return [];
  1034. }
  1035. }
  1036. /**
  1037. * 获取学生已答题目ID列表(用于排除)
  1038. */
  1039. private function getStudentAnsweredQuestionIds(string $studentId, array $kpCodes): array
  1040. {
  1041. try {
  1042. // 查询 student_answer_questions 表
  1043. $questionIds = DB::table('student_answer_questions')
  1044. ->where('student_id', $studentId)
  1045. ->whereIn('kp_code', $kpCodes)
  1046. ->distinct()
  1047. ->pluck('question_id')
  1048. ->toArray();
  1049. Log::debug('ExamTypeStrategy: 查询学生已答题目', [
  1050. 'student_id' => $studentId,
  1051. 'kp_count' => count($kpCodes),
  1052. 'answered_count' => count($questionIds)
  1053. ]);
  1054. return array_filter($questionIds); // 移除空值
  1055. } catch (\Exception $e) {
  1056. Log::error('ExamTypeStrategy: 查询学生已答题目失败', [
  1057. 'student_id' => $studentId,
  1058. 'error' => $e->getMessage()
  1059. ]);
  1060. return [];
  1061. }
  1062. }
  1063. /**
  1064. * 通过卷子ID列表查询错题
  1065. * 注意:paper_ids 使用的是 papers 表中的 paper_id 字段,不是 id 字段
  1066. * 错题数据从 mistake_records 表中获取,该表已包含 paper_id 字段
  1067. * 注意:不按学生ID过滤,因为卷子可能包含其他同学的错题,需要收集所有错题
  1068. */
  1069. private function getMistakeQuestionsFromPapers(array $paperIds, ?string $studentId = null): array
  1070. {
  1071. try {
  1072. // 使用 Eloquent 模型查询,从 mistake_records 表中获取错题记录
  1073. // 不按 student_id 过滤,因为要收集所有学生的错题
  1074. $mistakeRecords = MistakeRecord::query()
  1075. ->whereIn('paper_id', $paperIds)
  1076. ->get();
  1077. if ($mistakeRecords->isEmpty()) {
  1078. Log::warning('ExamTypeStrategy: 卷子中未找到错题记录', [
  1079. 'paper_ids' => $paperIds
  1080. ]);
  1081. return [];
  1082. }
  1083. // 收集所有错题的 question_id
  1084. $questionIds = $mistakeRecords->pluck('question_id')
  1085. ->filter()
  1086. ->unique()
  1087. ->values()
  1088. ->toArray();
  1089. Log::info('ExamTypeStrategy: 查询卷子错题完成', [
  1090. 'paper_count' => count($paperIds),
  1091. 'paper_ids_input' => $paperIds,
  1092. 'mistake_record_count' => $mistakeRecords->count(),
  1093. 'unique_question_count' => count($questionIds),
  1094. 'question_ids' => array_slice($questionIds, 0, 20), // 最多记录20个ID
  1095. 'per_paper_stats' => $mistakeRecords->groupBy('paper_id')->map->count()->toArray()
  1096. ]);
  1097. return array_filter($questionIds);
  1098. } catch (\Exception $e) {
  1099. Log::error('ExamTypeStrategy: 查询卷子错题失败', [
  1100. 'paper_ids' => $paperIds,
  1101. 'error' => $e->getMessage()
  1102. ]);
  1103. return [];
  1104. }
  1105. }
  1106. /**
  1107. * 通过题目ID列表获取知识点代码列表
  1108. */
  1109. private function getKnowledgePointsFromQuestions(array $questionIds): array
  1110. {
  1111. try {
  1112. // 使用 Eloquent 模型查询,获取题目的知识点
  1113. $questions = Question::whereIn('id', $questionIds)
  1114. ->whereNotNull('kp_code')
  1115. ->where('kp_code', '!=', '')
  1116. ->distinct()
  1117. ->pluck('kp_code')
  1118. ->toArray();
  1119. Log::debug('ExamTypeStrategy: 查询题目知识点', [
  1120. 'question_count' => count($questionIds),
  1121. 'kp_count' => count($questions)
  1122. ]);
  1123. return array_filter($questions);
  1124. } catch (\Exception $e) {
  1125. Log::error('ExamTypeStrategy: 查询题目知识点失败', [
  1126. 'question_ids' => array_slice($questionIds, 0, 10), // 只记录前10个
  1127. 'error' => $e->getMessage()
  1128. ]);
  1129. return [];
  1130. }
  1131. }
  1132. }