ExamTypeStrategy.php 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  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,不修改
  118. 'difficulty_category' => $difficultyCategory,
  119. ]);
  120. Log::info('ExamTypeStrategy: 难度分布应用完成', [
  121. 'category' => $difficultyCategory,
  122. 'distribution' => $distribution
  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. $endCatalogId = $params['end_catalog_id'] ?? null; // 截止章节ID
  265. if (!$textbookId) {
  266. Log::warning('ExamTypeStrategy: 摸底测试需要 textbook_id 参数');
  267. return $this->buildGeneralParams($params);
  268. }
  269. // 第一步:根据 textbook_id 查询章节(支持截止章节过滤)
  270. $catalogChapterIds = $this->getTextbookChapterIds($textbookId, $endCatalogId);
  271. if (empty($catalogChapterIds)) {
  272. Log::warning('ExamTypeStrategy: 未找到课本章节', ['textbook_id' => $textbookId]);
  273. return $this->buildGeneralParams($params);
  274. }
  275. Log::info('ExamTypeStrategy: 获取到课本章节(摸底测试)', [
  276. 'textbook_id' => $textbookId,
  277. 'end_catalog_id' => $endCatalogId,
  278. 'chapter_count' => count($catalogChapterIds)
  279. ]);
  280. // 第二步:根据章节ID查询知识点关联
  281. $kpCodes = $this->getKnowledgePointsFromChapters($catalogChapterIds, 25);
  282. if (empty($kpCodes)) {
  283. Log::warning('ExamTypeStrategy: 未找到知识点关联', ['textbook_id' => $textbookId]);
  284. return $this->buildGeneralParams($params);
  285. }
  286. Log::info('ExamTypeStrategy: 获取到知识点(摸底测试)', [
  287. 'kp_count' => count($kpCodes),
  288. 'kp_codes' => $kpCodes,
  289. 'textbook_id' => $textbookId,
  290. 'grade' => $grade,
  291. 'note' => '知识点数量将直接影响题目多样性'
  292. ]);
  293. // 摸底测试:平衡所有难度,覆盖多个知识点
  294. // 【修复】移除硬编码难度配比,使用difficulty_category参数动态计算
  295. $enhanced = array_merge($params, [
  296. 'kp_codes' => $kpCodes,
  297. 'textbook_id' => $textbookId,
  298. 'grade' => $grade,
  299. 'catalog_chapter_ids' => $catalogChapterIds,
  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. 'difficulty_category' => $params['difficulty_category'] ?? 1,
  314. 'note' => '将在buildParams中应用difficulty_category难度分布'
  315. ]);
  316. return $enhanced;
  317. }
  318. /**
  319. * 错题本 (assembleType=5)
  320. * 根据 paper_ids 数组查询卷子中的错题,组合成新卷子
  321. * 不需要 total_questions 参数
  322. */
  323. private function buildMistakeParams(array $params): array
  324. {
  325. Log::info('ExamTypeStrategy: 构建错题本参数', $params);
  326. $paperIds = $params['paper_ids'] ?? [];
  327. $studentId = $params['student_id'] ?? null;
  328. // 检查是否有 paper_ids 参数
  329. if (empty($paperIds)) {
  330. Log::warning('ExamTypeStrategy: 错题本需要 paper_ids 参数');
  331. return $this->buildGeneralParams($params);
  332. }
  333. Log::info('ExamTypeStrategy: 错题本组卷', [
  334. 'paper_ids' => $paperIds,
  335. 'student_id' => $studentId,
  336. 'paper_count' => count($paperIds)
  337. ]);
  338. // 通过 paper_ids 查询卷子中的错题
  339. $mistakeQuestionIds = $this->getMistakeQuestionsFromPapers($paperIds, $studentId);
  340. if (empty($mistakeQuestionIds)) {
  341. Log::warning('ExamTypeStrategy: 未找到错题', [
  342. 'paper_ids' => $paperIds
  343. ]);
  344. return $this->buildGeneralParams($params);
  345. }
  346. Log::info('ExamTypeStrategy: 获取到错题', [
  347. 'paper_count' => count($paperIds),
  348. 'mistake_count' => count($mistakeQuestionIds),
  349. 'mistake_question_ids' => array_slice($mistakeQuestionIds, 0, 10) // 只记录前10个
  350. ]);
  351. // 获取错题知识点
  352. $mistakeKnowledgePoints = $this->getKnowledgePointsFromQuestions($mistakeQuestionIds);
  353. // 组装增强参数
  354. $mistakeCount = count($mistakeQuestionIds);
  355. $maxQuestions = 50; // 错题本最大题目数限制
  356. // 如果错题超过最大值,截取到最大值
  357. if ($mistakeCount > $maxQuestions) {
  358. Log::warning('ExamTypeStrategy: 错题数量超过最大值限制,已截取', [
  359. 'mistake_count' => $mistakeCount,
  360. 'max_limit' => $maxQuestions,
  361. 'truncated_count' => $maxQuestions
  362. ]);
  363. $mistakeQuestionIds = array_slice($mistakeQuestionIds, 0, $maxQuestions);
  364. $mistakeCount = $maxQuestions;
  365. }
  366. $enhanced = array_merge($params, [
  367. 'mistake_question_ids' => $mistakeQuestionIds,
  368. 'paper_ids' => $paperIds,
  369. 'priority_knowledge_points' => array_values($mistakeKnowledgePoints),
  370. 'paper_name' => $params['paper_name'] ?? ('错题本_' . now()->format('Ymd_His')),
  371. 'total_questions' => $mistakeCount, // 错题本题目数量由实际错题数量决定
  372. // 错题本:保持原有题型配比
  373. 'question_type_ratio' => [
  374. '选择题' => 35,
  375. '填空题' => 30,
  376. '解答题' => 35,
  377. ],
  378. // 错题本不应用难度分布
  379. 'is_mistake_exam' => true,
  380. 'is_paper_based_mistake' => true, // 标记是基于卷子的错题本
  381. 'mistake_count' => $mistakeCount,
  382. 'knowledge_points_count' => count($mistakeKnowledgePoints),
  383. 'max_questions_limit' => $maxQuestions,
  384. ]);
  385. Log::info('ExamTypeStrategy: 错题本参数构建完成', [
  386. 'paper_count' => count($paperIds),
  387. 'mistake_count' => count($mistakeQuestionIds),
  388. 'knowledge_points_count' => count($mistakeKnowledgePoints)
  389. ]);
  390. return $enhanced;
  391. }
  392. /**
  393. * 专项练习:针对特定技能或知识点练习
  394. */
  395. private function buildPracticeParams(array $params): array
  396. {
  397. Log::info('ExamTypeStrategy: 构建专项练习参数', $params);
  398. $studentId = $params['student_id'] ?? null;
  399. $practiceOptions = $params['practice_options'] ?? [];
  400. $weaknessThreshold = $practiceOptions['weakness_threshold'] ?? 0.7;
  401. $intensity = $practiceOptions['intensity'] ?? 'medium';
  402. $focusWeaknesses = $practiceOptions['focus_weaknesses'] ?? true;
  403. // 【修复】移除硬编码难度配比,专项练习使用difficulty_category参数
  404. // 注意:强度调节逻辑已移除,统一使用difficulty_category控制难度分布
  405. // 获取学生薄弱点
  406. $weaknessFilter = [];
  407. if ($studentId && $focusWeaknesses) {
  408. $weaknessFilter = $this->getStudentWeaknesses($studentId, $weaknessThreshold);
  409. Log::info('ExamTypeStrategy: 获取到学生薄弱点', [
  410. 'student_id' => $studentId,
  411. 'weakness_threshold' => $weaknessThreshold,
  412. 'weakness_count' => count($weaknessFilter)
  413. ]);
  414. }
  415. // 优先使用薄弱点知识点,如果没有则使用用户选择的知识点
  416. $kpCodes = $params['kp_codes'] ?? [];
  417. if ($studentId && empty($kpCodes) && !empty($weaknessFilter)) {
  418. $kpCodes = array_column($weaknessFilter, 'kp_code');
  419. Log::info('ExamTypeStrategy: 使用薄弱点作为知识点', [
  420. 'kp_codes' => $kpCodes
  421. ]);
  422. }
  423. $enhanced = array_merge($params, [
  424. 'kp_codes' => $kpCodes,
  425. // 专项练习更注重题型覆盖
  426. 'question_type_ratio' => [
  427. '选择题' => 40,
  428. '填空题' => 30,
  429. '解答题' => 30,
  430. ],
  431. 'paper_name' => $params['paper_name'] ?? ('专项练习_' . now()->format('Ymd_His')),
  432. // 标记这是专项练习,用于后续处理
  433. 'is_practice_exam' => true,
  434. 'weakness_filter' => $weaknessFilter,
  435. ]);
  436. Log::info('ExamTypeStrategy: 专项练习参数构建完成(未应用难度分布)', [
  437. 'intensity' => $intensity,
  438. 'difficulty_category' => $params['difficulty_category'] ?? 1,
  439. 'kp_codes_count' => count($enhanced['kp_codes']),
  440. 'weakness_count' => count($weaknessFilter),
  441. 'note' => '将在buildParams中应用difficulty_category难度分布'
  442. ]);
  443. return $enhanced;
  444. }
  445. /**
  446. * 教材同步:按教材章节出题
  447. */
  448. private function buildTextbookParams(array $params): array
  449. {
  450. Log::info('ExamTypeStrategy: 构建教材同步参数', $params);
  451. // 教材同步:按章节顺序,难度递增
  452. // 【修复】移除硬编码难度配比,使用difficulty_category参数
  453. $textbookOptions = $params['textbook_options'] ?? [];
  454. $enhanced = array_merge($params, [
  455. 'question_type_ratio' => [
  456. '选择题' => 40,
  457. '填空题' => 30,
  458. '解答题' => 30,
  459. ],
  460. 'paper_name' => $params['paper_name'] ?? ('教材同步_' . now()->format('Ymd_His')),
  461. 'textbook_options' => $textbookOptions,
  462. ]);
  463. Log::info('ExamTypeStrategy: 教材同步参数构建完成(未应用难度分布)', [
  464. 'difficulty_category' => $params['difficulty_category'] ?? 1,
  465. 'note' => '将在buildParams中应用difficulty_category难度分布'
  466. ]);
  467. return $enhanced;
  468. }
  469. /**
  470. * 知识点专练:单个或少量知识点深练
  471. */
  472. private function buildKnowledgeParams(array $params): array
  473. {
  474. Log::info('ExamTypeStrategy: 构建知识点专练参数', $params);
  475. // 知识点专练:深度挖掘,多角度考查
  476. // 【修复】移除硬编码难度配比,使用difficulty_category参数
  477. $knowledgeOptions = $params['knowledge_options'] ?? [];
  478. $enhanced = array_merge($params, [
  479. 'question_type_ratio' => [
  480. '选择题' => 30,
  481. '填空题' => 35,
  482. '解答题' => 35,
  483. ],
  484. 'paper_name' => $params['paper_name'] ?? ('知识点专练_' . now()->format('Ymd_His')),
  485. 'knowledge_options' => $knowledgeOptions,
  486. ]);
  487. Log::info('ExamTypeStrategy: 知识点专练参数构建完成(未应用难度分布)', [
  488. 'difficulty_category' => $params['difficulty_category'] ?? 1,
  489. 'note' => '将在buildParams中应用difficulty_category难度分布'
  490. ]);
  491. return $enhanced;
  492. }
  493. /**
  494. * 按知识点组卷:根据指定知识点数组智能选题
  495. * 优先级策略:
  496. * 1. 直接关联知识点题目(来自输入数组)
  497. * 2. 相同知识点其他题目
  498. * 3. 子知识点题目(下探1层)
  499. * 4. 薄弱点题目比例调整
  500. * 5. 子知识点题目(下探2层)
  501. */
  502. private function buildKnowledgePointsParams(array $params): array
  503. {
  504. Log::info('ExamTypeStrategy: 构建按知识点组卷参数', $params);
  505. $studentId = $params['student_id'] ?? null;
  506. $totalQuestions = $params['total_questions'] ?? 20;
  507. $knowledgePointsOptions = $params['knowledge_points_options'] ?? [];
  508. $weaknessThreshold = $knowledgePointsOptions['weakness_threshold'] ?? 0.7;
  509. $focusWeaknesses = $knowledgePointsOptions['focus_weaknesses'] ?? true;
  510. $intensity = $knowledgePointsOptions['intensity'] ?? 'medium';
  511. // 获取用户指定的知识点数组
  512. $targetKnowledgePoints = $params['kp_codes'] ?? [];
  513. if (empty($targetKnowledgePoints)) {
  514. Log::warning('ExamTypeStrategy: 未指定知识点数组,使用默认策略');
  515. return $this->buildGeneralParams($params);
  516. }
  517. Log::info('ExamTypeStrategy: 目标知识点数组', [
  518. 'target_knowledge_points' => $targetKnowledgePoints,
  519. 'count' => count($targetKnowledgePoints)
  520. ]);
  521. // 根据强度调整难度配比
  522. $difficultyRatio = match($intensity) {
  523. 'low' => [
  524. '基础' => 60,
  525. '中等' => 35,
  526. '拔高' => 5,
  527. ],
  528. 'medium' => [
  529. '基础' => 45,
  530. '中等' => 40,
  531. '拔高' => 15,
  532. ],
  533. 'high' => [
  534. '基础' => 30,
  535. '中等' => 45,
  536. '拔高' => 25,
  537. ],
  538. default => [
  539. '基础' => 45,
  540. '中等' => 40,
  541. '拔高' => 15,
  542. ]
  543. };
  544. // 获取学生薄弱点(用于判断目标知识点是否为薄弱点)
  545. $weaknessFilter = [];
  546. if ($studentId && $focusWeaknesses) {
  547. $weaknessFilter = $this->getStudentWeaknesses($studentId, $weaknessThreshold);
  548. Log::info('ExamTypeStrategy: 获取到学生薄弱点', [
  549. 'student_id' => $studentId,
  550. 'weakness_threshold' => $weaknessThreshold,
  551. 'weakness_count' => count($weaknessFilter)
  552. ]);
  553. }
  554. // 检查目标知识点中哪些是薄弱点
  555. $weaknessKpCodes = array_column($weaknessFilter, 'kp_code');
  556. $targetWeaknessKps = array_intersect($targetKnowledgePoints, $weaknessKpCodes);
  557. Log::info('ExamTypeStrategy: 目标知识点中的薄弱点', [
  558. 'target_weakness_kps' => $targetWeaknessKps,
  559. 'weakness_count' => count($targetWeaknessKps)
  560. ]);
  561. // 使用 QuestionExpansionService 按知识点优先级扩展题目
  562. // 修改 expandQuestions 支持直接传入知识点数组
  563. $questionStrategy = $this->questionExpansionService->expandQuestionsByKnowledgePoints(
  564. $params,
  565. $studentId,
  566. $targetKnowledgePoints,
  567. $weaknessFilter,
  568. $totalQuestions
  569. );
  570. // 获取扩展统计
  571. $expansionStats = $this->questionExpansionService->getExpansionStats($questionStrategy);
  572. $enhanced = array_merge($params, [
  573. 'difficulty_ratio' => $difficultyRatio,
  574. 'kp_codes' => $targetKnowledgePoints, // 确保使用目标知识点
  575. 'mistake_question_ids' => $questionStrategy['mistake_question_ids'] ?? [],
  576. // 优先级知识点:目标知识点 + 薄弱点
  577. 'priority_knowledge_points' => array_merge(
  578. array_values($targetKnowledgePoints),
  579. array_column($weaknessFilter, 'kp_code')
  580. ),
  581. 'question_type_ratio' => [
  582. '选择题' => 35,
  583. '填空题' => 30,
  584. '解答题' => 35,
  585. ],
  586. 'paper_name' => $params['paper_name'] ?? ('知识点组卷_' . now()->format('Ymd_His')),
  587. // 标记这是按知识点组卷,用于后续处理
  588. 'is_knowledge_points_exam' => true,
  589. 'weakness_filter' => $weaknessFilter,
  590. // 目标知识点中的薄弱点(用于调整题目数量)
  591. 'target_weakness_kps' => array_values($targetWeaknessKps),
  592. // 题目扩展统计
  593. 'question_expansion_stats' => $expansionStats
  594. ]);
  595. Log::info('ExamTypeStrategy: 按知识点组卷参数构建完成', [
  596. 'intensity' => $intensity,
  597. 'target_knowledge_points_count' => count($targetKnowledgePoints),
  598. 'target_weakness_kps_count' => count($targetWeaknessKps),
  599. 'mistake_question_ids_count' => count($enhanced['mistake_question_ids']),
  600. 'priority_knowledge_points_count' => count($enhanced['priority_knowledge_points']),
  601. 'question_expansion_stats' => $enhanced['question_expansion_stats'],
  602. 'weakness_count' => count($weaknessFilter)
  603. ]);
  604. return $enhanced;
  605. }
  606. /**
  607. * 为摸底测试扩展知识点(确保覆盖全面)
  608. */
  609. private function expandKpCodesForDiagnostic(array $kpCodes): array
  610. {
  611. if (!empty($kpCodes)) {
  612. return $kpCodes;
  613. }
  614. // 如果没有指定知识点,返回一些通用的数学知识点
  615. return [
  616. '一元二次方程',
  617. '二次函数',
  618. '旋转',
  619. '圆',
  620. '概率初步',
  621. ];
  622. }
  623. /**
  624. * 获取学生薄弱点
  625. */
  626. private function getStudentWeaknesses(string $studentId, float $threshold): array
  627. {
  628. try {
  629. // 使用 StudentKnowledgeMastery 模型获取掌握度低于阈值的知识点
  630. $weaknessRecords = StudentKnowledgeMastery::forStudent($studentId)
  631. ->weaknesses($threshold)
  632. ->orderByMastery('asc')
  633. ->limit(20)
  634. ->with('knowledgePoint') // 预加载知识点信息
  635. ->get();
  636. // 转换为统一格式
  637. return $weaknessRecords->map(function ($record) {
  638. return [
  639. 'kp_code' => $record->kp_code,
  640. 'kp_name' => $record->knowledgePoint->name ?? $record->kp_code,
  641. 'mastery' => (float) ($record->mastery_level ?? 0),
  642. 'attempts' => (int) ($record->total_attempts ?? 0),
  643. 'correct' => (int) ($record->correct_attempts ?? 0),
  644. 'incorrect' => (int) ($record->incorrect_attempts ?? 0),
  645. 'confidence' => (float) ($record->confidence_level ?? 0),
  646. 'trend' => $record->mastery_trend ?? 'stable',
  647. ];
  648. })->toArray();
  649. } catch (\Exception $e) {
  650. Log::error('ExamTypeStrategy: 获取学生薄弱点失败', [
  651. 'student_id' => $studentId,
  652. 'threshold' => $threshold,
  653. 'error' => $e->getMessage()
  654. ]);
  655. return [];
  656. }
  657. }
  658. /**
  659. * 智能组卷 (assembleType=1)
  660. * 根据 textbook_id 查询章节,获取知识点,然后组卷
  661. * 增加年级概念选题逻辑
  662. */
  663. private function buildIntelligentAssembleParams(array $params): array
  664. {
  665. Log::info('ExamTypeStrategy: 构建智能组卷参数', $params);
  666. $textbookId = $params['textbook_id'] ?? null;
  667. $grade = $params['grade'] ?? null; // 年级信息
  668. $totalQuestions = $params['total_questions'] ?? 20;
  669. if (!$textbookId) {
  670. Log::warning('ExamTypeStrategy: 智能组卷需要 textbook_id 参数');
  671. return $this->buildGeneralParams($params);
  672. }
  673. // 第一步:根据 textbook_id 查询章节
  674. $catalogChapterIds = $this->getTextbookChapterIds($textbookId);
  675. if (empty($catalogChapterIds)) {
  676. Log::warning('ExamTypeStrategy: 未找到课本章节', ['textbook_id' => $textbookId]);
  677. return $this->buildGeneralParams($params);
  678. }
  679. Log::info('ExamTypeStrategy: 获取到课本章节', [
  680. 'textbook_id' => $textbookId,
  681. 'chapter_count' => count($catalogChapterIds)
  682. ]);
  683. // 第二步:根据章节ID查询知识点关联
  684. $kpCodes = $this->getKnowledgePointsFromChapters($catalogChapterIds, 25);
  685. if (empty($kpCodes)) {
  686. Log::warning('ExamTypeStrategy: 未找到知识点关联', [
  687. 'textbook_id' => $textbookId,
  688. 'chapter_ids' => $catalogChapterIds
  689. ]);
  690. return $this->buildGeneralParams($params);
  691. }
  692. Log::info('ExamTypeStrategy: 获取到知识点', [
  693. 'kp_count' => count($kpCodes),
  694. 'kp_codes' => array_slice($kpCodes, 0, 5) // 只记录前5个
  695. ]);
  696. // 组装增强参数
  697. $enhanced = array_merge($params, [
  698. 'kp_codes' => $kpCodes,
  699. 'textbook_id' => $textbookId,
  700. 'grade' => $grade,
  701. 'catalog_chapter_ids' => $catalogChapterIds,
  702. 'paper_name' => $params['paper_name'] ?? ('智能组卷_' . now()->format('Ymd_His')),
  703. // 智能组卷:平衡的题型和难度配比
  704. 'question_type_ratio' => [
  705. '选择题' => 40,
  706. '填空题' => 30,
  707. '解答题' => 30,
  708. ],
  709. 'difficulty_ratio' => [
  710. '基础' => 25,
  711. '中等' => 50,
  712. '拔高' => 25,
  713. ],
  714. 'question_category' => 0, // question_category=0 代表普通题目(智能组卷)
  715. 'is_intelligent_assemble' => true,
  716. ]);
  717. Log::info('ExamTypeStrategy: 智能组卷参数构建完成', [
  718. 'textbook_id' => $textbookId,
  719. 'grade' => $grade,
  720. 'kp_count' => count($kpCodes),
  721. 'total_questions' => $totalQuestions
  722. ]);
  723. return $enhanced;
  724. }
  725. /**
  726. * 知识点组卷 (assembleType=2)
  727. * 直接根据 kp_code_list 查询题目,排除已做过的题目
  728. */
  729. private function buildKnowledgePointAssembleParams(array $params): array
  730. {
  731. Log::info('ExamTypeStrategy: 构建知识点组卷参数', $params);
  732. $kpCodeList = $params['kp_code_list'] ?? [];
  733. $studentId = $params['student_id'] ?? null;
  734. $totalQuestions = $params['total_questions'] ?? 20;
  735. if (empty($kpCodeList)) {
  736. Log::warning('ExamTypeStrategy: 知识点组卷需要 kp_code_list 参数');
  737. return $this->buildGeneralParams($params);
  738. }
  739. Log::info('ExamTypeStrategy: 知识点组卷', [
  740. 'kp_code_list' => $kpCodeList,
  741. 'student_id' => $studentId,
  742. 'total_questions' => $totalQuestions
  743. ]);
  744. // 如果有学生ID,获取已做过的题目ID列表(用于排除)
  745. $answeredQuestionIds = [];
  746. if ($studentId) {
  747. $answeredQuestionIds = $this->getStudentAnsweredQuestionIds($studentId, $kpCodeList);
  748. Log::info('ExamTypeStrategy: 获取学生已答题目', [
  749. 'student_id' => $studentId,
  750. 'answered_count' => count($answeredQuestionIds)
  751. ]);
  752. }
  753. // 组装增强参数
  754. $enhanced = array_merge($params, [
  755. 'kp_codes' => $kpCodeList,
  756. 'exclude_question_ids' => $answeredQuestionIds,
  757. 'paper_name' => $params['paper_name'] ?? ('知识点组卷_' . now()->format('Ymd_His')),
  758. // 知识点组卷:注重题型平衡(恢复原有配比)
  759. 'question_type_ratio' => [
  760. '选择题' => 35,
  761. '填空题' => 30,
  762. '解答题' => 35,
  763. ],
  764. 'difficulty_ratio' => [
  765. '基础' => 25,
  766. '中等' => 50,
  767. '拔高' => 25,
  768. ],
  769. 'question_category' => 0, // question_category=0 代表普通题目
  770. 'is_knowledge_point_assemble' => true,
  771. ]);
  772. Log::info('ExamTypeStrategy: 知识点组卷参数构建完成', [
  773. 'kp_count' => count($kpCodeList),
  774. 'exclude_count' => count($answeredQuestionIds),
  775. 'total_questions' => $totalQuestions
  776. ]);
  777. return $enhanced;
  778. }
  779. /**
  780. * 教材组卷 (assembleType=3)
  781. * 根据 chapter_id_list 查询课本章节,获取知识点,然后组卷
  782. * 优化:按textbook_catalog_node_id筛选题目,添加章节知识点数量统计
  783. */
  784. private function buildTextbookAssembleParams(array $params): array
  785. {
  786. Log::info('ExamTypeStrategy: 构建教材组卷参数', $params);
  787. $chapterIdList = $params['chapter_id_list'] ?? [];
  788. $studentId = $params['student_id'] ?? null;
  789. $totalQuestions = $params['total_questions'] ?? 20;
  790. // 【优化】如果用户没有指定章节,自动从教材所有有题目的章节中选择
  791. if (empty($chapterIdList) && !empty($params['textbook_id'])) {
  792. Log::info('ExamTypeStrategy: 用户未指定章节,自动从教材选择', [
  793. 'textbook_id' => $params['textbook_id']
  794. ]);
  795. // 【修复】先查询教材下的所有章节,再筛选有题目的章节
  796. // 步骤1:根据textbook_id获取该教材下的所有章节ID
  797. $allChapterIds = DB::table('textbook_catalog_nodes')
  798. ->where('textbook_id', $params['textbook_id'])
  799. ->where('node_type', 'section')
  800. ->pluck('id')
  801. ->toArray();
  802. if (empty($allChapterIds)) {
  803. Log::warning('ExamTypeStrategy: 教材下未找到章节', [
  804. 'textbook_id' => $params['textbook_id']
  805. ]);
  806. } else {
  807. // 步骤2:从这些章节中筛选出有题目的章节
  808. $chapterIdList = DB::table('questions')
  809. ->whereIn('textbook_catalog_nodes_id', $allChapterIds)
  810. ->whereNotNull('textbook_catalog_nodes_id')
  811. ->where('textbook_catalog_nodes_id', '!=', '')
  812. ->distinct()
  813. ->pluck('textbook_catalog_nodes_id')
  814. ->toArray();
  815. Log::info('ExamTypeStrategy: 自动选择的章节列表', [
  816. 'textbook_id' => $params['textbook_id'],
  817. 'total_chapters' => count($allChapterIds),
  818. 'chapters_with_questions' => count($chapterIdList),
  819. 'chapter_ids' => $chapterIdList
  820. ]);
  821. }
  822. }
  823. // 【新增】如果用户指定了章节,解析章节节点类型并获取所有section/subsection节点
  824. if (!empty($chapterIdList)) {
  825. Log::info('ExamTypeStrategy: 用户指定了章节,开始解析节点类型', [
  826. 'input_chapter_ids' => $chapterIdList
  827. ]);
  828. // 解析用户传入的chapter_id_list,获取所有section/subsection节点
  829. $resolvedSectionIds = $this->resolveSectionNodesFromChapters($chapterIdList);
  830. if (!empty($resolvedSectionIds)) {
  831. // 使用解析后的section/subsection节点ID替换原有的chapterIdList
  832. $originalChapterCount = count($chapterIdList);
  833. $chapterIdList = $resolvedSectionIds;
  834. Log::info('ExamTypeStrategy: 章节节点解析完成,使用解析后的节点', [
  835. 'original_count' => $originalChapterCount,
  836. 'resolved_count' => count($chapterIdList),
  837. 'resolved_ids' => $chapterIdList
  838. ]);
  839. } else {
  840. Log::warning('ExamTypeStrategy: 章节节点解析失败,使用原始节点列表', [
  841. 'chapter_id_list' => $chapterIdList
  842. ]);
  843. }
  844. }
  845. if (empty($chapterIdList)) {
  846. Log::warning('ExamTypeStrategy: 教材组卷需要 chapter_id_list 参数或有效的textbook_id');
  847. return $this->buildGeneralParams($params);
  848. }
  849. Log::info('ExamTypeStrategy: 教材组卷', [
  850. 'chapter_id_list' => $chapterIdList,
  851. 'student_id' => $studentId,
  852. 'total_questions' => $totalQuestions
  853. ]);
  854. // 【修复】第一步:根据章节ID查询知识点关联,并统计每个章节的知识点数量
  855. $kpCodes = $this->getKnowledgePointsFromChapters($chapterIdList);
  856. // 【新增】获取每个章节对应的知识点数量统计
  857. $chapterKnowledgePointStats = $this->getChapterKnowledgePointStats($chapterIdList);
  858. Log::info('ExamTypeStrategy: 获取章节知识点统计', [
  859. 'chapter_stats' => $chapterKnowledgePointStats,
  860. 'total_chapters' => count($chapterIdList)
  861. ]);
  862. // 【重要】教材组卷严格限制知识点数量,不进行任何扩展
  863. if (empty($kpCodes)) {
  864. Log::warning('ExamTypeStrategy: 未找到章节知识点关联,但保留章节筛选参数', [
  865. 'chapter_id_list' => $chapterIdList,
  866. 'note' => '将在LearningAnalyticsService中按textbook_catalog_nodes_id字段筛选题目'
  867. ]);
  868. } else {
  869. Log::info('ExamTypeStrategy: 获取章节知识点(教材组卷严格限制)', [
  870. 'kp_count' => count($kpCodes),
  871. 'kp_codes' => $kpCodes,
  872. 'note' => '教材组卷只返回章节关联的知识点,不进行扩展'
  873. ]);
  874. }
  875. // 第二步:如果有学生ID,获取已做过的题目ID列表(用于排除)
  876. $answeredQuestionIds = [];
  877. if ($studentId) {
  878. $answeredQuestionIds = $this->getStudentAnsweredQuestionIds($studentId, $kpCodes);
  879. Log::info('ExamTypeStrategy: 获取学生已答题目', [
  880. 'student_id' => $studentId,
  881. 'answered_count' => count($answeredQuestionIds)
  882. ]);
  883. }
  884. // 【优化】第三步:按textbook_catalog_node_id筛选题目,添加筛选条件
  885. // 在LearningAnalyticsService中会使用这些参数进行题目筛选
  886. $textbookCatalogNodeIds = $chapterIdList; // 直接使用章节ID作为textbook_catalog_node_id筛选条件
  887. // 组装增强参数
  888. $enhanced = array_merge($params, [
  889. 'kp_codes' => $kpCodes, // 可能为空,但仍保留
  890. 'chapter_id_list' => $chapterIdList,
  891. 'textbook_catalog_node_ids' => $textbookCatalogNodeIds, // 【重要】即使kpCodes为空也设置此参数
  892. 'exclude_question_ids' => $answeredQuestionIds,
  893. 'paper_name' => $params['paper_name'] ?? ('教材组卷_' . now()->format('Ymd_His')),
  894. // 教材组卷:按教材特点分配题型
  895. 'question_type_ratio' => [
  896. '选择题' => 40,
  897. '填空题' => 30,
  898. '解答题' => 30,
  899. ],
  900. 'difficulty_ratio' => [
  901. '基础' => 25,
  902. '中等' => 50,
  903. '拔高' => 25,
  904. ],
  905. 'question_category' => 0, // question_category=0 代表普通题目
  906. 'is_textbook_assemble' => true,
  907. // 【新增】章节知识点数量统计
  908. 'chapter_knowledge_point_stats' => $chapterKnowledgePointStats,
  909. ]);
  910. Log::info('ExamTypeStrategy: 教材组卷参数构建完成', [
  911. 'chapter_count' => count($chapterIdList),
  912. 'kp_count' => count($kpCodes),
  913. 'exclude_count' => count($answeredQuestionIds),
  914. 'total_questions' => $totalQuestions,
  915. 'chapter_stats' => $chapterKnowledgePointStats
  916. ]);
  917. return $enhanced;
  918. }
  919. /**
  920. * 根据课本ID获取章节ID列表
  921. * @param int $textbookId 教材ID
  922. * @param int|null $endCatalogId 截止章节ID(仅摸底使用),只返回该章节及之前的章节
  923. */
  924. private function getTextbookChapterIds(int $textbookId, ?int $endCatalogId = null): array
  925. {
  926. try {
  927. $query = DB::table('textbook_catalog_nodes')
  928. ->where('textbook_id', $textbookId)
  929. ->where('node_type', 'section') // nodeType='section'
  930. ->orderBy('sort_order');
  931. // 如果指定了截止章节,只获取该章节及之前的章节
  932. if ($endCatalogId) {
  933. $endSortOrder = DB::table('textbook_catalog_nodes')
  934. ->where('id', $endCatalogId)
  935. ->value('sort_order');
  936. if ($endSortOrder !== null) {
  937. $query->where('sort_order', '<=', $endSortOrder);
  938. Log::debug('ExamTypeStrategy: 应用截止章节过滤', [
  939. 'end_catalog_id' => $endCatalogId,
  940. 'end_sort_order' => $endSortOrder
  941. ]);
  942. } else {
  943. Log::warning('ExamTypeStrategy: 截止章节ID无效', [
  944. 'end_catalog_id' => $endCatalogId
  945. ]);
  946. }
  947. }
  948. $chapterIds = $query->pluck('id')->toArray();
  949. Log::debug('ExamTypeStrategy: 查询课本章节ID', [
  950. 'textbook_id' => $textbookId,
  951. 'end_catalog_id' => $endCatalogId,
  952. 'found_count' => count($chapterIds)
  953. ]);
  954. return $chapterIds;
  955. } catch (\Exception $e) {
  956. Log::error('ExamTypeStrategy: 查询课本章节ID失败', [
  957. 'textbook_id' => $textbookId,
  958. 'error' => $e->getMessage()
  959. ]);
  960. return [];
  961. }
  962. }
  963. /**
  964. * 根据章节ID列表获取知识点代码列表(均等抽样版本)
  965. * 使用"知识点均等抽样"算法,确保覆盖全书章节
  966. *
  967. * @param array $chapterIds 章节ID列表
  968. * @param int $limit 目标题目数量(默认25)
  969. * @return array 抽样后的知识点代码列表
  970. */
  971. private function getKnowledgePointsFromChapters(array $chapterIds, int $limit = 25): array
  972. {
  973. try {
  974. // 如果章节数较少,使用原有逻辑
  975. if (count($chapterIds) <= 5) {
  976. Log::info('ExamTypeStrategy: 章节数较少,使用原有逻辑', [
  977. 'chapter_count' => count($chapterIds)
  978. ]);
  979. return $this->getKnowledgePointsFromChaptersLegacy($chapterIds, $limit);
  980. }
  981. // ========== 步骤1: 构建全量有序池 ==========
  982. // 查询所有知识点,按章节顺序排列,去重后得到有序数组
  983. $allKpData = DB::table('textbook_chapter_knowledge_relation as tckr')
  984. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  985. ->whereIn('tckr.catalog_chapter_id', $chapterIds)
  986. ->select('tckr.kp_code', 'tcn.sort_order', 'tcn.id as chapter_id', 'tcn.title as chapter_title')
  987. ->orderBy('tcn.sort_order', 'asc')
  988. ->orderBy('tckr.kp_code', 'asc')
  989. ->get();
  990. // 去重并构建有序数组
  991. $allKpCodes = [];
  992. $chapterInfo = [];
  993. foreach ($allKpData as $row) {
  994. if (!in_array($row->kp_code, $allKpCodes)) {
  995. $allKpCodes[] = $row->kp_code;
  996. $chapterInfo[$row->kp_code] = [
  997. 'chapter_id' => $row->chapter_id,
  998. 'chapter_title' => $row->chapter_title,
  999. 'sort_order' => $row->sort_order
  1000. ];
  1001. }
  1002. }
  1003. $totalKps = count($allKpCodes);
  1004. Log::info('ExamTypeStrategy: 构建全量有序池完成', [
  1005. 'chapter_count' => count($chapterIds),
  1006. 'total_knowledge_points' => $totalKps,
  1007. 'target_questions' => $limit
  1008. ]);
  1009. // ========== 步骤2: 计算抽样步长 ==========
  1010. $step = $totalKps > 0 ? $totalKps / $limit : 1;
  1011. Log::info('ExamTypeStrategy: 计算抽样步长', [
  1012. 'step' => $step
  1013. ]);
  1014. // ========== 步骤3: 等距取样 ==========
  1015. $selectedKps = [];
  1016. $selectedCount = 0;
  1017. $currentIndex = 0;
  1018. while ($selectedCount < $limit && $selectedCount < $totalKps) {
  1019. $index = (int) floor($currentIndex);
  1020. if ($index < $totalKps && isset($allKpCodes[$index])) {
  1021. $kpCode = $allKpCodes[$index];
  1022. if (!in_array($kpCode, $selectedKps)) {
  1023. $selectedKps[] = $kpCode;
  1024. $selectedCount++;
  1025. }
  1026. }
  1027. $currentIndex += $step;
  1028. }
  1029. // 如果数量不足,循环取样
  1030. if (count($selectedKps) < $limit && $totalKps > 0) {
  1031. Log::info('ExamTypeStrategy: 第一次抽样不足,进行循环取样', [
  1032. 'selected_count' => count($selectedKps),
  1033. 'target_count' => $limit
  1034. ]);
  1035. $needed = $limit - count($selectedKps);
  1036. $startIndex = 0;
  1037. for ($i = 0; $i < $needed && count($selectedKps) < $limit; $i++) {
  1038. $index = ($startIndex + $i) % $totalKps;
  1039. $kpCode = $allKpCodes[$index];
  1040. if (!in_array($kpCode, $selectedKps)) {
  1041. $selectedKps[] = $kpCode;
  1042. }
  1043. }
  1044. }
  1045. // ========== 步骤4: 记录抽样统计 ==========
  1046. $chapterDistribution = [];
  1047. foreach ($selectedKps as $kpCode) {
  1048. if (isset($chapterInfo[$kpCode])) {
  1049. $chapterId = $chapterInfo[$kpCode]['chapter_id'];
  1050. if (!isset($chapterDistribution[$chapterId])) {
  1051. $chapterDistribution[$chapterId] = [
  1052. 'count' => 0,
  1053. 'title' => $chapterInfo[$kpCode]['chapter_title']
  1054. ];
  1055. }
  1056. $chapterDistribution[$chapterId]['count']++;
  1057. }
  1058. }
  1059. Log::info('ExamTypeStrategy: 等距抽样完成', [
  1060. 'total_kps' => $totalKps,
  1061. 'selected_kps' => count($selectedKps),
  1062. 'step' => $step,
  1063. 'chapter_distribution' => $chapterDistribution,
  1064. 'sample_kp_codes' => array_slice($selectedKps, 0, 10)
  1065. ]);
  1066. return array_filter($selectedKps);
  1067. } catch (\Exception $e) {
  1068. Log::error('ExamTypeStrategy: 均等抽样获取章节知识点失败,使用原有逻辑', [
  1069. 'chapter_ids' => $chapterIds,
  1070. 'error' => $e->getMessage()
  1071. ]);
  1072. // 失败时回退到原有逻辑
  1073. return $this->getKnowledgePointsFromChaptersLegacy($chapterIds, $limit);
  1074. }
  1075. }
  1076. /**
  1077. * 原有逻辑(保留作为回退方案)
  1078. * 修复:解决DISTINCT和ORDER BY冲突问题
  1079. */
  1080. private function getKnowledgePointsFromChaptersLegacy(array $chapterIds, int $limit = 25): array
  1081. {
  1082. try {
  1083. // 修复方案1:使用GROUP BY替代DISTINCT,并选择需要的字段
  1084. $kpCodes = DB::table('textbook_chapter_knowledge_relation as tckr')
  1085. ->leftJoin('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  1086. ->whereIn('tckr.catalog_chapter_id', $chapterIds)
  1087. ->select('tckr.kp_code', 'tcn.sort_order')
  1088. ->orderBy('tcn.sort_order', 'asc')
  1089. ->orderBy('tckr.kp_code', 'asc')
  1090. ->limit($limit)
  1091. ->groupBy('tckr.kp_code')
  1092. ->pluck('tckr.kp_code')
  1093. ->toArray();
  1094. Log::debug('ExamTypeStrategy: 查询章节知识点(原有逻辑)', [
  1095. 'chapter_count' => count($chapterIds),
  1096. 'found_kp_count' => count($kpCodes)
  1097. ]);
  1098. return array_filter($kpCodes); // 移除空值
  1099. } catch (\Exception $e) {
  1100. Log::error('ExamTypeStrategy: 查询章节知识点失败', [
  1101. 'chapter_ids' => $chapterIds,
  1102. 'error' => $e->getMessage()
  1103. ]);
  1104. return [];
  1105. }
  1106. }
  1107. /**
  1108. * 获取学生已答题目ID列表(用于排除)
  1109. */
  1110. private function getStudentAnsweredQuestionIds(string $studentId, array $kpCodes): array
  1111. {
  1112. try {
  1113. // 【修复】查询 student_answer_questions 表,不使用 kp_code 过滤(该字段可能不存在)
  1114. $query = DB::table('student_answer_questions')
  1115. ->where('student_id', $studentId)
  1116. ->distinct();
  1117. // 如果有 question_id 字段,直接查询
  1118. $questionIds = $query->pluck('question_id')->toArray();
  1119. Log::debug('ExamTypeStrategy: 查询学生已答题目', [
  1120. 'student_id' => $studentId,
  1121. 'kp_count' => count($kpCodes),
  1122. 'answered_count' => count($questionIds),
  1123. 'note' => '只按学生ID过滤,不按kp_code过滤'
  1124. ]);
  1125. return array_filter($questionIds); // 移除空值
  1126. } catch (\Exception $e) {
  1127. Log::error('ExamTypeStrategy: 查询学生已答题目失败', [
  1128. 'student_id' => $studentId,
  1129. 'error' => $e->getMessage()
  1130. ]);
  1131. return [];
  1132. }
  1133. }
  1134. /**
  1135. * 通过卷子ID列表查询错题
  1136. * 注意:paper_ids 使用的是 papers 表中的 paper_id 字段,不是 id 字段
  1137. * 错题数据从 mistake_records 表中获取,该表已包含 paper_id 字段
  1138. * 注意:不按学生ID过滤,因为卷子可能包含其他同学的错题,需要收集所有错题
  1139. */
  1140. private function getMistakeQuestionsFromPapers(array $paperIds, ?string $studentId = null): array
  1141. {
  1142. try {
  1143. // 使用 Eloquent 模型查询,从 mistake_records 表中获取错题记录
  1144. // 不按 student_id 过滤,因为要收集所有学生的错题
  1145. $mistakeRecords = MistakeRecord::query()
  1146. ->whereIn('paper_id', $paperIds)
  1147. ->get();
  1148. if ($mistakeRecords->isEmpty()) {
  1149. Log::warning('ExamTypeStrategy: 卷子中未找到错题记录', [
  1150. 'paper_ids' => $paperIds
  1151. ]);
  1152. return [];
  1153. }
  1154. // 收集所有错题的 question_id
  1155. $questionIds = $mistakeRecords->pluck('question_id')
  1156. ->filter()
  1157. ->unique()
  1158. ->values()
  1159. ->toArray();
  1160. Log::info('ExamTypeStrategy: 查询卷子错题完成', [
  1161. 'paper_count' => count($paperIds),
  1162. 'paper_ids_input' => $paperIds,
  1163. 'mistake_record_count' => $mistakeRecords->count(),
  1164. 'unique_question_count' => count($questionIds),
  1165. 'question_ids' => array_slice($questionIds, 0, 20), // 最多记录20个ID
  1166. 'per_paper_stats' => $mistakeRecords->groupBy('paper_id')->map->count()->toArray()
  1167. ]);
  1168. return array_filter($questionIds);
  1169. } catch (\Exception $e) {
  1170. Log::error('ExamTypeStrategy: 查询卷子错题失败', [
  1171. 'paper_ids' => $paperIds,
  1172. 'error' => $e->getMessage()
  1173. ]);
  1174. return [];
  1175. }
  1176. }
  1177. /**
  1178. * 通过题目ID列表获取知识点代码列表
  1179. */
  1180. private function getKnowledgePointsFromQuestions(array $questionIds): array
  1181. {
  1182. try {
  1183. // 使用 Eloquent 模型查询,获取题目的知识点
  1184. $questions = Question::whereIn('id', $questionIds)
  1185. ->whereNotNull('kp_code')
  1186. ->where('kp_code', '!=', '')
  1187. ->distinct()
  1188. ->pluck('kp_code')
  1189. ->toArray();
  1190. Log::debug('ExamTypeStrategy: 查询题目知识点', [
  1191. 'question_count' => count($questionIds),
  1192. 'kp_count' => count($questions)
  1193. ]);
  1194. return array_filter($questions);
  1195. } catch (\Exception $e) {
  1196. Log::error('ExamTypeStrategy: 查询题目知识点失败', [
  1197. 'question_ids' => array_slice($questionIds, 0, 10), // 只记录前10个
  1198. 'error' => $e->getMessage()
  1199. ]);
  1200. return [];
  1201. }
  1202. }
  1203. /**
  1204. * 【新增】获取每个章节对应的知识点数量统计
  1205. * 通过textbook_chapter_knowledge_relation表关联查询
  1206. *
  1207. * @param array $chapterIdList 章节ID列表
  1208. * @return array 章节知识点数量统计
  1209. */
  1210. private function getChapterKnowledgePointStats(array $chapterIdList): array
  1211. {
  1212. try {
  1213. // 查询每个章节对应的知识点数量
  1214. $stats = DB::table('textbook_chapter_knowledge_relation as tckr')
  1215. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  1216. ->whereIn('tckr.catalog_chapter_id', $chapterIdList)
  1217. ->select(
  1218. 'tckr.catalog_chapter_id as chapter_id',
  1219. 'tcn.title as chapter_title',
  1220. DB::raw('COUNT(DISTINCT tckr.kp_code) as knowledge_point_count')
  1221. )
  1222. ->groupBy('tckr.catalog_chapter_id', 'tcn.title')
  1223. ->orderBy('tckr.catalog_chapter_id')
  1224. ->get();
  1225. // 转换为数组格式
  1226. $result = [];
  1227. foreach ($stats as $stat) {
  1228. $result[] = [
  1229. 'chapter_id' => $stat->chapter_id,
  1230. 'chapter_title' => $stat->chapter_title,
  1231. 'knowledge_point_count' => (int) $stat->knowledge_point_count
  1232. ];
  1233. }
  1234. Log::debug('ExamTypeStrategy: 获取章节知识点统计', [
  1235. 'chapter_count' => count($chapterIdList),
  1236. 'stats_count' => count($result),
  1237. 'stats' => $result
  1238. ]);
  1239. return $result;
  1240. } catch (\Exception $e) {
  1241. Log::error('ExamTypeStrategy: 获取章节知识点统计失败', [
  1242. 'chapter_id_list' => $chapterIdList,
  1243. 'error' => $e->getMessage()
  1244. ]);
  1245. // 返回空数组,不影响组卷流程
  1246. return [];
  1247. }
  1248. }
  1249. /**
  1250. * 【新增】递归获取section节点ID列表
  1251. * 根据用户传入的chapter_id_list,自动识别节点类型:
  1252. * - 如果是chapter节点,查找其下的所有section子节点(不包含subsection)
  1253. * - 如果是section节点,直接使用
  1254. *
  1255. * @param array $chapterIdList 用户传入的章节ID列表
  1256. * @return array 最终用于查询知识点的section节点ID列表
  1257. */
  1258. private function resolveSectionNodesFromChapters(array $chapterIdList): array
  1259. {
  1260. try {
  1261. if (empty($chapterIdList)) {
  1262. return [];
  1263. }
  1264. Log::info('ExamTypeStrategy: 开始解析章节节点', [
  1265. 'input_chapter_ids' => $chapterIdList
  1266. ]);
  1267. $finalSectionIds = [];
  1268. foreach ($chapterIdList as $nodeId) {
  1269. // 查询节点信息
  1270. $node = DB::table('textbook_catalog_nodes')
  1271. ->where('id', $nodeId)
  1272. ->first();
  1273. if (!$node) {
  1274. Log::warning('ExamTypeStrategy: 未找到节点', ['node_id' => $nodeId]);
  1275. continue;
  1276. }
  1277. Log::debug('ExamTypeStrategy: 处理节点', [
  1278. 'node_id' => $nodeId,
  1279. 'node_type' => $node->node_type,
  1280. 'title' => $node->title
  1281. ]);
  1282. // 根据节点类型处理
  1283. switch ($node->node_type) {
  1284. case 'chapter':
  1285. // 如果是chapter节点,查找其下的所有section子节点
  1286. $childNodes = DB::table('textbook_catalog_nodes')
  1287. ->where('parent_id', $nodeId)
  1288. ->where('node_type', 'section')
  1289. ->orderBy('sort_order')
  1290. ->get();
  1291. Log::info('ExamTypeStrategy: 解析chapter节点', [
  1292. 'chapter_id' => $nodeId,
  1293. 'chapter_title' => $node->title,
  1294. 'section_count' => count($childNodes)
  1295. ]);
  1296. foreach ($childNodes as $child) {
  1297. if (!in_array($child->id, $finalSectionIds)) {
  1298. $finalSectionIds[] = $child->id;
  1299. Log::debug('ExamTypeStrategy: 添加section子节点', [
  1300. 'parent_chapter' => $nodeId,
  1301. 'child_node_id' => $child->id,
  1302. 'child_title' => $child->title,
  1303. 'child_type' => $child->node_type
  1304. ]);
  1305. }
  1306. }
  1307. break;
  1308. case 'section':
  1309. // 如果是section节点,直接使用
  1310. if (!in_array($nodeId, $finalSectionIds)) {
  1311. $finalSectionIds[] = $nodeId;
  1312. Log::debug('ExamTypeStrategy: 直接使用section节点', [
  1313. 'node_id' => $nodeId,
  1314. 'title' => $node->title,
  1315. 'node_type' => $node->node_type
  1316. ]);
  1317. }
  1318. break;
  1319. case 'subsection':
  1320. // 如果是subsection节点,需要找到其父级section节点
  1321. $parentSection = DB::table('textbook_catalog_nodes')
  1322. ->where('id', $node->parent_id)
  1323. ->where('node_type', 'section')
  1324. ->first();
  1325. if ($parentSection && !in_array($parentSection->id, $finalSectionIds)) {
  1326. $finalSectionIds[] = $parentSection->id;
  1327. Log::debug('ExamTypeStrategy: 通过subsection找到父级section', [
  1328. 'subsection_id' => $nodeId,
  1329. 'subsection_title' => $node->title,
  1330. 'parent_section_id' => $parentSection->id,
  1331. 'parent_section_title' => $parentSection->title
  1332. ]);
  1333. }
  1334. break;
  1335. default:
  1336. Log::warning('ExamTypeStrategy: 未知节点类型', [
  1337. 'node_id' => $nodeId,
  1338. 'node_type' => $node->node_type
  1339. ]);
  1340. break;
  1341. }
  1342. }
  1343. Log::info('ExamTypeStrategy: 章节节点解析完成', [
  1344. 'input_count' => count($chapterIdList),
  1345. 'output_section_count' => count($finalSectionIds),
  1346. 'section_ids' => $finalSectionIds
  1347. ]);
  1348. return $finalSectionIds;
  1349. } catch (\Exception $e) {
  1350. Log::error('ExamTypeStrategy: 解析章节节点失败', [
  1351. 'chapter_id_list' => $chapterIdList,
  1352. 'error' => $e->getMessage()
  1353. ]);
  1354. // 出错时返回空数组
  1355. return [];
  1356. }
  1357. }
  1358. }