ExamTypeStrategy.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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. $enhanced = array_merge($params, [
  353. 'mistake_question_ids' => $mistakeQuestionIds,
  354. 'paper_ids' => $paperIds,
  355. 'priority_knowledge_points' => array_values($mistakeKnowledgePoints),
  356. 'paper_name' => $params['paper_name'] ?? ('错题本_' . now()->format('Ymd_His')),
  357. // 错题本:保持原有题型配比
  358. 'question_type_ratio' => [
  359. '选择题' => 35,
  360. '填空题' => 30,
  361. '解答题' => 35,
  362. ],
  363. // 错题本不应用难度分布
  364. 'is_mistake_exam' => true,
  365. 'is_paper_based_mistake' => true, // 标记是基于卷子的错题本
  366. 'mistake_count' => count($mistakeQuestionIds),
  367. 'knowledge_points_count' => count($mistakeKnowledgePoints),
  368. ]);
  369. Log::info('ExamTypeStrategy: 错题本参数构建完成', [
  370. 'paper_count' => count($paperIds),
  371. 'mistake_count' => count($mistakeQuestionIds),
  372. 'knowledge_points_count' => count($mistakeKnowledgePoints)
  373. ]);
  374. return $enhanced;
  375. }
  376. /**
  377. * 专项练习:针对特定技能或知识点练习
  378. */
  379. private function buildPracticeParams(array $params): array
  380. {
  381. Log::info('ExamTypeStrategy: 构建专项练习参数', $params);
  382. $studentId = $params['student_id'] ?? null;
  383. $practiceOptions = $params['practice_options'] ?? [];
  384. $weaknessThreshold = $practiceOptions['weakness_threshold'] ?? 0.7;
  385. $intensity = $practiceOptions['intensity'] ?? 'medium';
  386. $focusWeaknesses = $practiceOptions['focus_weaknesses'] ?? true;
  387. // 根据强度调整难度配比
  388. $difficultyRatio = match($intensity) {
  389. 'low' => [
  390. '基础' => 60,
  391. '中等' => 35,
  392. '拔高' => 5,
  393. ],
  394. 'medium' => [
  395. '基础' => 45,
  396. '中等' => 40,
  397. '拔高' => 15,
  398. ],
  399. 'high' => [
  400. '基础' => 30,
  401. '中等' => 45,
  402. '拔高' => 25,
  403. ],
  404. default => [
  405. '基础' => 45,
  406. '中等' => 40,
  407. '拔高' => 15,
  408. ]
  409. };
  410. // 获取学生薄弱点
  411. $weaknessFilter = [];
  412. if ($studentId && $focusWeaknesses) {
  413. $weaknessFilter = $this->getStudentWeaknesses($studentId, $weaknessThreshold);
  414. Log::info('ExamTypeStrategy: 获取到学生薄弱点', [
  415. 'student_id' => $studentId,
  416. 'weakness_threshold' => $weaknessThreshold,
  417. 'weakness_count' => count($weaknessFilter)
  418. ]);
  419. }
  420. // 优先使用薄弱点知识点,如果没有则使用用户选择的知识点
  421. $kpCodes = $params['kp_codes'] ?? [];
  422. if ($studentId && empty($kpCodes) && !empty($weaknessFilter)) {
  423. $kpCodes = array_column($weaknessFilter, 'kp_code');
  424. Log::info('ExamTypeStrategy: 使用薄弱点作为知识点', [
  425. 'kp_codes' => $kpCodes
  426. ]);
  427. }
  428. $enhanced = array_merge($params, [
  429. 'difficulty_ratio' => $difficultyRatio,
  430. 'kp_codes' => $kpCodes,
  431. // 专项练习更注重题型覆盖
  432. 'question_type_ratio' => [
  433. '选择题' => 40,
  434. '填空题' => 30,
  435. '解答题' => 30,
  436. ],
  437. 'paper_name' => $params['paper_name'] ?? ('专项练习_' . now()->format('Ymd_His')),
  438. // 标记这是专项练习,用于后续处理
  439. 'is_practice_exam' => true,
  440. 'weakness_filter' => $weaknessFilter,
  441. ]);
  442. Log::info('ExamTypeStrategy: 专项练习参数构建完成', [
  443. 'intensity' => $intensity,
  444. 'difficulty_ratio' => $enhanced['difficulty_ratio'],
  445. 'kp_codes_count' => count($enhanced['kp_codes']),
  446. 'weakness_count' => count($weaknessFilter)
  447. ]);
  448. return $enhanced;
  449. }
  450. /**
  451. * 教材同步:按教材章节出题
  452. */
  453. private function buildTextbookParams(array $params): array
  454. {
  455. Log::info('ExamTypeStrategy: 构建教材同步参数', $params);
  456. // 教材同步:按章节顺序,难度递增
  457. $textbookOptions = $params['textbook_options'] ?? [];
  458. $enhanced = array_merge($params, [
  459. // 教材同步:基础和中等题为主
  460. 'difficulty_ratio' => [
  461. '基础' => 50,
  462. '中等' => 40,
  463. '拔高' => 10,
  464. ],
  465. 'question_type_ratio' => [
  466. '选择题' => 40,
  467. '填空题' => 30,
  468. '解答题' => 30,
  469. ],
  470. 'paper_name' => $params['paper_name'] ?? ('教材同步_' . now()->format('Ymd_His')),
  471. 'textbook_options' => $textbookOptions,
  472. ]);
  473. return $enhanced;
  474. }
  475. /**
  476. * 知识点专练:单个或少量知识点深练
  477. */
  478. private function buildKnowledgeParams(array $params): array
  479. {
  480. Log::info('ExamTypeStrategy: 构建知识点专练参数', $params);
  481. // 知识点专练:深度挖掘,多角度考查
  482. $knowledgeOptions = $params['knowledge_options'] ?? [];
  483. $enhanced = array_merge($params, [
  484. // 知识点专练:难度分布更均匀
  485. 'difficulty_ratio' => [
  486. '基础' => 35,
  487. '中等' => 45,
  488. '拔高' => 20,
  489. ],
  490. 'question_type_ratio' => [
  491. '选择题' => 30,
  492. '填空题' => 35,
  493. '解答题' => 35,
  494. ],
  495. 'paper_name' => $params['paper_name'] ?? ('知识点专练_' . now()->format('Ymd_His')),
  496. 'knowledge_options' => $knowledgeOptions,
  497. ]);
  498. return $enhanced;
  499. }
  500. /**
  501. * 按知识点组卷:根据指定知识点数组智能选题
  502. * 优先级策略:
  503. * 1. 直接关联知识点题目(来自输入数组)
  504. * 2. 相同知识点其他题目
  505. * 3. 子知识点题目(下探1层)
  506. * 4. 薄弱点题目比例调整
  507. * 5. 子知识点题目(下探2层)
  508. */
  509. private function buildKnowledgePointsParams(array $params): array
  510. {
  511. Log::info('ExamTypeStrategy: 构建按知识点组卷参数', $params);
  512. $studentId = $params['student_id'] ?? null;
  513. $totalQuestions = $params['total_questions'] ?? 20;
  514. $knowledgePointsOptions = $params['knowledge_points_options'] ?? [];
  515. $weaknessThreshold = $knowledgePointsOptions['weakness_threshold'] ?? 0.7;
  516. $focusWeaknesses = $knowledgePointsOptions['focus_weaknesses'] ?? true;
  517. $intensity = $knowledgePointsOptions['intensity'] ?? 'medium';
  518. // 获取用户指定的知识点数组
  519. $targetKnowledgePoints = $params['kp_codes'] ?? [];
  520. if (empty($targetKnowledgePoints)) {
  521. Log::warning('ExamTypeStrategy: 未指定知识点数组,使用默认策略');
  522. return $this->buildGeneralParams($params);
  523. }
  524. Log::info('ExamTypeStrategy: 目标知识点数组', [
  525. 'target_knowledge_points' => $targetKnowledgePoints,
  526. 'count' => count($targetKnowledgePoints)
  527. ]);
  528. // 根据强度调整难度配比
  529. $difficultyRatio = match($intensity) {
  530. 'low' => [
  531. '基础' => 60,
  532. '中等' => 35,
  533. '拔高' => 5,
  534. ],
  535. 'medium' => [
  536. '基础' => 45,
  537. '中等' => 40,
  538. '拔高' => 15,
  539. ],
  540. 'high' => [
  541. '基础' => 30,
  542. '中等' => 45,
  543. '拔高' => 25,
  544. ],
  545. default => [
  546. '基础' => 45,
  547. '中等' => 40,
  548. '拔高' => 15,
  549. ]
  550. };
  551. // 获取学生薄弱点(用于判断目标知识点是否为薄弱点)
  552. $weaknessFilter = [];
  553. if ($studentId && $focusWeaknesses) {
  554. $weaknessFilter = $this->getStudentWeaknesses($studentId, $weaknessThreshold);
  555. Log::info('ExamTypeStrategy: 获取到学生薄弱点', [
  556. 'student_id' => $studentId,
  557. 'weakness_threshold' => $weaknessThreshold,
  558. 'weakness_count' => count($weaknessFilter)
  559. ]);
  560. }
  561. // 检查目标知识点中哪些是薄弱点
  562. $weaknessKpCodes = array_column($weaknessFilter, 'kp_code');
  563. $targetWeaknessKps = array_intersect($targetKnowledgePoints, $weaknessKpCodes);
  564. Log::info('ExamTypeStrategy: 目标知识点中的薄弱点', [
  565. 'target_weakness_kps' => $targetWeaknessKps,
  566. 'weakness_count' => count($targetWeaknessKps)
  567. ]);
  568. // 使用 QuestionExpansionService 按知识点优先级扩展题目
  569. // 修改 expandQuestions 支持直接传入知识点数组
  570. $questionStrategy = $this->questionExpansionService->expandQuestionsByKnowledgePoints(
  571. $params,
  572. $studentId,
  573. $targetKnowledgePoints,
  574. $weaknessFilter,
  575. $totalQuestions
  576. );
  577. // 获取扩展统计
  578. $expansionStats = $this->questionExpansionService->getExpansionStats($questionStrategy);
  579. $enhanced = array_merge($params, [
  580. 'difficulty_ratio' => $difficultyRatio,
  581. 'kp_codes' => $targetKnowledgePoints, // 确保使用目标知识点
  582. 'mistake_question_ids' => $questionStrategy['mistake_question_ids'] ?? [],
  583. // 优先级知识点:目标知识点 + 薄弱点
  584. 'priority_knowledge_points' => array_merge(
  585. array_values($targetKnowledgePoints),
  586. array_column($weaknessFilter, 'kp_code')
  587. ),
  588. 'question_type_ratio' => [
  589. '选择题' => 35,
  590. '填空题' => 30,
  591. '解答题' => 35,
  592. ],
  593. 'paper_name' => $params['paper_name'] ?? ('知识点组卷_' . now()->format('Ymd_His')),
  594. // 标记这是按知识点组卷,用于后续处理
  595. 'is_knowledge_points_exam' => true,
  596. 'weakness_filter' => $weaknessFilter,
  597. // 目标知识点中的薄弱点(用于调整题目数量)
  598. 'target_weakness_kps' => array_values($targetWeaknessKps),
  599. // 题目扩展统计
  600. 'question_expansion_stats' => $expansionStats
  601. ]);
  602. Log::info('ExamTypeStrategy: 按知识点组卷参数构建完成', [
  603. 'intensity' => $intensity,
  604. 'target_knowledge_points_count' => count($targetKnowledgePoints),
  605. 'target_weakness_kps_count' => count($targetWeaknessKps),
  606. 'mistake_question_ids_count' => count($enhanced['mistake_question_ids']),
  607. 'priority_knowledge_points_count' => count($enhanced['priority_knowledge_points']),
  608. 'question_expansion_stats' => $enhanced['question_expansion_stats'],
  609. 'weakness_count' => count($weaknessFilter)
  610. ]);
  611. return $enhanced;
  612. }
  613. /**
  614. * 为摸底测试扩展知识点(确保覆盖全面)
  615. */
  616. private function expandKpCodesForDiagnostic(array $kpCodes): array
  617. {
  618. if (!empty($kpCodes)) {
  619. return $kpCodes;
  620. }
  621. // 如果没有指定知识点,返回一些通用的数学知识点
  622. return [
  623. '一元二次方程',
  624. '二次函数',
  625. '旋转',
  626. '圆',
  627. '概率初步',
  628. ];
  629. }
  630. /**
  631. * 获取学生薄弱点
  632. */
  633. private function getStudentWeaknesses(string $studentId, float $threshold): array
  634. {
  635. try {
  636. // 使用 StudentKnowledgeMastery 模型获取掌握度低于阈值的知识点
  637. $weaknessRecords = StudentKnowledgeMastery::forStudent($studentId)
  638. ->weaknesses($threshold)
  639. ->orderByMastery('asc')
  640. ->limit(20)
  641. ->with('knowledgePoint') // 预加载知识点信息
  642. ->get();
  643. // 转换为统一格式
  644. return $weaknessRecords->map(function ($record) {
  645. return [
  646. 'kp_code' => $record->kp_code,
  647. 'kp_name' => $record->knowledgePoint->name ?? $record->kp_code,
  648. 'mastery' => (float) ($record->mastery_level ?? 0),
  649. 'attempts' => (int) ($record->total_attempts ?? 0),
  650. 'correct' => (int) ($record->correct_attempts ?? 0),
  651. 'incorrect' => (int) ($record->incorrect_attempts ?? 0),
  652. 'confidence' => (float) ($record->confidence_level ?? 0),
  653. 'trend' => $record->mastery_trend ?? 'stable',
  654. ];
  655. })->toArray();
  656. } catch (\Exception $e) {
  657. Log::error('ExamTypeStrategy: 获取学生薄弱点失败', [
  658. 'student_id' => $studentId,
  659. 'threshold' => $threshold,
  660. 'error' => $e->getMessage()
  661. ]);
  662. return [];
  663. }
  664. }
  665. /**
  666. * 智能组卷 (assembleType=1)
  667. * 根据 textbook_id 查询章节,获取知识点,然后组卷
  668. * 增加年级概念选题逻辑
  669. */
  670. private function buildIntelligentAssembleParams(array $params): array
  671. {
  672. Log::info('ExamTypeStrategy: 构建智能组卷参数', $params);
  673. $textbookId = $params['textbook_id'] ?? null;
  674. $grade = $params['grade'] ?? null; // 年级信息
  675. $totalQuestions = $params['total_questions'] ?? 20;
  676. if (!$textbookId) {
  677. Log::warning('ExamTypeStrategy: 智能组卷需要 textbook_id 参数');
  678. return $this->buildGeneralParams($params);
  679. }
  680. // 第一步:根据 textbook_id 查询章节
  681. $catalogChapterIds = $this->getTextbookChapterIds($textbookId);
  682. if (empty($catalogChapterIds)) {
  683. Log::warning('ExamTypeStrategy: 未找到课本章节', ['textbook_id' => $textbookId]);
  684. return $this->buildGeneralParams($params);
  685. }
  686. Log::info('ExamTypeStrategy: 获取到课本章节', [
  687. 'textbook_id' => $textbookId,
  688. 'chapter_count' => count($catalogChapterIds)
  689. ]);
  690. // 第二步:根据章节ID查询知识点关联
  691. $kpCodes = $this->getKnowledgePointsFromChapters($catalogChapterIds, 25);
  692. if (empty($kpCodes)) {
  693. Log::warning('ExamTypeStrategy: 未找到知识点关联', [
  694. 'textbook_id' => $textbookId,
  695. 'chapter_ids' => $catalogChapterIds
  696. ]);
  697. return $this->buildGeneralParams($params);
  698. }
  699. Log::info('ExamTypeStrategy: 获取到知识点', [
  700. 'kp_count' => count($kpCodes),
  701. 'kp_codes' => array_slice($kpCodes, 0, 5) // 只记录前5个
  702. ]);
  703. // 组装增强参数
  704. $enhanced = array_merge($params, [
  705. 'kp_codes' => $kpCodes,
  706. 'textbook_id' => $textbookId,
  707. 'grade' => $grade,
  708. 'catalog_chapter_ids' => $catalogChapterIds,
  709. 'paper_name' => $params['paper_name'] ?? ('智能组卷_' . now()->format('Ymd_His')),
  710. // 智能组卷:平衡的题型和难度配比
  711. 'question_type_ratio' => [
  712. '选择题' => 40,
  713. '填空题' => 30,
  714. '解答题' => 30,
  715. ],
  716. 'difficulty_ratio' => [
  717. '基础' => 25,
  718. '中等' => 50,
  719. '拔高' => 25,
  720. ],
  721. 'question_category' => 0, // question_category=0 代表普通题目(智能组卷)
  722. 'is_intelligent_assemble' => true,
  723. ]);
  724. Log::info('ExamTypeStrategy: 智能组卷参数构建完成', [
  725. 'textbook_id' => $textbookId,
  726. 'grade' => $grade,
  727. 'kp_count' => count($kpCodes),
  728. 'total_questions' => $totalQuestions
  729. ]);
  730. return $enhanced;
  731. }
  732. /**
  733. * 知识点组卷 (assembleType=2)
  734. * 直接根据 kp_code_list 查询题目,排除已做过的题目
  735. */
  736. private function buildKnowledgePointAssembleParams(array $params): array
  737. {
  738. Log::info('ExamTypeStrategy: 构建知识点组卷参数', $params);
  739. $kpCodeList = $params['kp_code_list'] ?? [];
  740. $studentId = $params['student_id'] ?? null;
  741. $totalQuestions = $params['total_questions'] ?? 20;
  742. if (empty($kpCodeList)) {
  743. Log::warning('ExamTypeStrategy: 知识点组卷需要 kp_code_list 参数');
  744. return $this->buildGeneralParams($params);
  745. }
  746. Log::info('ExamTypeStrategy: 知识点组卷', [
  747. 'kp_code_list' => $kpCodeList,
  748. 'student_id' => $studentId,
  749. 'total_questions' => $totalQuestions
  750. ]);
  751. // 如果有学生ID,获取已做过的题目ID列表(用于排除)
  752. $answeredQuestionIds = [];
  753. if ($studentId) {
  754. $answeredQuestionIds = $this->getStudentAnsweredQuestionIds($studentId, $kpCodeList);
  755. Log::info('ExamTypeStrategy: 获取学生已答题目', [
  756. 'student_id' => $studentId,
  757. 'answered_count' => count($answeredQuestionIds)
  758. ]);
  759. }
  760. // 组装增强参数
  761. $enhanced = array_merge($params, [
  762. 'kp_codes' => $kpCodeList,
  763. 'exclude_question_ids' => $answeredQuestionIds,
  764. 'paper_name' => $params['paper_name'] ?? ('知识点组卷_' . now()->format('Ymd_His')),
  765. // 知识点组卷:注重题型平衡
  766. 'question_type_ratio' => [
  767. '选择题' => 35,
  768. '填空题' => 30,
  769. '解答题' => 35,
  770. ],
  771. 'difficulty_ratio' => [
  772. '基础' => 25,
  773. '中等' => 50,
  774. '拔高' => 25,
  775. ],
  776. 'question_category' => 0, // question_category=0 代表普通题目
  777. 'is_knowledge_point_assemble' => true,
  778. ]);
  779. Log::info('ExamTypeStrategy: 知识点组卷参数构建完成', [
  780. 'kp_count' => count($kpCodeList),
  781. 'exclude_count' => count($answeredQuestionIds),
  782. 'total_questions' => $totalQuestions
  783. ]);
  784. return $enhanced;
  785. }
  786. /**
  787. * 教材组卷 (assembleType=3)
  788. * 根据 chapter_id_list 查询课本章节,获取知识点,然后组卷
  789. */
  790. private function buildTextbookAssembleParams(array $params): array
  791. {
  792. Log::info('ExamTypeStrategy: 构建教材组卷参数', $params);
  793. $chapterIdList = $params['chapter_id_list'] ?? [];
  794. $studentId = $params['student_id'] ?? null;
  795. $totalQuestions = $params['total_questions'] ?? 20;
  796. if (empty($chapterIdList)) {
  797. Log::warning('ExamTypeStrategy: 教材组卷需要 chapter_id_list 参数');
  798. return $this->buildGeneralParams($params);
  799. }
  800. Log::info('ExamTypeStrategy: 教材组卷', [
  801. 'chapter_id_list' => $chapterIdList,
  802. 'student_id' => $studentId,
  803. 'total_questions' => $totalQuestions
  804. ]);
  805. // 第一步:根据章节ID查询知识点关联
  806. $kpCodes = $this->getKnowledgePointsFromChapters($chapterIdList);
  807. if (empty($kpCodes)) {
  808. Log::warning('ExamTypeStrategy: 未找到章节知识点关联', [
  809. 'chapter_id_list' => $chapterIdList
  810. ]);
  811. return $this->buildGeneralParams($params);
  812. }
  813. Log::info('ExamTypeStrategy: 获取章节知识点', [
  814. 'kp_count' => count($kpCodes),
  815. 'kp_codes' => array_slice($kpCodes, 0, 5)
  816. ]);
  817. // 第二步:如果有学生ID,获取已做过的题目ID列表(用于排除)
  818. $answeredQuestionIds = [];
  819. if ($studentId) {
  820. $answeredQuestionIds = $this->getStudentAnsweredQuestionIds($studentId, $kpCodes);
  821. Log::info('ExamTypeStrategy: 获取学生已答题目', [
  822. 'student_id' => $studentId,
  823. 'answered_count' => count($answeredQuestionIds)
  824. ]);
  825. }
  826. // 组装增强参数
  827. $enhanced = array_merge($params, [
  828. 'kp_codes' => $kpCodes,
  829. 'chapter_id_list' => $chapterIdList,
  830. 'exclude_question_ids' => $answeredQuestionIds,
  831. 'paper_name' => $params['paper_name'] ?? ('教材组卷_' . now()->format('Ymd_His')),
  832. // 教材组卷:按教材特点分配题型
  833. 'question_type_ratio' => [
  834. '选择题' => 40,
  835. '填空题' => 30,
  836. '解答题' => 30,
  837. ],
  838. 'difficulty_ratio' => [
  839. '基础' => 25,
  840. '中等' => 50,
  841. '拔高' => 25,
  842. ],
  843. 'question_category' => 0, // question_category=0 代表普通题目
  844. 'is_textbook_assemble' => true,
  845. ]);
  846. Log::info('ExamTypeStrategy: 教材组卷参数构建完成', [
  847. 'chapter_count' => count($chapterIdList),
  848. 'kp_count' => count($kpCodes),
  849. 'exclude_count' => count($answeredQuestionIds),
  850. 'total_questions' => $totalQuestions
  851. ]);
  852. return $enhanced;
  853. }
  854. /**
  855. * 根据课本ID获取章节ID列表
  856. */
  857. private function getTextbookChapterIds(int $textbookId): array
  858. {
  859. try {
  860. // 查询 text_book_catalog_nodes 表
  861. $chapterIds = DB::table('textbook_catalog_nodes')
  862. ->where('textbook_id', $textbookId)
  863. ->where('node_type', 'section') // nodeType='section'
  864. ->orderBy('sort_order')
  865. ->pluck('id')
  866. ->toArray();
  867. Log::debug('ExamTypeStrategy: 查询课本章节ID', [
  868. 'textbook_id' => $textbookId,
  869. 'found_count' => count($chapterIds)
  870. ]);
  871. return $chapterIds;
  872. } catch (\Exception $e) {
  873. Log::error('ExamTypeStrategy: 查询课本章节ID失败', [
  874. 'textbook_id' => $textbookId,
  875. 'error' => $e->getMessage()
  876. ]);
  877. return [];
  878. }
  879. }
  880. /**
  881. * 根据章节ID列表获取知识点代码列表
  882. */
  883. private function getKnowledgePointsFromChapters(array $chapterIds, int $limit = 25): array
  884. {
  885. try {
  886. // 查询 textbook_chapter_knowledge_relation 表
  887. $kpCodes = DB::table('textbook_chapter_knowledge_relation')
  888. ->whereIn('catalog_chapter_id', $chapterIds)
  889. ->limit($limit)
  890. ->distinct()
  891. ->pluck('kp_code')
  892. ->toArray();
  893. Log::debug('ExamTypeStrategy: 查询章节知识点', [
  894. 'chapter_count' => count($chapterIds),
  895. 'found_kp_count' => count($kpCodes)
  896. ]);
  897. return array_filter($kpCodes); // 移除空值
  898. } catch (\Exception $e) {
  899. Log::error('ExamTypeStrategy: 查询章节知识点失败', [
  900. 'chapter_ids' => $chapterIds,
  901. 'error' => $e->getMessage()
  902. ]);
  903. return [];
  904. }
  905. }
  906. /**
  907. * 获取学生已答题目ID列表(用于排除)
  908. */
  909. private function getStudentAnsweredQuestionIds(string $studentId, array $kpCodes): array
  910. {
  911. try {
  912. // 查询 student_answer_questions 表
  913. $questionIds = DB::table('student_answer_questions')
  914. ->where('student_id', $studentId)
  915. ->whereIn('kp_code', $kpCodes)
  916. ->distinct()
  917. ->pluck('question_id')
  918. ->toArray();
  919. Log::debug('ExamTypeStrategy: 查询学生已答题目', [
  920. 'student_id' => $studentId,
  921. 'kp_count' => count($kpCodes),
  922. 'answered_count' => count($questionIds)
  923. ]);
  924. return array_filter($questionIds); // 移除空值
  925. } catch (\Exception $e) {
  926. Log::error('ExamTypeStrategy: 查询学生已答题目失败', [
  927. 'student_id' => $studentId,
  928. 'error' => $e->getMessage()
  929. ]);
  930. return [];
  931. }
  932. }
  933. /**
  934. * 通过卷子ID列表查询错题
  935. * 注意:paper_ids 使用的是 papers 表中的 paper_id 字段,不是 id 字段
  936. * 错题数据从 mistake_records 表中获取,该表已包含 paper_id 字段
  937. * 注意:不按学生ID过滤,因为卷子可能包含其他同学的错题,需要收集所有错题
  938. */
  939. private function getMistakeQuestionsFromPapers(array $paperIds, ?string $studentId = null): array
  940. {
  941. try {
  942. // 使用 Eloquent 模型查询,从 mistake_records 表中获取错题记录
  943. // 不按 student_id 过滤,因为要收集所有学生的错题
  944. $mistakeRecords = MistakeRecord::query()
  945. ->whereIn('paper_id', $paperIds)
  946. ->get();
  947. if ($mistakeRecords->isEmpty()) {
  948. Log::warning('ExamTypeStrategy: 卷子中未找到错题记录', [
  949. 'paper_ids' => $paperIds
  950. ]);
  951. return [];
  952. }
  953. // 收集所有错题的 question_id
  954. $questionIds = $mistakeRecords->pluck('question_id')
  955. ->filter()
  956. ->unique()
  957. ->values()
  958. ->toArray();
  959. Log::info('ExamTypeStrategy: 查询卷子错题完成', [
  960. 'paper_count' => count($paperIds),
  961. 'paper_ids_input' => $paperIds,
  962. 'mistake_record_count' => $mistakeRecords->count(),
  963. 'unique_question_count' => count($questionIds),
  964. 'question_ids' => array_slice($questionIds, 0, 20), // 最多记录20个ID
  965. 'per_paper_stats' => $mistakeRecords->groupBy('paper_id')->map->count()->toArray()
  966. ]);
  967. return array_filter($questionIds);
  968. } catch (\Exception $e) {
  969. Log::error('ExamTypeStrategy: 查询卷子错题失败', [
  970. 'paper_ids' => $paperIds,
  971. 'error' => $e->getMessage()
  972. ]);
  973. return [];
  974. }
  975. }
  976. /**
  977. * 通过题目ID列表获取知识点代码列表
  978. */
  979. private function getKnowledgePointsFromQuestions(array $questionIds): array
  980. {
  981. try {
  982. // 使用 Eloquent 模型查询,获取题目的知识点
  983. $questions = Question::whereIn('id', $questionIds)
  984. ->whereNotNull('kp_code')
  985. ->where('kp_code', '!=', '')
  986. ->distinct()
  987. ->pluck('kp_code')
  988. ->toArray();
  989. Log::debug('ExamTypeStrategy: 查询题目知识点', [
  990. 'question_count' => count($questionIds),
  991. 'kp_count' => count($questions)
  992. ]);
  993. return array_filter($questions);
  994. } catch (\Exception $e) {
  995. Log::error('ExamTypeStrategy: 查询题目知识点失败', [
  996. 'question_ids' => array_slice($questionIds, 0, 10), // 只记录前10个
  997. 'error' => $e->getMessage()
  998. ]);
  999. return [];
  1000. }
  1001. }
  1002. }