ExamTypeStrategy.php 41 KB

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