QuestionExpansionService.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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\Question;
  7. use App\Models\KnowledgePoint;
  8. class QuestionExpansionService
  9. {
  10. /**
  11. * 按优先级扩展题目数量
  12. * 优先级策略:
  13. * 1. 优先使用错题记录的题目
  14. * 2. 错题相同的知识点的其他题目
  15. * 3. 相同知识点的子知识点的题目
  16. * 4. 学生薄弱知识点相关题目
  17. * 5. 薄弱知识点的子知识点的题目
  18. */
  19. public function expandQuestions(array $baseParams, ?string $studentId, array $weaknessFilter, int $totalQuestions): array
  20. {
  21. Log::info('QuestionExpansionService: 开始题目扩展', [
  22. 'student_id' => $studentId,
  23. 'total_needed' => $totalQuestions,
  24. 'weakness_count' => count($weaknessFilter)
  25. ]);
  26. $strategy = [
  27. 'mistake_ids' => $baseParams['mistake_ids'] ?? [],
  28. 'mistake_question_ids' => $baseParams['mistake_question_ids'] ?? [],
  29. 'step2_count' => 0,
  30. 'step3_count' => 0,
  31. 'step4_count' => 0,
  32. 'step5_count' => 0,
  33. 'expansion_details' => []
  34. ];
  35. $includeMistakes = ($baseParams['mistake_options']['review_mistakes'] ?? true) && $studentId;
  36. if (!$includeMistakes) {
  37. Log::info('QuestionExpansionService: 未开启错题回顾,跳过扩展');
  38. return $strategy;
  39. }
  40. // Step 1: 获取学生历史错题(优先级:最高)
  41. // 直接使用学生历史错题,学习价值最高
  42. if (empty($strategy['mistake_question_ids'])) {
  43. $studentMistakes = $this->getStudentMistakes($studentId);
  44. $strategy['mistake_question_ids'] = array_values(array_unique(array_column($studentMistakes, 'question_id')));
  45. $strategy['expansion_details']['step1_mistakes'] = count($strategy['mistake_question_ids']);
  46. Log::info('QuestionExpansionService: Step1 - 获取历史错题', [
  47. 'count' => count($strategy['mistake_question_ids']),
  48. 'mistake_ids' => $strategy['mistake_question_ids']
  49. ]);
  50. }
  51. // 如果错题数量已满足需求,直接返回
  52. if (count($strategy['mistake_question_ids']) >= $totalQuestions) {
  53. Log::info('QuestionExpansionService: Step1 - 错题数量已满足需求', [
  54. 'total_needed' => $totalQuestions,
  55. 'mistake_count' => count($strategy['mistake_question_ids'])
  56. ]);
  57. return $strategy;
  58. }
  59. // Step 2: 错题相同的知识点的其他题目(优先级:高)
  60. // 强化特定知识点的掌握,题目类型多样化
  61. $remaining = $totalQuestions - count($strategy['mistake_question_ids']);
  62. $mistakeKps = $this->getMistakeKnowledgePoints($studentId, $strategy['mistake_question_ids']);
  63. if (!empty($mistakeKps) && $remaining > 0) {
  64. $step2Questions = $this->getQuestionsByKnowledgePoints($mistakeKps, $strategy['mistake_question_ids'], $remaining);
  65. $strategy['mistake_question_ids'] = array_merge($strategy['mistake_question_ids'], $step2Questions);
  66. $strategy['step2_count'] = count($step2Questions);
  67. $strategy['expansion_details']['step2_same_kp'] = [
  68. 'knowledge_points' => $mistakeKps,
  69. 'added_count' => count($step2Questions)
  70. ];
  71. Log::info('QuestionExpansionService: Step2 - 获取同知识点其他题目', [
  72. 'knowledge_points' => $mistakeKps,
  73. 'added_count' => count($step2Questions),
  74. 'total_count' => count($strategy['mistake_question_ids'])
  75. ]);
  76. }
  77. // 如果数量仍不足,继续扩展
  78. $remaining = $totalQuestions - count($strategy['mistake_question_ids']);
  79. if ($remaining <= 0) {
  80. return $strategy;
  81. }
  82. // Step 3: 相同知识点的子知识点的题目(优先级:中高)
  83. // 深入知识点的细分类别,实现精准练习
  84. if (!empty($mistakeKps) && $remaining > 0) {
  85. $childKps = $this->getChildKnowledgePoints($mistakeKps);
  86. if (!empty($childKps)) {
  87. $step3Questions = $this->getQuestionsByKnowledgePoints($childKps, $strategy['mistake_question_ids'], $remaining);
  88. $strategy['mistake_question_ids'] = array_merge($strategy['mistake_question_ids'], $step3Questions);
  89. $strategy['step3_count'] = count($step3Questions);
  90. $strategy['expansion_details']['step3_child_kp'] = [
  91. 'child_knowledge_points' => $childKps,
  92. 'added_count' => count($step3Questions)
  93. ];
  94. Log::info('QuestionExpansionService: Step3 - 获取子知识点题目', [
  95. 'child_knowledge_points' => $childKps,
  96. 'added_count' => count($step3Questions),
  97. 'total_count' => count($strategy['mistake_question_ids'])
  98. ]);
  99. }
  100. }
  101. // 如果数量仍不足,继续扩展
  102. $remaining = $totalQuestions - count($strategy['mistake_question_ids']);
  103. if ($remaining <= 0) {
  104. return $strategy;
  105. }
  106. // Step 4: 学生薄弱知识点相关题目(优先级:中)
  107. // 针对性强化薄弱环节,提升整体掌握度
  108. if (!empty($weaknessFilter) && $remaining > 0) {
  109. $weaknessKps = array_column($weaknessFilter, 'kp_code');
  110. $step4Questions = $this->getQuestionsByKnowledgePoints($weaknessKps, $strategy['mistake_question_ids'], $remaining);
  111. $strategy['mistake_question_ids'] = array_merge($strategy['mistake_question_ids'], $step4Questions);
  112. $strategy['step4_count'] = count($step4Questions);
  113. $strategy['expansion_details']['step4_weakness'] = [
  114. 'weakness_knowledge_points' => $weaknessKps,
  115. 'added_count' => count($step4Questions)
  116. ];
  117. Log::info('QuestionExpansionService: Step4 - 获取薄弱知识点题目', [
  118. 'weakness_knowledge_points' => $weaknessKps,
  119. 'added_count' => count($step4Questions),
  120. 'total_count' => count($strategy['mistake_question_ids'])
  121. ]);
  122. }
  123. // 如果数量仍不足,继续扩展
  124. $remaining = $totalQuestions - count($strategy['mistake_question_ids']);
  125. if ($remaining <= 0) {
  126. return $strategy;
  127. }
  128. // Step 5: 薄弱知识点的子知识点的题目(优先级:低)
  129. // 全面覆盖薄弱环节的各个细分领域
  130. if (!empty($weaknessFilter) && $remaining > 0) {
  131. $weaknessKps = array_column($weaknessFilter, 'kp_code');
  132. $childWeaknessKps = $this->getChildKnowledgePoints($weaknessKps);
  133. if (!empty($childWeaknessKps)) {
  134. $step5Questions = $this->getQuestionsByKnowledgePoints($childWeaknessKps, $strategy['mistake_question_ids'], $remaining);
  135. $strategy['mistake_question_ids'] = array_merge($strategy['mistake_question_ids'], $step5Questions);
  136. $strategy['step5_count'] = count($step5Questions);
  137. $strategy['expansion_details']['step5_child_weakness'] = [
  138. 'child_weakness_knowledge_points' => $childWeaknessKps,
  139. 'added_count' => count($step5Questions)
  140. ];
  141. Log::info('QuestionExpansionService: Step5 - 获取薄弱点子知识点题目', [
  142. 'child_weakness_knowledge_points' => $childWeaknessKps,
  143. 'added_count' => count($step5Questions),
  144. 'total_count' => count($strategy['mistake_question_ids'])
  145. ]);
  146. }
  147. }
  148. Log::info('QuestionExpansionService: 题目扩展完成', [
  149. 'total_final_count' => count($strategy['mistake_question_ids']),
  150. 'expansion_details' => $strategy['expansion_details']
  151. ]);
  152. return $strategy;
  153. }
  154. /**
  155. * 获取学生错题(去重,按question_id分组)
  156. */
  157. private function getStudentMistakes(string $studentId): array
  158. {
  159. try {
  160. // 使用 MistakeRecord 模型获取学生的错题(不限制数量,获取全部)
  161. // 按 question_id 分组去重,保留第一条记录
  162. $mistakeRecords = MistakeRecord::forStudent($studentId)
  163. ->where('review_status', '!=', MistakeRecord::REVIEW_STATUS_MASTERED) // 排除已掌握的错题
  164. ->select(['question_id', 'knowledge_point', 'error_type', 'difficulty'])
  165. ->get()
  166. ->unique('question_id') // 按 question_id 去重
  167. ->values(); // 重新索引
  168. Log::info('QuestionExpansionService: 获取学生错题(去重后)', [
  169. 'student_id' => $studentId,
  170. 'total_records' => MistakeRecord::forStudent($studentId)
  171. ->where('review_status', '!=', MistakeRecord::REVIEW_STATUS_MASTERED)->count(),
  172. 'unique_count' => $mistakeRecords->count()
  173. ]);
  174. return $mistakeRecords->map(function ($record) {
  175. return [
  176. 'question_id' => $record->question_id,
  177. 'kp_code' => $record->knowledge_point,
  178. 'error_type' => $record->error_type,
  179. 'difficulty' => $record->difficulty,
  180. ];
  181. })->toArray();
  182. } catch (\Exception $e) {
  183. Log::error('QuestionExpansionService: 获取学生错题失败', [
  184. 'student_id' => $studentId,
  185. 'error' => $e->getMessage()
  186. ]);
  187. return [];
  188. }
  189. }
  190. /**
  191. * 获取错题对应的知识点
  192. */
  193. private function getMistakeKnowledgePoints(string $studentId, array $questionIds): array
  194. {
  195. $mistakeRecords = MistakeRecord::forStudent($studentId)
  196. ->whereIn('question_id', $questionIds)
  197. ->whereNotNull('knowledge_point')
  198. ->select(['knowledge_point'])
  199. ->get();
  200. return array_values(array_unique(array_filter($mistakeRecords->pluck('knowledge_point')->toArray())));
  201. }
  202. /**
  203. * 根据知识点获取题目
  204. */
  205. private function getQuestionsByKnowledgePoints(array $kpCodes, array $excludeQuestionIds, int $limit): array
  206. {
  207. if (empty($kpCodes)) {
  208. return [];
  209. }
  210. try {
  211. $questions = Question::where('audit_status', 0) // 只获取审核通过的题目
  212. ->whereIn('kp_code', $kpCodes)
  213. ->whereNotIn('id', $excludeQuestionIds)
  214. ->select(['id'])
  215. ->limit($limit)
  216. ->get();
  217. return $questions->pluck('id')->toArray();
  218. } catch (\Exception $e) {
  219. Log::warning('QuestionExpansionService: 获取题目失败', [
  220. 'kp_codes' => $kpCodes,
  221. 'limit' => $limit,
  222. 'error' => $e->getMessage()
  223. ]);
  224. return [];
  225. }
  226. }
  227. /**
  228. * 获取子知识点
  229. */
  230. private function getChildKnowledgePoints(array $parentKpCodes): array
  231. {
  232. try {
  233. $childKps = KnowledgePoint::whereIn('parent_kp_code', $parentKpCodes)
  234. ->select(['kp_code'])
  235. ->get();
  236. return $childKps->pluck('kp_code')->toArray();
  237. } catch (\Exception $e) {
  238. Log::warning('QuestionExpansionService: 获取子知识点失败', [
  239. 'parent_kp_codes' => $parentKpCodes,
  240. 'error' => $e->getMessage()
  241. ]);
  242. return [];
  243. }
  244. }
  245. /**
  246. * 获取扩展统计信息
  247. */
  248. public function getExpansionStats(array $strategy): array
  249. {
  250. return [
  251. 'total_questions' => count($strategy['mistake_question_ids'] ?? []),
  252. 'step1_mistakes' => count($strategy['mistake_question_ids'] ?? []),
  253. 'step2_same_kp' => $strategy['step2_count'] ?? 0,
  254. 'step3_child_kp' => $strategy['step3_count'] ?? 0,
  255. 'step4_weakness' => $strategy['step4_count'] ?? 0,
  256. 'step5_child_weakness' => $strategy['step5_count'] ?? 0,
  257. 'expansion_rate' => $this->calculateExpansionRate($strategy),
  258. 'details' => $strategy['expansion_details'] ?? []
  259. ];
  260. }
  261. /**
  262. * 计算扩展率
  263. */
  264. private function calculateExpansionRate(array $strategy): float
  265. {
  266. $totalExpanded = ($strategy['step2_count'] ?? 0) +
  267. ($strategy['step3_count'] ?? 0) +
  268. ($strategy['step4_count'] ?? 0) +
  269. ($strategy['step5_count'] ?? 0);
  270. $totalQuestions = count($strategy['mistake_question_ids'] ?? []);
  271. if ($totalQuestions === 0) {
  272. return 0.0;
  273. }
  274. return round(($totalExpanded / $totalQuestions) * 100, 2);
  275. }
  276. /**
  277. * 按知识点优先级扩展题目数量(按知识点组卷专用)
  278. * 优先级策略:
  279. * 1. 直接关联知识点题目(来自输入数组)
  280. * 2. 相同知识点其他题目
  281. * 3. 子知识点题目(下探1层)
  282. * 4. 薄弱知识点题目
  283. * 5. 子知识点题目(下探2层)
  284. */
  285. public function expandQuestionsByKnowledgePoints(array $baseParams, ?string $studentId, array $targetKnowledgePoints, array $weaknessFilter, int $totalQuestions): array
  286. {
  287. Log::info('QuestionExpansionService: 开始按知识点扩展题目', [
  288. 'student_id' => $studentId,
  289. 'target_knowledge_points' => $targetKnowledgePoints,
  290. 'total_needed' => $totalQuestions,
  291. 'weakness_count' => count($weaknessFilter)
  292. ]);
  293. $strategy = [
  294. 'mistake_ids' => [],
  295. 'mistake_question_ids' => [],
  296. 'step2_count' => 0,
  297. 'step3_count' => 0,
  298. 'step4_count' => 0,
  299. 'step5_count' => 0,
  300. 'expansion_details' => []
  301. ];
  302. $initialExcludeQuestionIds = array_values(array_unique(array_filter(
  303. $baseParams['exclude_question_ids'] ?? []
  304. )));
  305. // Step 1: 获取直接关联知识点题目(优先级:最高)
  306. // 直接使用用户指定的知识点数组中的题目
  307. if (!empty($targetKnowledgePoints)) {
  308. $step1Questions = $this->getQuestionsByKnowledgePoints(
  309. $targetKnowledgePoints,
  310. array_merge($initialExcludeQuestionIds, $strategy['mistake_question_ids']),
  311. $totalQuestions
  312. );
  313. $strategy['mistake_question_ids'] = array_merge($strategy['mistake_question_ids'], $step1Questions);
  314. $strategy['expansion_details']['step1_direct_kp'] = [
  315. 'target_knowledge_points' => $targetKnowledgePoints,
  316. 'added_count' => count($step1Questions)
  317. ];
  318. Log::info('QuestionExpansionService: Step1 - 获取直接关联知识点题目', [
  319. 'target_knowledge_points' => $targetKnowledgePoints,
  320. 'added_count' => count($step1Questions),
  321. 'total_count' => count($strategy['mistake_question_ids'])
  322. ]);
  323. }
  324. // 如果直接关联题目数量已满足需求,直接返回
  325. if (count($strategy['mistake_question_ids']) >= $totalQuestions) {
  326. Log::info('QuestionExpansionService: Step1 - 直接关联知识点题目数量已满足需求', [
  327. 'total_needed' => $totalQuestions,
  328. 'direct_kp_count' => count($strategy['mistake_question_ids'])
  329. ]);
  330. return $strategy;
  331. }
  332. // Step 2: 相同知识点其他题目(优先级:高)
  333. // 强化特定知识点的掌握,题目类型多样化
  334. $remaining = $totalQuestions - count($strategy['mistake_question_ids']);
  335. if (!empty($targetKnowledgePoints) && $remaining > 0) {
  336. $step2Questions = $this->getQuestionsByKnowledgePoints(
  337. $targetKnowledgePoints,
  338. array_merge($initialExcludeQuestionIds, $strategy['mistake_question_ids']),
  339. $remaining
  340. );
  341. $strategy['mistake_question_ids'] = array_merge($strategy['mistake_question_ids'], $step2Questions);
  342. $strategy['step2_count'] = count($step2Questions);
  343. $strategy['expansion_details']['step2_same_kp'] = [
  344. 'knowledge_points' => $targetKnowledgePoints,
  345. 'added_count' => count($step2Questions)
  346. ];
  347. Log::info('QuestionExpansionService: Step2 - 获取相同知识点其他题目', [
  348. 'knowledge_points' => $targetKnowledgePoints,
  349. 'added_count' => count($step2Questions),
  350. 'total_count' => count($strategy['mistake_question_ids'])
  351. ]);
  352. }
  353. // 如果数量仍不足,继续扩展
  354. $remaining = $totalQuestions - count($strategy['mistake_question_ids']);
  355. if ($remaining <= 0) {
  356. return $strategy;
  357. }
  358. // Step 3: 子知识点题目(下探1层)(优先级:中高)
  359. // 深入知识点的细分类别,实现精准练习
  360. if (!empty($targetKnowledgePoints) && $remaining > 0) {
  361. $childKps = $this->getChildKnowledgePoints($targetKnowledgePoints);
  362. if (!empty($childKps)) {
  363. $step3Questions = $this->getQuestionsByKnowledgePoints(
  364. $childKps,
  365. array_merge($initialExcludeQuestionIds, $strategy['mistake_question_ids']),
  366. $remaining
  367. );
  368. $strategy['mistake_question_ids'] = array_merge($strategy['mistake_question_ids'], $step3Questions);
  369. $strategy['step3_count'] = count($step3Questions);
  370. $strategy['expansion_details']['step3_child_kp_level1'] = [
  371. 'child_knowledge_points' => $childKps,
  372. 'added_count' => count($step3Questions)
  373. ];
  374. Log::info('QuestionExpansionService: Step3 - 获取子知识点题目(下探1层)', [
  375. 'child_knowledge_points' => $childKps,
  376. 'added_count' => count($step3Questions),
  377. 'total_count' => count($strategy['mistake_question_ids'])
  378. ]);
  379. }
  380. }
  381. // 如果数量仍不足,继续扩展
  382. $remaining = $totalQuestions - count($strategy['mistake_question_ids']);
  383. if ($remaining <= 0) {
  384. return $strategy;
  385. }
  386. // Step 4: 薄弱知识点题目(优先级:中)
  387. // 针对性强化薄弱环节,提升整体掌握度
  388. if (!empty($weaknessFilter) && $remaining > 0) {
  389. $weaknessKps = array_column($weaknessFilter, 'kp_code');
  390. // 排除已使用的目标知识点
  391. $weaknessKps = array_diff($weaknessKps, $targetKnowledgePoints);
  392. if (!empty($weaknessKps)) {
  393. $step4Questions = $this->getQuestionsByKnowledgePoints(
  394. $weaknessKps,
  395. array_merge($initialExcludeQuestionIds, $strategy['mistake_question_ids']),
  396. $remaining
  397. );
  398. $strategy['mistake_question_ids'] = array_merge($strategy['mistake_question_ids'], $step4Questions);
  399. $strategy['step4_count'] = count($step4Questions);
  400. $strategy['expansion_details']['step4_weakness'] = [
  401. 'weakness_knowledge_points' => $weaknessKps,
  402. 'added_count' => count($step4Questions)
  403. ];
  404. Log::info('QuestionExpansionService: Step4 - 获取薄弱知识点题目', [
  405. 'weakness_knowledge_points' => $weaknessKps,
  406. 'added_count' => count($step4Questions),
  407. 'total_count' => count($strategy['mistake_question_ids'])
  408. ]);
  409. }
  410. }
  411. // 如果数量仍不足,继续扩展
  412. $remaining = $totalQuestions - count($strategy['mistake_question_ids']);
  413. if ($remaining <= 0) {
  414. return $strategy;
  415. }
  416. // Step 5: 子知识点题目(下探2层)(优先级:低)
  417. // 全面覆盖薄弱环节的各个细分领域
  418. if (!empty($weaknessFilter) && $remaining > 0) {
  419. $weaknessKps = array_column($weaknessFilter, 'kp_code');
  420. // 排除已使用的目标知识点
  421. $weaknessKps = array_diff($weaknessKps, $targetKnowledgePoints);
  422. if (!empty($weaknessKps)) {
  423. $childWeaknessKps = $this->getChildKnowledgePoints($weaknessKps);
  424. if (!empty($childWeaknessKps)) {
  425. $step5Questions = $this->getQuestionsByKnowledgePoints(
  426. $childWeaknessKps,
  427. array_merge($initialExcludeQuestionIds, $strategy['mistake_question_ids']),
  428. $remaining
  429. );
  430. $strategy['mistake_question_ids'] = array_merge($strategy['mistake_question_ids'], $step5Questions);
  431. $strategy['step5_count'] = count($step5Questions);
  432. $strategy['expansion_details']['step5_child_weakness_level2'] = [
  433. 'child_weakness_knowledge_points' => $childWeaknessKps,
  434. 'added_count' => count($step5Questions)
  435. ];
  436. Log::info('QuestionExpansionService: Step5 - 获取薄弱点子知识点题目(下探2层)', [
  437. 'child_weakness_knowledge_points' => $childWeaknessKps,
  438. 'added_count' => count($step5Questions),
  439. 'total_count' => count($strategy['mistake_question_ids'])
  440. ]);
  441. }
  442. }
  443. }
  444. Log::info('QuestionExpansionService: 按知识点题目扩展完成', [
  445. 'total_final_count' => count($strategy['mistake_question_ids']),
  446. 'target_knowledge_points' => $targetKnowledgePoints,
  447. 'expansion_details' => $strategy['expansion_details']
  448. ]);
  449. return $strategy;
  450. }
  451. /**
  452. * 获取子知识点(下探多层)
  453. * 支持追溯下探两层
  454. */
  455. private function getChildKnowledgePointsMultiLevel(array $parentKpCodes, int $maxDepth = 2): array
  456. {
  457. $allChildKps = [];
  458. $currentLevelKps = $parentKpCodes;
  459. $depth = 0;
  460. while ($depth < $maxDepth && !empty($currentLevelKps)) {
  461. Log::info('QuestionExpansionService: 获取子知识点', [
  462. 'depth' => $depth + 1,
  463. 'parent_kp_codes' => $currentLevelKps
  464. ]);
  465. $childKps = $this->getChildKnowledgePoints($currentLevelKps);
  466. if (!empty($childKps)) {
  467. $allChildKps = array_merge($allChildKps, $childKps);
  468. $currentLevelKps = $childKps; // 下一层的父级是这一层的子级
  469. } else {
  470. break; // 没有更多子知识点时停止
  471. }
  472. $depth++;
  473. }
  474. // 去重
  475. return array_values(array_unique($allChildKps));
  476. }
  477. }