ExamTypeStrategy.php 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056
  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. protected DifficultyDistributionService $difficultyDistributionService;
  16. public function __construct(
  17. QuestionExpansionService $questionExpansionService,
  18. QuestionLocalService $questionLocalService = null,
  19. DifficultyDistributionService $difficultyDistributionService = null
  20. )
  21. {
  22. $this->questionExpansionService = $questionExpansionService;
  23. $this->questionLocalService = $questionLocalService ?? app(QuestionLocalService::class);
  24. $this->difficultyDistributionService = $difficultyDistributionService ?? app(DifficultyDistributionService::class);
  25. }
  26. /**
  27. * 根据组卷类型构建参数
  28. * assembleType: 0-章节摸底, 1-智能组卷, 2-知识点组卷, 3-教材组卷, 4-通用, 5-错题本, 8-智能组卷(新), 9-原摸底
  29. *
  30. * 映射规则(前端不改,后端动态处理):
  31. * - 0, 9(摸底)→ 章节摸底(新逻辑)
  32. * - 1, 8(智能组卷)→ 按知识点顺序学习(新逻辑)
  33. * - 2, 3, 4, 5 → 保持原有逻辑不变
  34. */
  35. public function buildParams(array $baseParams, int $assembleType): array
  36. {
  37. Log::info('ExamTypeStrategy: 构建组卷参数', [
  38. 'assemble_type' => $assembleType,
  39. 'base_params_keys' => array_keys($baseParams)
  40. ]);
  41. // 映射 assembleType 到实际处理逻辑
  42. $actualType = match($assembleType) {
  43. 0, 9 => 'chapter_diagnostic', // 摸底 → 章节摸底(新逻辑)
  44. 1, 8 => 'chapter_intelligent', // 智能组卷 → 按知识点顺序学习(新逻辑)
  45. default => $assembleType // 其他保持不变
  46. };
  47. Log::info('ExamTypeStrategy: assembleType 映射', [
  48. 'original' => $assembleType,
  49. 'actual' => $actualType,
  50. ]);
  51. return match($actualType) {
  52. 'chapter_diagnostic' => $this->applyDifficultyDistribution($this->buildChapterDiagnosticParams($baseParams)), // 章节摸底(新)
  53. 'chapter_intelligent' => $this->applyDifficultyDistribution($this->buildChapterIntelligentParams($baseParams)), // 按知识点顺序学习(新)
  54. 2 => $this->applyDifficultyDistribution($this->buildKnowledgePointAssembleParams($baseParams)), // 知识点组卷(不动)
  55. 3 => $this->applyDifficultyDistribution($this->buildTextbookAssembleParams($baseParams)), // 教材组卷(不动)
  56. 4 => $this->applyDifficultyDistribution($this->buildGeneralParams($baseParams)), // 通用(不动)
  57. 5 => $this->applyDifficultyDistribution($this->buildMistakeParams($baseParams)), // 追练(不动)
  58. default => $this->applyDifficultyDistribution($this->buildGeneralParams($baseParams))
  59. };
  60. }
  61. /**
  62. * 根据组卷类型构建参数(兼容旧版 exam_type 参数)
  63. * @deprecated 使用 buildParams(array, int) 替代
  64. */
  65. public function buildParamsLegacy(array $baseParams, string $examType): array
  66. {
  67. // 兼容旧版 exam_type 参数
  68. $assembleType = match($examType) {
  69. 'diagnostic' => 9,
  70. 'general' => 4,
  71. 'practice' => 5,
  72. 'mistake' => 5,
  73. 'textbook' => 3,
  74. 'knowledge' => 2,
  75. 'knowledge_points' => 6,
  76. default => 4
  77. };
  78. return $this->buildParams($baseParams, $assembleType);
  79. }
  80. /**
  81. * 通用智能出卷(原有行为)
  82. */
  83. private function buildGeneralParams(array $params): array
  84. {
  85. Log::info('ExamTypeStrategy: 通用智能出卷参数', $params);
  86. // 返回原始参数,难度分布逻辑在 buildParams 中统一处理
  87. return $params;
  88. }
  89. /**
  90. * 应用难度系数分布逻辑
  91. * 根据 difficulty_category 参数实现分层选题策略
  92. *
  93. * @param array $params 基础参数
  94. * @param bool $forceApply 是否强制应用(默认false,不对错题本类型应用)
  95. * @return array 增强后的参数
  96. */
  97. private function applyDifficultyDistribution(array $params, bool $forceApply = false): array
  98. {
  99. // 统一应用难度分布(错题本类型也允许应用)
  100. $assembleType = (int) ($params['assemble_type'] ?? 4);
  101. $difficultyCategory = (int) ($params['difficulty_category'] ?? 1);
  102. $totalQuestions = (int) ($params['total_questions'] ?? 20);
  103. Log::info('ExamTypeStrategy: 应用难度系数分布', [
  104. 'difficulty_category' => $difficultyCategory,
  105. 'total_questions' => $totalQuestions,
  106. 'assemble_type' => $assembleType
  107. ]);
  108. // 根据难度类别计算题目分布
  109. $distribution = $this->difficultyDistributionService->calculateDistribution($difficultyCategory, $totalQuestions);
  110. // 构建难度分布配置
  111. $difficultyDistributionConfig = [
  112. 'strategy' => 'difficulty分层选题',
  113. 'category' => $difficultyCategory,
  114. 'total_questions' => $totalQuestions,
  115. 'distribution' => $distribution,
  116. 'ranges' => $this->difficultyDistributionService->getRanges($difficultyCategory),
  117. 'use_question_local_service' => true, // 标记使用新的独立方法
  118. ];
  119. $enhanced = array_merge($params, [
  120. 'difficulty_distribution_config' => $difficultyDistributionConfig,
  121. // 保留原有的 difficulty_ratio 以兼容性
  122. 'difficulty_ratio' => [
  123. '基础' => $distribution['low']['percentage'],
  124. '中等' => $distribution['medium']['percentage'],
  125. '拔高' => $distribution['high']['percentage'],
  126. ],
  127. // 启用难度分布选题标志
  128. 'enable_difficulty_distribution' => true,
  129. // 【重要】保持原始的 difficulty_category,不修改
  130. 'difficulty_category' => $difficultyCategory,
  131. ]);
  132. Log::info('ExamTypeStrategy: 难度分布应用完成', [
  133. 'category' => $difficultyCategory,
  134. 'distribution' => $distribution
  135. ]);
  136. return $enhanced;
  137. }
  138. /**
  139. * 应用难度分布到题目集合
  140. * 这是一个独立的公共方法,供外部调用
  141. *
  142. * @param array $questions 候选题目数组
  143. * @param int $totalQuestions 总题目数
  144. * @param int $difficultyCategory 难度类别 (1-4)
  145. * @param array $filters 其他筛选条件
  146. * @return array 分布后的题目
  147. */
  148. public function applyDifficultyDistributionToQuestions(array $questions, int $totalQuestions, int $difficultyCategory = 1, array $filters = []): array
  149. {
  150. Log::info('ExamTypeStrategy: 应用难度分布到题目集合', [
  151. 'total_questions' => $totalQuestions,
  152. 'difficulty_category' => $difficultyCategory,
  153. 'input_questions' => count($questions)
  154. ]);
  155. // 使用 QuestionLocalService 的独立方法
  156. return $this->questionLocalService->selectQuestionsByDifficultyDistribution(
  157. $questions,
  158. $totalQuestions,
  159. $difficultyCategory,
  160. $filters
  161. );
  162. }
  163. /**
  164. * 根据难度类别计算题目分布
  165. *
  166. * @param int $category 难度类别 (0-4)
  167. * @param int $totalQuestions 总题目数
  168. * @return array 分布配置
  169. */
  170. private function calculateDifficultyDistribution(int $category, int $totalQuestions): array
  171. {
  172. return $this->difficultyDistributionService->calculateDistribution($category, $totalQuestions);
  173. }
  174. /**
  175. * 获取难度范围配置
  176. *
  177. * @param int $category 难度类别
  178. * @return array 难度范围配置
  179. */
  180. private function getDifficultyRanges(int $category): array
  181. {
  182. return $this->difficultyDistributionService->getRanges($category);
  183. }
  184. /**
  185. * 摸底测试:评估当前水平
  186. */
  187. private function buildDiagnosticParams(array $params): array
  188. {
  189. Log::info('ExamTypeStrategy: 构建摸底测试参数', $params);
  190. $textbookId = $params['textbook_id'] ?? null;
  191. $grade = $params['grade'] ?? null;
  192. $totalQuestions = $params['total_questions'] ?? 20;
  193. $endCatalogId = $params['end_catalog_id'] ?? null; // 截止章节ID
  194. if (!$textbookId) {
  195. Log::warning('ExamTypeStrategy: 摸底测试需要 textbook_id 参数');
  196. return $this->buildGeneralParams($params);
  197. }
  198. // 第一步:根据 textbook_id 查询章节(支持截止章节过滤)
  199. $catalogChapterIds = $this->getTextbookChapterIds($textbookId, $endCatalogId);
  200. if (empty($catalogChapterIds)) {
  201. Log::warning('ExamTypeStrategy: 未找到课本章节', ['textbook_id' => $textbookId]);
  202. return $this->buildGeneralParams($params);
  203. }
  204. Log::info('ExamTypeStrategy: 获取到课本章节(摸底测试)', [
  205. 'textbook_id' => $textbookId,
  206. 'end_catalog_id' => $endCatalogId,
  207. 'chapter_count' => count($catalogChapterIds)
  208. ]);
  209. // 第二步:根据章节ID查询知识点关联
  210. $kpCodes = $this->getKnowledgePointsFromChapters($catalogChapterIds, 25);
  211. if (empty($kpCodes)) {
  212. Log::warning('ExamTypeStrategy: 未找到知识点关联', ['textbook_id' => $textbookId]);
  213. return $this->buildGeneralParams($params);
  214. }
  215. Log::info('ExamTypeStrategy: 获取到知识点(摸底测试)', [
  216. 'kp_count' => count($kpCodes),
  217. 'kp_codes' => $kpCodes,
  218. 'textbook_id' => $textbookId,
  219. 'grade' => $grade,
  220. 'note' => '知识点数量将直接影响题目多样性'
  221. ]);
  222. // 摸底测试:平衡所有难度,覆盖多个知识点
  223. // 【修复】移除硬编码难度配比,使用difficulty_category参数动态计算
  224. $enhanced = array_merge($params, [
  225. 'kp_codes' => $kpCodes,
  226. 'textbook_id' => $textbookId,
  227. 'grade' => $grade,
  228. 'catalog_chapter_ids' => $catalogChapterIds,
  229. // 题型配比:选择题多一些,便于快速评估
  230. 'question_type_ratio' => [
  231. '选择题' => 50,
  232. '填空题' => 25,
  233. '解答题' => 25,
  234. ],
  235. 'paper_name' => $params['paper_name'] ?? ('摸底测试_' . now()->format('Ymd_His')),
  236. ]);
  237. Log::info('ExamTypeStrategy: 摸底测试参数构建完成(未应用难度分布)', [
  238. 'textbook_id' => $textbookId,
  239. 'kp_count' => count($kpCodes),
  240. 'total_questions' => $totalQuestions,
  241. 'difficulty_category' => $params['difficulty_category'] ?? 1,
  242. 'note' => '将在buildParams中应用difficulty_category难度分布'
  243. ]);
  244. return $enhanced;
  245. }
  246. /**
  247. * 新摸底测试:使用教材首章知识点作为起点,复用知识点组卷逻辑
  248. */
  249. private function buildInitialDiagnosticParams(array $params): array
  250. {
  251. // Log::info('ExamTypeStrategy: 构建新摸底测试参数', $params);
  252. $diagnosticService = app(DiagnosticChapterService::class);
  253. $textbookId = $params['textbook_id'] ?? null;
  254. $grade = $params['grade'] ?? null;
  255. $totalQuestions = $params['total_questions'] ?? 20;
  256. Log::info('ExamTypeStrategy: 新摸底使用textbook_id', [
  257. 'textbook_id' => $textbookId,
  258. ]);
  259. if (!$textbookId) {
  260. Log::warning('ExamTypeStrategy: 新摸底测试需要 textbook_id 参数');
  261. return $this->buildGeneralParams($params);
  262. }
  263. $studentId = (int) ($params['student_id'] ?? 0);
  264. $initial = $diagnosticService->getFirstUnmasteredChapterKnowledgePoints((int) $textbookId, $studentId, 0.9);
  265. if (empty($initial)) {
  266. $initial = $diagnosticService->getInitialChapterKnowledgePoints((int) $textbookId);
  267. }
  268. if (empty($initial['kp_codes'])) {
  269. Log::warning('ExamTypeStrategy: 新摸底未找到首章知识点', [
  270. 'textbook_id' => $textbookId,
  271. ]);
  272. return $this->buildGeneralParams($params);
  273. }
  274. $enhanced = array_merge($params, [
  275. 'kp_code_list' => $initial['kp_codes'],
  276. 'chapter_id_list' => $initial['section_ids'],
  277. 'diagnostic_chapter_id' => $initial['chapter_id'],
  278. 'textbook_id' => $textbookId,
  279. 'grade' => $grade,
  280. 'paper_name' => $params['paper_name'] ?? ('摸底测试_' . now()->format('Ymd_His')),
  281. ]);
  282. Log::info('ExamTypeStrategy: 新摸底参数构建完成', [
  283. 'textbook_id' => $textbookId,
  284. 'chapter_id' => $initial['chapter_id'] ?? null,
  285. 'section_count' => count($initial['section_ids'] ?? []),
  286. 'kp_count' => count($initial['kp_codes'] ?? []),
  287. 'total_questions' => $totalQuestions,
  288. ]);
  289. return $this->buildKnowledgePointAssembleParams($enhanced);
  290. }
  291. /**
  292. * 追练 (assembleType=5)
  293. * 根据 paper_ids 获取卷子题目知识点列表,再按知识点组卷
  294. * 不需要 total_questions 参数
  295. */
  296. private function buildMistakeParams(array $params): array
  297. {
  298. Log::info('ExamTypeStrategy: 构建追练参数', $params);
  299. $paperIds = $params['paper_ids'] ?? [];
  300. $studentId = $params['student_id'] ?? null;
  301. // 检查是否有 paper_ids 参数
  302. if (empty($paperIds)) {
  303. Log::warning('ExamTypeStrategy: 追练需要 paper_ids 参数');
  304. return $this->buildGeneralParams($params);
  305. }
  306. Log::info('ExamTypeStrategy: 追练组卷', [
  307. 'paper_ids' => $paperIds,
  308. 'student_id' => $studentId,
  309. 'paper_count' => count($paperIds)
  310. ]);
  311. // 通过 paper_ids 查询卷子中的全部题目
  312. $paperQuestionIds = $this->getQuestionIdsFromPapers($paperIds);
  313. if (empty($paperQuestionIds)) {
  314. Log::warning('ExamTypeStrategy: 卷子题目为空,无法生成追练', [
  315. 'paper_ids' => $paperIds
  316. ]);
  317. return $this->buildGeneralParams($params);
  318. }
  319. Log::info('ExamTypeStrategy: 获取到卷子题目', [
  320. 'paper_count' => count($paperIds),
  321. 'question_count' => count($paperQuestionIds),
  322. 'question_ids' => array_slice($paperQuestionIds, 0, 10) // 只记录前10个
  323. ]);
  324. // 优先从错题记录获取知识点;若无错题则回退到卷子题目知识点
  325. $paperKnowledgePoints = $this->getMistakeKnowledgePointsFromPapers($studentId, $paperIds);
  326. $useMistakeKnowledgePoints = ! empty($paperKnowledgePoints);
  327. if (! $useMistakeKnowledgePoints) {
  328. // 获取卷子题目知识点(直接从 paper_questions.knowledge_point)
  329. $paperKnowledgePoints = $this->getKnowledgePointsFromPaperQuestions($paperIds);
  330. }
  331. // 排除错题本已有题目,避免重复出现
  332. $excludeQuestionIds = $this->getMistakeQuestionIdsFromPapers($studentId, $paperIds);
  333. Log::info('ExamTypeStrategy: 追练知识点来源', [
  334. 'student_id' => $studentId,
  335. 'paper_ids' => $paperIds,
  336. 'use_mistake_kp' => $useMistakeKnowledgePoints,
  337. 'kp_count' => count($paperKnowledgePoints),
  338. 'exclude_count' => count($excludeQuestionIds),
  339. ]);
  340. if (empty($paperKnowledgePoints)) {
  341. Log::warning('ExamTypeStrategy: 卷子题目未找到知识点,无法生成错题本', [
  342. 'paper_ids' => $paperIds,
  343. 'question_count' => count($paperQuestionIds)
  344. ]);
  345. return $this->buildGeneralParams($params);
  346. }
  347. // 取卷子中最小难度等级、最大题量与最高总分作为默认
  348. $paperStats = $this->getPaperAggregateStats($paperIds);
  349. $difficultyCategory = $paperStats['difficulty_category_min'] ?? ($params['difficulty_category'] ?? 1);
  350. $maxTotalQuestions = $paperStats['total_questions_max'] ?? null;
  351. $maxTotalScore = $paperStats['total_score_max'] ?? null;
  352. // 组装增强参数(复用知识点组卷逻辑)
  353. $questionCount = count($paperQuestionIds);
  354. $maxQuestions = 50; // 错题本最大题目数限制
  355. $targetQuestions = (int) ($maxTotalQuestions ?? $questionCount);
  356. $targetQuestions = min($targetQuestions, $maxQuestions);
  357. // 如果题量超过最大值,按上限截取
  358. if ($questionCount > $maxQuestions) {
  359. Log::warning('ExamTypeStrategy: 错题数量超过最大值限制,已截取', [
  360. 'question_count' => $questionCount,
  361. 'max_limit' => $maxQuestions,
  362. 'truncated_count' => $maxQuestions
  363. ]);
  364. $questionCount = $maxQuestions;
  365. }
  366. $enhanced = array_merge($params, [
  367. 'kp_code_list' => array_values($paperKnowledgePoints),
  368. 'paper_ids' => $paperIds,
  369. 'paper_name' => $params['paper_name'] ?? ('追练_' . now()->format('Ymd_His')),
  370. 'total_questions' => $targetQuestions, // 题目数量由卷子题目规模/参数决定
  371. 'total_score' => $maxTotalScore ?? ($params['total_score'] ?? null),
  372. 'difficulty_category' => $difficultyCategory,
  373. 'is_mistake_exam' => true,
  374. 'is_paper_based_mistake' => true, // 标记是基于卷子的错题本
  375. 'mistake_kp_source' => $useMistakeKnowledgePoints,
  376. 'exclude_question_ids' => $excludeQuestionIds,
  377. 'source_paper_question_count' => $questionCount,
  378. 'knowledge_points_count' => count($paperKnowledgePoints),
  379. 'max_questions_limit' => $maxQuestions,
  380. ]);
  381. Log::info('ExamTypeStrategy: 错题本参数构建完成(按卷子知识点)', [
  382. 'paper_count' => count($paperIds),
  383. 'question_count' => $questionCount,
  384. 'knowledge_points_count' => count($paperKnowledgePoints),
  385. 'total_questions' => $targetQuestions,
  386. 'difficulty_category' => $difficultyCategory,
  387. 'total_score' => $maxTotalScore
  388. ]);
  389. Log::debug('ExamTypeStrategy: 错题本组卷关键参数', [
  390. 'paper_ids' => $paperIds,
  391. 'kp_code_list' => array_values($paperKnowledgePoints),
  392. 'difficulty_category' => $difficultyCategory,
  393. 'total_questions' => $targetQuestions,
  394. 'total_score' => $maxTotalScore
  395. ]);
  396. return $this->buildKnowledgePointAssembleParams($enhanced);
  397. }
  398. /**
  399. * 从错题记录中获取知识点列表(按学生+卷子)
  400. */
  401. private function getMistakeKnowledgePointsFromPapers(?string $studentId, array $paperIds): array
  402. {
  403. if (empty($studentId) || empty($paperIds)) {
  404. return [];
  405. }
  406. try {
  407. $records = \App\Models\MistakeRecord::query()
  408. ->where('student_id', $studentId)
  409. ->whereIn('paper_id', $paperIds)
  410. ->get(['kp_ids']);
  411. $kpCodes = [];
  412. foreach ($records as $record) {
  413. $kpIds = $record->kp_ids;
  414. if (empty($kpIds)) {
  415. continue;
  416. }
  417. if (is_string($kpIds)) {
  418. $decoded = json_decode($kpIds, true);
  419. if (is_array($decoded)) {
  420. $kpIds = $decoded;
  421. }
  422. }
  423. if (is_array($kpIds)) {
  424. foreach ($kpIds as $kpId) {
  425. if (! empty($kpId)) {
  426. $kpCodes[$kpId] = true;
  427. }
  428. }
  429. }
  430. }
  431. return array_values(array_keys($kpCodes));
  432. } catch (\Exception $e) {
  433. Log::warning('ExamTypeStrategy: 获取错题知识点失败,回退旧逻辑', [
  434. 'student_id' => $studentId,
  435. 'paper_ids' => $paperIds,
  436. 'error' => $e->getMessage(),
  437. ]);
  438. return [];
  439. }
  440. }
  441. /**
  442. * 从错题记录中获取题目ID列表(用于排除已出现的错题)
  443. */
  444. private function getMistakeQuestionIdsFromPapers(?string $studentId, array $paperIds): array
  445. {
  446. if (empty($studentId) || empty($paperIds)) {
  447. return [];
  448. }
  449. try {
  450. return \App\Models\MistakeRecord::query()
  451. ->where('student_id', $studentId)
  452. ->whereIn('paper_id', $paperIds)
  453. ->pluck('question_id')
  454. ->filter()
  455. ->unique()
  456. ->values()
  457. ->toArray();
  458. } catch (\Exception $e) {
  459. Log::warning('ExamTypeStrategy: 获取错题题目ID失败,忽略排除', [
  460. 'student_id' => $studentId,
  461. 'paper_ids' => $paperIds,
  462. 'error' => $e->getMessage(),
  463. ]);
  464. return [];
  465. }
  466. }
  467. /**
  468. * 专项练习:针对特定技能或知识点练习
  469. */
  470. private function buildPracticeParams(array $params): array
  471. {
  472. Log::info('ExamTypeStrategy: 构建专项练习参数', $params);
  473. $studentId = $params['student_id'] ?? null;
  474. $practiceOptions = $params['practice_options'] ?? [];
  475. $weaknessThreshold = $practiceOptions['weakness_threshold'] ?? 0.7;
  476. $intensity = $practiceOptions['intensity'] ?? 'medium';
  477. $focusWeaknesses = $practiceOptions['focus_weaknesses'] ?? true;
  478. // 【修复】移除硬编码难度配比,专项练习使用difficulty_category参数
  479. // 注意:强度调节逻辑已移除,统一使用difficulty_category控制难度分布
  480. // 获取学生薄弱点
  481. $weaknessFilter = [];
  482. if ($studentId && $focusWeaknesses) {
  483. $weaknessFilter = $this->getStudentWeaknesses($studentId, $weaknessThreshold);
  484. Log::info('ExamTypeStrategy: 获取到学生薄弱点', [
  485. 'student_id' => $studentId,
  486. 'weakness_threshold' => $weaknessThreshold,
  487. 'weakness_count' => count($weaknessFilter)
  488. ]);
  489. }
  490. // 优先使用薄弱点知识点,如果没有则使用用户选择的知识点
  491. $kpCodes = $params['kp_codes'] ?? [];
  492. if ($studentId && empty($kpCodes) && !empty($weaknessFilter)) {
  493. $kpCodes = array_column($weaknessFilter, 'kp_code');
  494. Log::info('ExamTypeStrategy: 使用薄弱点作为知识点', [
  495. 'kp_codes' => $kpCodes
  496. ]);
  497. }
  498. $enhanced = array_merge($params, [
  499. 'kp_codes' => $kpCodes,
  500. // 专项练习更注重题型覆盖
  501. 'question_type_ratio' => [
  502. '选择题' => 40,
  503. '填空题' => 30,
  504. '解答题' => 30,
  505. ],
  506. 'paper_name' => $params['paper_name'] ?? ('专项练习_' . now()->format('Ymd_His')),
  507. // 标记这是专项练习,用于后续处理
  508. 'is_practice_exam' => true,
  509. 'weakness_filter' => $weaknessFilter,
  510. ]);
  511. Log::info('ExamTypeStrategy: 专项练习参数构建完成(未应用难度分布)', [
  512. 'intensity' => $intensity,
  513. 'difficulty_category' => $params['difficulty_category'] ?? 1,
  514. 'kp_codes_count' => count($enhanced['kp_codes']),
  515. 'weakness_count' => count($weaknessFilter),
  516. 'note' => '将在buildParams中应用difficulty_category难度分布'
  517. ]);
  518. return $enhanced;
  519. }
  520. /**
  521. * 教材同步:按教材章节出题
  522. */
  523. private function buildTextbookParams(array $params): array
  524. {
  525. Log::info('ExamTypeStrategy: 构建教材同步参数', $params);
  526. // 教材同步:按章节顺序,难度递增
  527. // 【修复】移除硬编码难度配比,使用difficulty_category参数
  528. $textbookOptions = $params['textbook_options'] ?? [];
  529. $enhanced = array_merge($params, [
  530. 'question_type_ratio' => [
  531. '选择题' => 40,
  532. '填空题' => 30,
  533. '解答题' => 30,
  534. ],
  535. 'paper_name' => $params['paper_name'] ?? ('教材同步_' . now()->format('Ymd_His')),
  536. 'textbook_options' => $textbookOptions,
  537. ]);
  538. Log::info('ExamTypeStrategy: 教材同步参数构建完成(未应用难度分布)', [
  539. 'difficulty_category' => $params['difficulty_category'] ?? 1,
  540. 'note' => '将在buildParams中应用difficulty_category难度分布'
  541. ]);
  542. return $enhanced;
  543. }
  544. /**
  545. * 知识点专练:单个或少量知识点深练
  546. */
  547. private function buildKnowledgeParams(array $params): array
  548. {
  549. Log::info('ExamTypeStrategy: 构建知识点专练参数', $params);
  550. // 知识点专练:深度挖掘,多角度考查
  551. // 【修复】移除硬编码难度配比,使用difficulty_category参数
  552. $knowledgeOptions = $params['knowledge_options'] ?? [];
  553. $enhanced = array_merge($params, [
  554. 'question_type_ratio' => [
  555. '选择题' => 30,
  556. '填空题' => 35,
  557. '解答题' => 35,
  558. ],
  559. 'paper_name' => $params['paper_name'] ?? ('知识点专练_' . now()->format('Ymd_His')),
  560. 'knowledge_options' => $knowledgeOptions,
  561. ]);
  562. Log::info('ExamTypeStrategy: 知识点专练参数构建完成(未应用难度分布)', [
  563. 'difficulty_category' => $params['difficulty_category'] ?? 1,
  564. 'note' => '将在buildParams中应用difficulty_category难度分布'
  565. ]);
  566. return $enhanced;
  567. }
  568. /**
  569. * 按知识点组卷:根据指定知识点数组智能选题
  570. * 优先级策略:
  571. * 1. 直接关联知识点题目(来自输入数组)
  572. * 2. 相同知识点其他题目
  573. * 3. 子知识点题目(下探1层)
  574. * 4. 薄弱点题目比例调整
  575. * 5. 子知识点题目(下探2层)
  576. */
  577. private function buildKnowledgePointsParams(array $params): array
  578. {
  579. Log::info('ExamTypeStrategy: 构建按知识点组卷参数', $params);
  580. $studentId = $params['student_id'] ?? null;
  581. $totalQuestions = $params['total_questions'] ?? 20;
  582. $knowledgePointsOptions = $params['knowledge_points_options'] ?? [];
  583. $weaknessThreshold = $knowledgePointsOptions['weakness_threshold'] ?? 0.7;
  584. $focusWeaknesses = $knowledgePointsOptions['focus_weaknesses'] ?? true;
  585. $intensity = $knowledgePointsOptions['intensity'] ?? 'medium';
  586. // 获取用户指定的知识点数组
  587. $targetKnowledgePoints = $params['kp_codes'] ?? [];
  588. if (empty($targetKnowledgePoints)) {
  589. Log::warning('ExamTypeStrategy: 未指定知识点数组,使用默认策略');
  590. return $this->buildGeneralParams($params);
  591. }
  592. Log::info('ExamTypeStrategy: 目标知识点数组', [
  593. 'target_knowledge_points' => $targetKnowledgePoints,
  594. 'count' => count($targetKnowledgePoints)
  595. ]);
  596. // 根据强度调整难度配比
  597. $difficultyRatio = match($intensity) {
  598. 'low' => [
  599. '基础' => 60,
  600. '中等' => 35,
  601. '拔高' => 5,
  602. ],
  603. 'medium' => [
  604. '基础' => 45,
  605. '中等' => 40,
  606. '拔高' => 15,
  607. ],
  608. 'high' => [
  609. '基础' => 30,
  610. '中等' => 45,
  611. '拔高' => 25,
  612. ],
  613. default => [
  614. '基础' => 45,
  615. '中等' => 40,
  616. '拔高' => 15,
  617. ]
  618. };
  619. // 获取学生薄弱点(用于判断目标知识点是否为薄弱点)
  620. $weaknessFilter = [];
  621. if ($studentId && $focusWeaknesses) {
  622. $weaknessFilter = $this->getStudentWeaknesses($studentId, $weaknessThreshold);
  623. Log::info('ExamTypeStrategy: 获取到学生薄弱点', [
  624. 'student_id' => $studentId,
  625. 'weakness_threshold' => $weaknessThreshold,
  626. 'weakness_count' => count($weaknessFilter)
  627. ]);
  628. }
  629. // 检查目标知识点中哪些是薄弱点
  630. $weaknessKpCodes = array_column($weaknessFilter, 'kp_code');
  631. $targetWeaknessKps = array_intersect($targetKnowledgePoints, $weaknessKpCodes);
  632. Log::info('ExamTypeStrategy: 目标知识点中的薄弱点', [
  633. 'target_weakness_kps' => $targetWeaknessKps,
  634. 'weakness_count' => count($targetWeaknessKps)
  635. ]);
  636. // 使用 QuestionExpansionService 按知识点优先级扩展题目
  637. // 修改 expandQuestions 支持直接传入知识点数组
  638. $questionStrategy = $this->questionExpansionService->expandQuestionsByKnowledgePoints(
  639. $params,
  640. $studentId,
  641. $targetKnowledgePoints,
  642. $weaknessFilter,
  643. $totalQuestions
  644. );
  645. // 获取扩展统计
  646. $expansionStats = $this->questionExpansionService->getExpansionStats($questionStrategy);
  647. $enhanced = array_merge($params, [
  648. 'difficulty_ratio' => $difficultyRatio,
  649. 'kp_codes' => $targetKnowledgePoints, // 确保使用目标知识点
  650. 'mistake_question_ids' => $questionStrategy['mistake_question_ids'] ?? [],
  651. // 优先级知识点:目标知识点 + 薄弱点
  652. 'priority_knowledge_points' => array_merge(
  653. array_values($targetKnowledgePoints),
  654. array_column($weaknessFilter, 'kp_code')
  655. ),
  656. 'question_type_ratio' => [
  657. '选择题' => 35,
  658. '填空题' => 30,
  659. '解答题' => 35,
  660. ],
  661. 'paper_name' => $params['paper_name'] ?? ('知识点组题_' . now()->format('Ymd_His')),
  662. // 标记这是按知识点组卷,用于后续处理
  663. 'is_knowledge_points_exam' => true,
  664. 'weakness_filter' => $weaknessFilter,
  665. // 目标知识点中的薄弱点(用于调整题目数量)
  666. 'target_weakness_kps' => array_values($targetWeaknessKps),
  667. // 题目扩展统计
  668. 'question_expansion_stats' => $expansionStats
  669. ]);
  670. Log::info('ExamTypeStrategy: 按知识点组卷参数构建完成', [
  671. 'intensity' => $intensity,
  672. 'target_knowledge_points_count' => count($targetKnowledgePoints),
  673. 'target_weakness_kps_count' => count($targetWeaknessKps),
  674. 'mistake_question_ids_count' => count($enhanced['mistake_question_ids']),
  675. 'priority_knowledge_points_count' => count($enhanced['priority_knowledge_points']),
  676. 'question_expansion_stats' => $enhanced['question_expansion_stats'],
  677. 'weakness_count' => count($weaknessFilter)
  678. ]);
  679. return $enhanced;
  680. }
  681. /**
  682. * 为摸底测试扩展知识点(确保覆盖全面)
  683. */
  684. private function expandKpCodesForDiagnostic(array $kpCodes): array
  685. {
  686. if (!empty($kpCodes)) {
  687. return $kpCodes;
  688. }
  689. // 如果没有指定知识点,返回一些通用的数学知识点
  690. return [
  691. '一元二次方程',
  692. '二次函数',
  693. '旋转',
  694. '圆',
  695. '概率初步',
  696. ];
  697. }
  698. /**
  699. * 获取学生薄弱点
  700. */
  701. private function getStudentWeaknesses(string $studentId, float $threshold): array
  702. {
  703. try {
  704. // 使用 StudentKnowledgeMastery 模型获取掌握度低于阈值的知识点
  705. $weaknessRecords = StudentKnowledgeMastery::forStudent($studentId)
  706. ->weaknesses($threshold)
  707. ->whereHas('knowledgePoint', function ($query) {
  708. $query->whereNotNull('parent_kp_code'); // 排除根节点(如 M00/S000_000)
  709. })
  710. ->orderByMastery('asc')
  711. ->limit(20)
  712. ->with('knowledgePoint') // 预加载知识点信息
  713. ->get();
  714. // 转换为统一格式
  715. return $weaknessRecords->map(function ($record) {
  716. return [
  717. 'kp_code' => $record->kp_code,
  718. 'kp_name' => $record->knowledgePoint->name ?? $record->kp_code,
  719. 'mastery' => (float) ($record->mastery_level ?? 0),
  720. 'attempts' => (int) ($record->total_attempts ?? 0),
  721. 'correct' => (int) ($record->correct_attempts ?? 0),
  722. 'incorrect' => (int) ($record->incorrect_attempts ?? 0),
  723. 'confidence' => (float) ($record->confidence_level ?? 0),
  724. 'trend' => $record->mastery_trend ?? 'stable',
  725. ];
  726. })->toArray();
  727. } catch (\Exception $e) {
  728. Log::error('ExamTypeStrategy: 获取学生薄弱点失败', [
  729. 'student_id' => $studentId,
  730. 'threshold' => $threshold,
  731. 'error' => $e->getMessage()
  732. ]);
  733. return [];
  734. }
  735. }
  736. /**
  737. * 智能组卷 (assembleType=8, 兼容旧 assembleType=1)
  738. * 基于教材知识点顺序与学生掌握度,选择首个未达标知识点(或其列表)组卷
  739. */
  740. private function buildIntelligentAssembleParams(array $params): array
  741. {
  742. Log::info('ExamTypeStrategy: 构建智能组卷参数', $params);
  743. $textbookId = $params['textbook_id'] ?? null;
  744. $grade = $params['grade'] ?? null; // 年级信息
  745. $totalQuestions = $params['total_questions'] ?? 20;
  746. $studentId = (int) ($params['student_id'] ?? 0);
  747. if (!$textbookId) {
  748. Log::warning('ExamTypeStrategy: 智能组卷需要 textbook_id 参数');
  749. return $this->buildGeneralParams($params);
  750. }
  751. $diagnosticService = app(DiagnosticChapterService::class);
  752. $textbookKpCodes = $diagnosticService->getTextbookKnowledgePointsInOrder((int) $textbookId);
  753. if (empty($textbookKpCodes)) {
  754. Log::warning('ExamTypeStrategy: 教材未找到知识点', ['textbook_id' => $textbookId]);
  755. return $this->buildGeneralParams($params);
  756. }
  757. $masteryMap = [];
  758. if ($studentId) {
  759. $masteryMap = StudentKnowledgeMastery::query()
  760. ->where('student_id', $studentId)
  761. ->whereIn('kp_code', $textbookKpCodes)
  762. ->pluck('mastery_level', 'kp_code')
  763. ->toArray();
  764. }
  765. $matchedKpCodes = array_values(array_intersect($textbookKpCodes, array_keys($masteryMap)));
  766. if (empty($matchedKpCodes)) {
  767. $initial = $diagnosticService->getInitialChapterKnowledgePoints((int) $textbookId);
  768. $kpCodes = $initial['kp_codes'] ?? [];
  769. if (empty($kpCodes)) {
  770. Log::warning('ExamTypeStrategy: 智能组卷未找到首章知识点', [
  771. 'textbook_id' => $textbookId
  772. ]);
  773. return $this->buildGeneralParams($params);
  774. }
  775. } else {
  776. $kpCodes = [];
  777. foreach ($textbookKpCodes as $kpCode) {
  778. if (!isset($masteryMap[$kpCode])) {
  779. continue;
  780. }
  781. $level = (float) $masteryMap[$kpCode];
  782. if ($level < 0.9) {
  783. $kpCodes[] = $kpCode;
  784. }
  785. }
  786. if (empty($kpCodes)) {
  787. $initial = $diagnosticService->getInitialChapterKnowledgePoints((int) $textbookId);
  788. $kpCodes = $initial['kp_codes'] ?? [];
  789. }
  790. }
  791. Log::info('ExamTypeStrategy: 获取到知识点', [
  792. 'kp_count' => count($kpCodes),
  793. 'kp_codes' => array_slice($kpCodes, 0, 5)
  794. ]);
  795. // 【重要】grade 缺失时从教材推断,保证智能补充可触发
  796. if ($textbookId && ($grade === null || $grade === '')) {
  797. $grade = DB::table('textbooks')->where('id', $textbookId)->value('grade');
  798. Log::info('ExamTypeStrategy: 智能组卷从教材推断 grade', [
  799. 'textbook_id' => $textbookId,
  800. 'inferred_grade' => $grade
  801. ]);
  802. }
  803. // 组装增强参数
  804. $enhanced = array_merge($params, [
  805. 'kp_code_list' => $kpCodes,
  806. 'textbook_id' => $textbookId,
  807. 'grade' => $grade,
  808. 'paper_name' => $params['paper_name'] ?? ('智能组题_' . now()->format('Ymd_His')),
  809. // 智能组卷:平衡的题型和难度配比
  810. 'question_type_ratio' => [
  811. '选择题' => 40,
  812. '填空题' => 30,
  813. '解答题' => 30,
  814. ],
  815. 'difficulty_ratio' => [
  816. '基础' => 25,
  817. '中等' => 50,
  818. '拔高' => 25,
  819. ],
  820. 'question_category' => 0, // question_category=0 代表普通题目(智能组卷)
  821. 'is_intelligent_assemble' => true,
  822. ]);
  823. Log::info('ExamTypeStrategy: 智能组卷参数构建完成', [
  824. 'textbook_id' => $textbookId,
  825. 'grade' => $grade,
  826. 'kp_count' => count($kpCodes),
  827. 'total_questions' => $totalQuestions
  828. ]);
  829. return $this->buildKnowledgePointAssembleParams($enhanced);
  830. }
  831. /**
  832. * 知识点组卷 (assembleType=2)
  833. * 直接根据 kp_code_list 查询题目,排除已做过的题目
  834. */
  835. private function buildKnowledgePointAssembleParams(array $params): array
  836. {
  837. Log::info('ExamTypeStrategy: 构建知识点组卷参数', $params);
  838. $kpCodeList = $params['kp_code_list'] ?? [];
  839. if (!is_array($kpCodeList)) {
  840. $kpCodeList = [];
  841. }
  842. $kpCodeList = array_values(array_unique(array_filter($kpCodeList)));
  843. $studentId = $params['student_id'] ?? null;
  844. $totalQuestions = $params['total_questions'] ?? 20;
  845. if (empty($kpCodeList)) {
  846. Log::warning('ExamTypeStrategy: 知识点组卷需要 kp_code_list 参数');
  847. return $this->buildGeneralParams($params);
  848. }
  849. Log::info('ExamTypeStrategy: 知识点组卷', [
  850. 'kp_code_list' => $kpCodeList,
  851. 'student_id' => $studentId,
  852. 'total_questions' => $totalQuestions
  853. ]);
  854. // assemble_type=2 走知识点扩展策略(复用 QuestionExpansionService)。
  855. // 只在基础题池不足时,才会触发子知识点补充(由扩展策略内部控制)。
  856. $assembleType = (int) ($params['assemble_type'] ?? 4);
  857. $priorityQuestionIds = [];
  858. $basePoolCount = 0;
  859. $finalPoolCount = 0;
  860. $childAddedCount = 0;
  861. if ($assembleType === 2) {
  862. $expansionStrategy = $this->questionExpansionService->expandQuestionsByKnowledgePoints(
  863. $params,
  864. $studentId ? (string) $studentId : null,
  865. $kpCodeList,
  866. [],
  867. (int) $totalQuestions
  868. );
  869. $priorityQuestionIds = array_values(array_unique(array_filter($expansionStrategy['mistake_question_ids'] ?? [])));
  870. $basePoolCount = (int) (
  871. ($expansionStrategy['expansion_details']['step1_direct_kp']['added_count'] ?? 0)
  872. + ($expansionStrategy['expansion_details']['step2_same_kp']['added_count'] ?? 0)
  873. );
  874. $finalPoolCount = count($priorityQuestionIds);
  875. $childAddedCount = max(0, $finalPoolCount - $basePoolCount);
  876. }
  877. // 三项汇总日志放在外围,便于统一观察策略触发情况。
  878. Log::info('ExamTypeStrategy: 知识点组卷题池评估', [
  879. 'original_kp_count' => count($kpCodeList),
  880. 'child_kp_added_count' => $childAddedCount,
  881. 'pool_count_after_expand' => $finalPoolCount,
  882. 'total_questions' => (int) $totalQuestions,
  883. 'assemble_type' => $assembleType,
  884. ]);
  885. // 如果有学生ID,获取已做过的题目ID列表(用于排除)
  886. $answeredQuestionIds = [];
  887. if ($studentId) {
  888. $answeredQuestionIds = $this->getStudentAnsweredQuestionIds($studentId, $kpCodeList);
  889. Log::info('ExamTypeStrategy: 获取学生已答题目', [
  890. 'student_id' => $studentId,
  891. 'answered_count' => count($answeredQuestionIds)
  892. ]);
  893. }
  894. // 组装增强参数
  895. $enhanced = array_merge($params, [
  896. 'kp_codes' => $kpCodeList,
  897. 'mistake_question_ids' => $basePoolCount < (int) $totalQuestions ? $priorityQuestionIds : [],
  898. 'exclude_question_ids' => $answeredQuestionIds,
  899. 'paper_name' => $params['paper_name'] ?? ('知识点组题_' . now()->format('Ymd_His')),
  900. // 知识点组卷:442配比(配合固定分值5/5/10,各题型贡献均等)
  901. 'question_type_ratio' => [
  902. '选择题' => 40,
  903. '填空题' => 40,
  904. '解答题' => 20,
  905. ],
  906. 'difficulty_ratio' => [
  907. '基础' => 25,
  908. '中等' => 50,
  909. '拔高' => 25,
  910. ],
  911. 'question_category' => 0, // question_category=0 代表普通题目
  912. 'is_knowledge_point_assemble' => true,
  913. ]);
  914. Log::info('ExamTypeStrategy: 知识点组卷参数构建完成', [
  915. 'kp_count' => count($kpCodeList),
  916. 'exclude_count' => count($answeredQuestionIds),
  917. 'total_questions' => $totalQuestions
  918. ]);
  919. return $enhanced;
  920. }
  921. /**
  922. * 教材组卷 (assembleType=3)
  923. * 根据 chapter_id_list 查询课本章节,获取知识点,然后组卷
  924. * 优化:按textbook_catalog_node_id筛选题目,添加章节知识点数量统计
  925. */
  926. private function buildTextbookAssembleParams(array $params): array
  927. {
  928. Log::info('ExamTypeStrategy: 构建教材组卷参数', $params);
  929. $chapterIdList = $params['chapter_id_list'] ?? [];
  930. $studentId = $params['student_id'] ?? null;
  931. $totalQuestions = $params['total_questions'] ?? 20;
  932. // 【优化】如果用户没有指定章节,自动从教材所有有题目的章节中选择
  933. if (empty($chapterIdList) && !empty($params['textbook_id'])) {
  934. Log::info('ExamTypeStrategy: 用户未指定章节,自动从教材选择', [
  935. 'textbook_id' => $params['textbook_id']
  936. ]);
  937. // 【修复】先查询教材下的所有章节,再筛选有题目的章节
  938. // 步骤1:根据textbook_id获取该教材下的所有章节ID
  939. $allChapterIds = DB::table('textbook_catalog_nodes')
  940. ->where('textbook_id', $params['textbook_id'])
  941. ->where('node_type', 'section')
  942. ->pluck('id')
  943. ->toArray();
  944. if (empty($allChapterIds)) {
  945. Log::warning('ExamTypeStrategy: 教材下未找到章节', [
  946. 'textbook_id' => $params['textbook_id']
  947. ]);
  948. } else {
  949. // 步骤2:从这些章节中筛选出有题目的章节
  950. $chapterIdList = DB::table('questions')
  951. ->whereIn('textbook_catalog_nodes_id', $allChapterIds)
  952. ->whereNotNull('textbook_catalog_nodes_id')
  953. ->where('textbook_catalog_nodes_id', '!=', '')
  954. ->distinct()
  955. ->pluck('textbook_catalog_nodes_id')
  956. ->toArray();
  957. Log::info('ExamTypeStrategy: 自动选择的章节列表', [
  958. 'textbook_id' => $params['textbook_id'],
  959. 'total_chapters' => count($allChapterIds),
  960. 'chapters_with_questions' => count($chapterIdList),
  961. 'chapter_ids' => $chapterIdList
  962. ]);
  963. }
  964. }
  965. // 【新增】如果用户指定了章节,解析章节节点类型并获取所有section/subsection节点
  966. if (!empty($chapterIdList)) {
  967. Log::info('ExamTypeStrategy: 用户指定了章节,开始解析节点类型', [
  968. 'input_chapter_ids' => $chapterIdList
  969. ]);
  970. // 解析用户传入的chapter_id_list,获取所有section/subsection节点
  971. $resolvedSectionIds = $this->resolveSectionNodesFromChapters($chapterIdList);
  972. if (!empty($resolvedSectionIds)) {
  973. // 使用解析后的section/subsection节点ID替换原有的chapterIdList
  974. $originalChapterCount = count($chapterIdList);
  975. $chapterIdList = $resolvedSectionIds;
  976. Log::info('ExamTypeStrategy: 章节节点解析完成,使用解析后的节点', [
  977. 'original_count' => $originalChapterCount,
  978. 'resolved_count' => count($chapterIdList),
  979. 'resolved_ids' => $chapterIdList
  980. ]);
  981. } else {
  982. Log::warning('ExamTypeStrategy: 章节节点解析失败,使用原始节点列表', [
  983. 'chapter_id_list' => $chapterIdList
  984. ]);
  985. }
  986. }
  987. if (empty($chapterIdList)) {
  988. Log::warning('ExamTypeStrategy: 教材组卷需要 chapter_id_list 参数或有效的textbook_id');
  989. return $this->buildGeneralParams($params);
  990. }
  991. Log::info('ExamTypeStrategy: 教材组卷', [
  992. 'chapter_id_list' => $chapterIdList,
  993. 'student_id' => $studentId,
  994. 'total_questions' => $totalQuestions
  995. ]);
  996. // 【修复】第一步:根据章节ID查询知识点关联,并统计每个章节的知识点数量
  997. $kpCodes = $this->getKnowledgePointsFromChapters($chapterIdList);
  998. // 【新增】获取每个章节对应的知识点数量统计
  999. $chapterKnowledgePointStats = $this->getChapterKnowledgePointStats($chapterIdList);
  1000. Log::info('ExamTypeStrategy: 获取章节知识点统计', [
  1001. 'chapter_stats' => $chapterKnowledgePointStats,
  1002. 'total_chapters' => count($chapterIdList)
  1003. ]);
  1004. // 【重要】教材组卷严格限制知识点数量,不进行任何扩展
  1005. if (empty($kpCodes)) {
  1006. Log::warning('ExamTypeStrategy: 未找到章节知识点关联,但保留章节筛选参数', [
  1007. 'chapter_id_list' => $chapterIdList,
  1008. 'note' => '将在LearningAnalyticsService中按textbook_catalog_nodes_id字段筛选题目'
  1009. ]);
  1010. } else {
  1011. Log::info('ExamTypeStrategy: 获取章节知识点(教材组卷严格限制)', [
  1012. 'kp_count' => count($kpCodes),
  1013. 'kp_codes' => $kpCodes,
  1014. 'note' => '教材组卷只返回章节关联的知识点,不进行扩展'
  1015. ]);
  1016. }
  1017. // 第二步:如果有学生ID,获取已做过的题目ID列表(用于排除)
  1018. $answeredQuestionIds = [];
  1019. if ($studentId) {
  1020. $answeredQuestionIds = $this->getStudentAnsweredQuestionIds($studentId, $kpCodes);
  1021. Log::info('ExamTypeStrategy: 获取学生已答题目', [
  1022. 'student_id' => $studentId,
  1023. 'answered_count' => count($answeredQuestionIds)
  1024. ]);
  1025. }
  1026. // 【优化】第三步:按textbook_catalog_node_id筛选题目,添加筛选条件
  1027. // 在LearningAnalyticsService中会使用这些参数进行题目筛选
  1028. $textbookCatalogNodeIds = $chapterIdList; // 直接使用章节ID作为textbook_catalog_node_id筛选条件
  1029. // 【重要】确保 grade 和 textbook_id 传给智能补充;grade 缺失时从教材推断
  1030. $textbookId = (int) ($params['textbook_id'] ?? 0);
  1031. $grade = $params['grade'] ?? null;
  1032. if ($textbookId && $grade === null) {
  1033. $grade = DB::table('textbooks')->where('id', $textbookId)->value('grade');
  1034. Log::info('ExamTypeStrategy: 教材组卷从教材推断 grade', [
  1035. 'textbook_id' => $textbookId,
  1036. 'inferred_grade' => $grade
  1037. ]);
  1038. }
  1039. // 组装增强参数
  1040. $enhanced = array_merge($params, [
  1041. 'kp_codes' => $kpCodes, // 可能为空,但仍保留
  1042. 'chapter_id_list' => $chapterIdList,
  1043. 'textbook_id' => $textbookId ?: ($params['textbook_id'] ?? null), // 保证智能补充有教材范围
  1044. 'grade' => $grade,
  1045. 'textbook_catalog_node_ids' => $textbookCatalogNodeIds, // 【重要】即使kpCodes为空也设置此参数
  1046. 'exclude_question_ids' => $answeredQuestionIds,
  1047. 'paper_name' => $params['paper_name'] ?? ('教材组题_' . now()->format('Ymd_His')),
  1048. // 教材组卷:按教材特点分配题型
  1049. 'question_type_ratio' => [
  1050. '选择题' => 40,
  1051. '填空题' => 30,
  1052. '解答题' => 30,
  1053. ],
  1054. 'difficulty_ratio' => [
  1055. '基础' => 25,
  1056. '中等' => 50,
  1057. '拔高' => 25,
  1058. ],
  1059. 'question_category' => 0, // question_category=0 代表普通题目
  1060. 'is_textbook_assemble' => true,
  1061. // 【新增】章节知识点数量统计
  1062. 'chapter_knowledge_point_stats' => $chapterKnowledgePointStats,
  1063. ]);
  1064. Log::info('ExamTypeStrategy: 教材组卷参数构建完成', [
  1065. 'chapter_count' => count($chapterIdList),
  1066. 'kp_count' => count($kpCodes),
  1067. 'exclude_count' => count($answeredQuestionIds),
  1068. 'total_questions' => $totalQuestions,
  1069. 'chapter_stats' => $chapterKnowledgePointStats
  1070. ]);
  1071. return $enhanced;
  1072. }
  1073. /**
  1074. * 根据课本ID获取章节ID列表
  1075. * @param int $textbookId 教材ID
  1076. * @param int|null $endCatalogId 截止章节ID(仅摸底使用),只返回该章节及之前的章节
  1077. */
  1078. private function getTextbookChapterIds(int $textbookId, ?int $endCatalogId = null): array
  1079. {
  1080. try {
  1081. $query = DB::table('textbook_catalog_nodes')
  1082. ->where('textbook_id', $textbookId)
  1083. ->where('node_type', 'section') // nodeType='section'
  1084. ->orderBy('sort_order');
  1085. // 如果指定了截止章节,只获取该章节及之前的章节
  1086. if ($endCatalogId) {
  1087. $endSortOrder = DB::table('textbook_catalog_nodes')
  1088. ->where('id', $endCatalogId)
  1089. ->value('sort_order');
  1090. if ($endSortOrder !== null) {
  1091. $query->where('sort_order', '<=', $endSortOrder);
  1092. Log::debug('ExamTypeStrategy: 应用截止章节过滤', [
  1093. 'end_catalog_id' => $endCatalogId,
  1094. 'end_sort_order' => $endSortOrder
  1095. ]);
  1096. } else {
  1097. Log::warning('ExamTypeStrategy: 截止章节ID无效', [
  1098. 'end_catalog_id' => $endCatalogId
  1099. ]);
  1100. }
  1101. }
  1102. $chapterIds = $query->pluck('id')->toArray();
  1103. Log::debug('ExamTypeStrategy: 查询课本章节ID', [
  1104. 'textbook_id' => $textbookId,
  1105. 'end_catalog_id' => $endCatalogId,
  1106. 'found_count' => count($chapterIds)
  1107. ]);
  1108. return $chapterIds;
  1109. } catch (\Exception $e) {
  1110. Log::error('ExamTypeStrategy: 查询课本章节ID失败', [
  1111. 'textbook_id' => $textbookId,
  1112. 'error' => $e->getMessage()
  1113. ]);
  1114. return [];
  1115. }
  1116. }
  1117. /**
  1118. * 根据章节ID列表获取知识点代码列表(均等抽样版本)
  1119. * 使用"知识点均等抽样"算法,确保覆盖全书章节
  1120. *
  1121. * @param array $chapterIds 章节ID列表
  1122. * @param int $limit 目标题目数量(默认25)
  1123. * @return array 抽样后的知识点代码列表
  1124. */
  1125. private function getKnowledgePointsFromChapters(array $chapterIds, int $limit = 25): array
  1126. {
  1127. try {
  1128. // 如果章节数较少,使用原有逻辑
  1129. if (count($chapterIds) <= 15) {
  1130. Log::info('ExamTypeStrategy: 章节数较少,使用原有逻辑', [
  1131. 'chapter_count' => count($chapterIds)
  1132. ]);
  1133. return $this->getKnowledgePointsFromChaptersLegacy($chapterIds, $limit);
  1134. }
  1135. // ========== 步骤1: 构建全量有序池 ==========
  1136. // 查询所有知识点,按章节顺序排列,去重后得到有序数组
  1137. $allKpData = DB::table('textbook_chapter_knowledge_relation as tckr')
  1138. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  1139. ->whereIn('tckr.catalog_chapter_id', $chapterIds)
  1140. ->where(function ($q) {
  1141. $q->where('tckr.is_deleted', 0)->orWhereNull('tckr.is_deleted');
  1142. })
  1143. ->select('tckr.kp_code', 'tcn.sort_order', 'tcn.id as chapter_id', 'tcn.title as chapter_title')
  1144. ->orderBy('tcn.sort_order', 'asc')
  1145. ->orderBy('tckr.kp_code', 'asc')
  1146. ->get();
  1147. // 去重并构建有序数组
  1148. $allKpCodes = [];
  1149. $chapterInfo = [];
  1150. foreach ($allKpData as $row) {
  1151. if (!in_array($row->kp_code, $allKpCodes)) {
  1152. $allKpCodes[] = $row->kp_code;
  1153. $chapterInfo[$row->kp_code] = [
  1154. 'chapter_id' => $row->chapter_id,
  1155. 'chapter_title' => $row->chapter_title,
  1156. 'sort_order' => $row->sort_order
  1157. ];
  1158. }
  1159. }
  1160. $totalKps = count($allKpCodes);
  1161. Log::info('ExamTypeStrategy: 构建全量有序池完成', [
  1162. 'chapter_count' => count($chapterIds),
  1163. 'total_knowledge_points' => $totalKps,
  1164. 'target_questions' => $limit
  1165. ]);
  1166. // ========== 步骤2: 计算抽样步长 ==========
  1167. $step = $totalKps > 0 ? $totalKps / $limit : 1;
  1168. Log::info('ExamTypeStrategy: 计算抽样步长', [
  1169. 'step' => $step
  1170. ]);
  1171. // ========== 步骤3: 等距取样 ==========
  1172. $selectedKps = [];
  1173. $selectedCount = 0;
  1174. $currentIndex = 0;
  1175. while ($selectedCount < $limit && $selectedCount < $totalKps) {
  1176. $index = (int) floor($currentIndex);
  1177. if ($index < $totalKps && isset($allKpCodes[$index])) {
  1178. $kpCode = $allKpCodes[$index];
  1179. if (!in_array($kpCode, $selectedKps)) {
  1180. $selectedKps[] = $kpCode;
  1181. $selectedCount++;
  1182. }
  1183. }
  1184. $currentIndex += $step;
  1185. }
  1186. // 如果数量不足,循环取样
  1187. if (count($selectedKps) < $limit && $totalKps > 0) {
  1188. Log::info('ExamTypeStrategy: 第一次抽样不足,进行循环取样', [
  1189. 'selected_count' => count($selectedKps),
  1190. 'target_count' => $limit
  1191. ]);
  1192. $needed = $limit - count($selectedKps);
  1193. $startIndex = 0;
  1194. for ($i = 0; $i < $needed && count($selectedKps) < $limit; $i++) {
  1195. $index = ($startIndex + $i) % $totalKps;
  1196. $kpCode = $allKpCodes[$index];
  1197. if (!in_array($kpCode, $selectedKps)) {
  1198. $selectedKps[] = $kpCode;
  1199. }
  1200. }
  1201. }
  1202. // ========== 步骤4: 记录抽样统计 ==========
  1203. $chapterDistribution = [];
  1204. foreach ($selectedKps as $kpCode) {
  1205. if (isset($chapterInfo[$kpCode])) {
  1206. $chapterId = $chapterInfo[$kpCode]['chapter_id'];
  1207. if (!isset($chapterDistribution[$chapterId])) {
  1208. $chapterDistribution[$chapterId] = [
  1209. 'count' => 0,
  1210. 'title' => $chapterInfo[$kpCode]['chapter_title']
  1211. ];
  1212. }
  1213. $chapterDistribution[$chapterId]['count']++;
  1214. }
  1215. }
  1216. Log::info('ExamTypeStrategy: 等距抽样完成', [
  1217. 'total_kps' => $totalKps,
  1218. 'selected_kps' => count($selectedKps),
  1219. 'step' => $step,
  1220. 'chapter_distribution' => $chapterDistribution,
  1221. 'sample_kp_codes' => array_slice($selectedKps, 0, 10)
  1222. ]);
  1223. return array_filter($selectedKps);
  1224. } catch (\Exception $e) {
  1225. Log::error('ExamTypeStrategy: 均等抽样获取章节知识点失败,使用原有逻辑', [
  1226. 'chapter_ids' => $chapterIds,
  1227. 'error' => $e->getMessage()
  1228. ]);
  1229. // 失败时回退到原有逻辑
  1230. return $this->getKnowledgePointsFromChaptersLegacy($chapterIds, $limit);
  1231. }
  1232. }
  1233. /**
  1234. * 原有逻辑(保留作为回退方案)
  1235. * 修复:解决DISTINCT和ORDER BY冲突问题
  1236. */
  1237. private function getKnowledgePointsFromChaptersLegacy(array $chapterIds, int $limit = 25): array
  1238. {
  1239. try {
  1240. // 修复方案1:使用GROUP BY替代DISTINCT,并选择需要的字段
  1241. $kpCodes = DB::table('textbook_chapter_knowledge_relation')
  1242. ->whereIn('catalog_chapter_id', $chapterIds)
  1243. ->where(function ($q) {
  1244. $q->where('is_deleted', 0)->orWhereNull('is_deleted');
  1245. })
  1246. ->select('kp_code')
  1247. ->groupBy('kp_code')
  1248. ->pluck('kp_code')
  1249. ->toArray();
  1250. Log::debug('ExamTypeStrategy: 查询章节知识点(原有逻辑)', [
  1251. 'chapter_count' => count($chapterIds),
  1252. 'found_kp_count' => count($kpCodes)
  1253. ]);
  1254. return array_filter($kpCodes); // 移除空值
  1255. } catch (\Exception $e) {
  1256. Log::error('ExamTypeStrategy: 查询章节知识点失败', [
  1257. 'chapter_ids' => $chapterIds,
  1258. 'error' => $e->getMessage()
  1259. ]);
  1260. return [];
  1261. }
  1262. }
  1263. /**
  1264. * 获取学生已做题目ID列表(用于排除)
  1265. *
  1266. * 唯一来源:从 paper_questions 中取该学生名下所有试卷的题目 ID(questions.id)
  1267. * 确保新卷子不会出现学生做过的重复题目
  1268. */
  1269. private function getStudentAnsweredQuestionIds(string $studentId, array $kpCodes): array
  1270. {
  1271. try {
  1272. $questionIds = PaperQuestion::query()
  1273. ->whereHas('paper', fn ($q) => $q->where('student_id', $studentId))
  1274. ->whereNotNull('question_bank_id')
  1275. ->where('question_bank_id', '>', 0)
  1276. ->distinct()
  1277. ->pluck('question_bank_id')
  1278. ->map(fn ($v) => (int) $v)
  1279. ->values()
  1280. ->toArray();
  1281. $paperCount = Paper::where('student_id', $studentId)->count();
  1282. Log::info('ExamTypeStrategy: 从 paper_questions 获取学生已做题目', [
  1283. 'student_id' => $studentId,
  1284. 'paper_count' => $paperCount,
  1285. 'exclude_count' => count($questionIds),
  1286. ]);
  1287. return $questionIds;
  1288. } catch (\Exception $e) {
  1289. Log::error('ExamTypeStrategy: 获取学生已做题目失败', [
  1290. 'student_id' => $studentId,
  1291. 'error' => $e->getMessage()
  1292. ]);
  1293. return [];
  1294. }
  1295. }
  1296. /**
  1297. * 通过卷子ID列表查询错题
  1298. * 注意:paper_ids 使用的是 papers 表中的 paper_id 字段,不是 id 字段
  1299. * 错题数据从 mistake_records 表中获取,该表已包含 paper_id 字段
  1300. * 注意:不按学生ID过滤,因为卷子可能包含其他同学的错题,需要收集所有错题
  1301. */
  1302. private function getMistakeQuestionsFromPapers(array $paperIds, ?string $studentId = null): array
  1303. {
  1304. try {
  1305. // 使用 Eloquent 模型查询,从 mistake_records 表中获取错题记录
  1306. // 不按 student_id 过滤,因为要收集所有学生的错题
  1307. $mistakeRecords = MistakeRecord::query()
  1308. ->whereIn('paper_id', $paperIds)
  1309. ->get();
  1310. if ($mistakeRecords->isEmpty()) {
  1311. Log::warning('ExamTypeStrategy: 卷子中未找到错题记录', [
  1312. 'paper_ids' => $paperIds
  1313. ]);
  1314. return [];
  1315. }
  1316. // 收集所有错题的 question_id
  1317. $questionIds = $mistakeRecords->pluck('question_id')
  1318. ->filter()
  1319. ->unique()
  1320. ->values()
  1321. ->toArray();
  1322. Log::info('ExamTypeStrategy: 查询卷子错题完成', [
  1323. 'paper_count' => count($paperIds),
  1324. 'paper_ids_input' => $paperIds,
  1325. 'mistake_record_count' => $mistakeRecords->count(),
  1326. 'unique_question_count' => count($questionIds),
  1327. 'question_ids' => array_slice($questionIds, 0, 20), // 最多记录20个ID
  1328. 'per_paper_stats' => $mistakeRecords->groupBy('paper_id')->map->count()->toArray()
  1329. ]);
  1330. return array_filter($questionIds);
  1331. } catch (\Exception $e) {
  1332. Log::error('ExamTypeStrategy: 查询卷子错题失败', [
  1333. 'paper_ids' => $paperIds,
  1334. 'error' => $e->getMessage()
  1335. ]);
  1336. return [];
  1337. }
  1338. }
  1339. /**
  1340. * 通过题目ID列表获取知识点代码列表
  1341. */
  1342. private function getKnowledgePointsFromQuestions(array $questionIds): array
  1343. {
  1344. try {
  1345. // 使用 Eloquent 模型查询,获取题目的知识点
  1346. $questions = Question::whereIn('id', $questionIds)
  1347. ->whereNotNull('kp_code')
  1348. ->where('kp_code', '!=', '')
  1349. ->distinct()
  1350. ->pluck('kp_code')
  1351. ->toArray();
  1352. Log::debug('ExamTypeStrategy: 查询题目知识点', [
  1353. 'question_count' => count($questionIds),
  1354. 'kp_count' => count($questions)
  1355. ]);
  1356. return array_filter($questions);
  1357. } catch (\Exception $e) {
  1358. Log::error('ExamTypeStrategy: 查询题目知识点失败', [
  1359. 'question_ids' => array_slice($questionIds, 0, 10), // 只记录前10个
  1360. 'error' => $e->getMessage()
  1361. ]);
  1362. return [];
  1363. }
  1364. }
  1365. /**
  1366. * 通过卷子ID列表获取卷子题目ID
  1367. */
  1368. private function getQuestionIdsFromPapers(array $paperIds): array
  1369. {
  1370. try {
  1371. $questionIds = DB::table('paper_questions')
  1372. ->whereIn('paper_id', $paperIds)
  1373. ->pluck('question_bank_id')
  1374. ->unique()
  1375. ->filter()
  1376. ->values()
  1377. ->toArray();
  1378. Log::debug('ExamTypeStrategy: 获取卷子题目ID', [
  1379. 'paper_ids' => $paperIds,
  1380. 'question_count' => count($questionIds)
  1381. ]);
  1382. return $questionIds;
  1383. } catch (\Exception $e) {
  1384. Log::error('ExamTypeStrategy: 获取卷子题目ID失败', [
  1385. 'paper_ids' => $paperIds,
  1386. 'error' => $e->getMessage()
  1387. ]);
  1388. return [];
  1389. }
  1390. }
  1391. /**
  1392. * 通过卷子ID列表获取题目知识点(直接使用 paper_questions.knowledge_point)
  1393. */
  1394. private function getKnowledgePointsFromPaperQuestions(array $paperIds): array
  1395. {
  1396. try {
  1397. $knowledgePoints = DB::table('paper_questions')
  1398. ->whereIn('paper_id', $paperIds)
  1399. ->whereNotNull('knowledge_point')
  1400. ->where('knowledge_point', '!=', '')
  1401. ->pluck('knowledge_point')
  1402. ->unique()
  1403. ->filter()
  1404. ->values()
  1405. ->toArray();
  1406. Log::debug('ExamTypeStrategy: 获取卷子题目知识点', [
  1407. 'paper_ids' => $paperIds,
  1408. 'kp_count' => count($knowledgePoints),
  1409. ]);
  1410. return $knowledgePoints;
  1411. } catch (\Exception $e) {
  1412. Log::error('ExamTypeStrategy: 获取卷子题目知识点失败', [
  1413. 'paper_ids' => $paperIds,
  1414. 'error' => $e->getMessage()
  1415. ]);
  1416. return [];
  1417. }
  1418. }
  1419. /**
  1420. * 通过卷子ID列表获取难度/题量/总分的聚合信息
  1421. */
  1422. private function getPaperAggregateStats(array $paperIds): array
  1423. {
  1424. try {
  1425. $rows = DB::table('papers')
  1426. ->whereIn('paper_id', $paperIds)
  1427. ->select(['paper_id', 'difficulty_category', 'total_questions', 'total_score'])
  1428. ->get();
  1429. $perPaper = [];
  1430. $difficultyValues = [];
  1431. $questionValues = [];
  1432. $scoreValues = [];
  1433. foreach ($rows as $row) {
  1434. $difficulty = is_null($row->difficulty_category) ? null : (int) $row->difficulty_category;
  1435. $totalQuestions = is_null($row->total_questions) ? null : (int) $row->total_questions;
  1436. $totalScore = is_null($row->total_score) ? null : (float) $row->total_score;
  1437. $perPaper[$row->paper_id] = [
  1438. 'difficulty_category' => $difficulty,
  1439. 'total_questions' => $totalQuestions,
  1440. 'total_score' => $totalScore,
  1441. 'raw_total_questions' => $row->total_questions,
  1442. ];
  1443. if (!is_null($difficulty)) {
  1444. $difficultyValues[] = $difficulty;
  1445. }
  1446. if (!empty($totalQuestions)) {
  1447. $questionValues[] = $totalQuestions;
  1448. }
  1449. if (!is_null($totalScore)) {
  1450. $scoreValues[] = $totalScore;
  1451. }
  1452. }
  1453. $stats = [
  1454. 'difficulty_category_min' => empty($difficultyValues) ? null : min($difficultyValues),
  1455. 'total_questions_max' => empty($questionValues) ? null : max($questionValues),
  1456. 'total_score_max' => empty($scoreValues) ? null : max($scoreValues),
  1457. ];
  1458. if (empty($stats['total_questions_max'])) {
  1459. $stats['total_questions_max'] = DB::table('paper_questions')
  1460. ->whereIn('paper_id', $paperIds)
  1461. ->selectRaw('paper_id, COUNT(*) as cnt')
  1462. ->groupBy('paper_id')
  1463. ->pluck('cnt')
  1464. ->max();
  1465. }
  1466. Log::info('ExamTypeStrategy: 获取卷子聚合信息', [
  1467. 'paper_ids' => $paperIds,
  1468. 'per_paper' => $perPaper,
  1469. 'stats' => $stats,
  1470. ]);
  1471. return $stats;
  1472. } catch (\Exception $e) {
  1473. Log::error('ExamTypeStrategy: 获取卷子聚合信息失败', [
  1474. 'paper_ids' => $paperIds,
  1475. 'error' => $e->getMessage()
  1476. ]);
  1477. return [];
  1478. }
  1479. }
  1480. /**
  1481. * 【新增】获取每个章节对应的知识点数量统计
  1482. * 通过textbook_chapter_knowledge_relation表关联查询
  1483. *
  1484. * @param array $chapterIdList 章节ID列表
  1485. * @return array 章节知识点数量统计
  1486. */
  1487. private function getChapterKnowledgePointStats(array $chapterIdList): array
  1488. {
  1489. try {
  1490. // 查询每个章节对应的知识点数量
  1491. $stats = DB::table('textbook_chapter_knowledge_relation as tckr')
  1492. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  1493. ->whereIn('tckr.catalog_chapter_id', $chapterIdList)
  1494. ->where(function ($q) {
  1495. $q->where('tckr.is_deleted', 0)->orWhereNull('tckr.is_deleted');
  1496. })
  1497. ->select(
  1498. 'tckr.catalog_chapter_id as chapter_id',
  1499. 'tcn.title as chapter_title',
  1500. DB::raw('COUNT(DISTINCT tckr.kp_code) as knowledge_point_count')
  1501. )
  1502. ->groupBy('tckr.catalog_chapter_id', 'tcn.title')
  1503. ->orderBy('tckr.catalog_chapter_id')
  1504. ->get();
  1505. // 转换为数组格式
  1506. $result = [];
  1507. foreach ($stats as $stat) {
  1508. $result[] = [
  1509. 'chapter_id' => $stat->chapter_id,
  1510. 'chapter_title' => $stat->chapter_title,
  1511. 'knowledge_point_count' => (int) $stat->knowledge_point_count
  1512. ];
  1513. }
  1514. Log::debug('ExamTypeStrategy: 获取章节知识点统计', [
  1515. 'chapter_count' => count($chapterIdList),
  1516. 'stats_count' => count($result),
  1517. 'stats' => $result
  1518. ]);
  1519. return $result;
  1520. } catch (\Exception $e) {
  1521. Log::error('ExamTypeStrategy: 获取章节知识点统计失败', [
  1522. 'chapter_id_list' => $chapterIdList,
  1523. 'error' => $e->getMessage()
  1524. ]);
  1525. // 返回空数组,不影响组卷流程
  1526. return [];
  1527. }
  1528. }
  1529. /**
  1530. * 【新增】递归获取section节点ID列表
  1531. * 根据用户传入的chapter_id_list,自动识别节点类型:
  1532. * - 如果是chapter节点,查找其下的所有section子节点(不包含subsection)
  1533. * - 如果是section节点,直接使用
  1534. *
  1535. * @param array $chapterIdList 用户传入的章节ID列表
  1536. * @return array 最终用于查询知识点的section节点ID列表
  1537. */
  1538. private function resolveSectionNodesFromChapters(array $chapterIdList): array
  1539. {
  1540. try {
  1541. if (empty($chapterIdList)) {
  1542. return [];
  1543. }
  1544. Log::info('ExamTypeStrategy: 开始解析章节节点', [
  1545. 'input_chapter_ids' => $chapterIdList
  1546. ]);
  1547. $finalSectionIds = [];
  1548. foreach ($chapterIdList as $nodeId) {
  1549. // 查询节点信息
  1550. $node = DB::table('textbook_catalog_nodes')
  1551. ->where('id', $nodeId)
  1552. ->first();
  1553. if (!$node) {
  1554. Log::warning('ExamTypeStrategy: 未找到节点', ['node_id' => $nodeId]);
  1555. continue;
  1556. }
  1557. Log::debug('ExamTypeStrategy: 处理节点', [
  1558. 'node_id' => $nodeId,
  1559. 'node_type' => $node->node_type,
  1560. 'title' => $node->title
  1561. ]);
  1562. // 根据节点类型处理
  1563. switch ($node->node_type) {
  1564. case 'chapter':
  1565. // 如果是chapter节点,查找其下的所有section子节点
  1566. $childNodes = DB::table('textbook_catalog_nodes')
  1567. ->where('parent_id', $nodeId)
  1568. ->where('node_type', 'section')
  1569. ->orderBy('sort_order')
  1570. ->get();
  1571. Log::info('ExamTypeStrategy: 解析chapter节点', [
  1572. 'chapter_id' => $nodeId,
  1573. 'chapter_title' => $node->title,
  1574. 'section_count' => count($childNodes)
  1575. ]);
  1576. foreach ($childNodes as $child) {
  1577. if (!in_array($child->id, $finalSectionIds)) {
  1578. $finalSectionIds[] = $child->id;
  1579. Log::debug('ExamTypeStrategy: 添加section子节点', [
  1580. 'parent_chapter' => $nodeId,
  1581. 'child_node_id' => $child->id,
  1582. 'child_title' => $child->title,
  1583. 'child_type' => $child->node_type
  1584. ]);
  1585. }
  1586. }
  1587. break;
  1588. case 'section':
  1589. // 如果是section节点,直接使用
  1590. if (!in_array($nodeId, $finalSectionIds)) {
  1591. $finalSectionIds[] = $nodeId;
  1592. Log::debug('ExamTypeStrategy: 直接使用section节点', [
  1593. 'node_id' => $nodeId,
  1594. 'title' => $node->title,
  1595. 'node_type' => $node->node_type
  1596. ]);
  1597. }
  1598. break;
  1599. case 'subsection':
  1600. // 如果是subsection节点,需要找到其父级section节点
  1601. $parentSection = DB::table('textbook_catalog_nodes')
  1602. ->where('id', $node->parent_id)
  1603. ->where('node_type', 'section')
  1604. ->first();
  1605. if ($parentSection && !in_array($parentSection->id, $finalSectionIds)) {
  1606. $finalSectionIds[] = $parentSection->id;
  1607. Log::debug('ExamTypeStrategy: 通过subsection找到父级section', [
  1608. 'subsection_id' => $nodeId,
  1609. 'subsection_title' => $node->title,
  1610. 'parent_section_id' => $parentSection->id,
  1611. 'parent_section_title' => $parentSection->title
  1612. ]);
  1613. }
  1614. break;
  1615. default:
  1616. Log::warning('ExamTypeStrategy: 未知节点类型', [
  1617. 'node_id' => $nodeId,
  1618. 'node_type' => $node->node_type
  1619. ]);
  1620. break;
  1621. }
  1622. }
  1623. Log::info('ExamTypeStrategy: 章节节点解析完成', [
  1624. 'input_count' => count($chapterIdList),
  1625. 'output_section_count' => count($finalSectionIds),
  1626. 'section_ids' => $finalSectionIds
  1627. ]);
  1628. return $finalSectionIds;
  1629. } catch (\Exception $e) {
  1630. Log::error('ExamTypeStrategy: 解析章节节点失败', [
  1631. 'chapter_id_list' => $chapterIdList,
  1632. 'error' => $e->getMessage()
  1633. ]);
  1634. // 出错时返回空数组
  1635. return [];
  1636. }
  1637. }
  1638. // ========== 以下是新增的章节摸底和智能组卷方法 ==========
  1639. /**
  1640. * 章节摸底(新逻辑)
  1641. * - 找第一个未摸底的章节
  1642. * - 用该章节的知识点出题(不扩展子知识点)
  1643. * - 过滤掉没有题目的知识点
  1644. * - 保存时记录 diagnostic_chapter_id
  1645. */
  1646. private function buildChapterDiagnosticParams(array $params): array
  1647. {
  1648. $diagnosticService = app(DiagnosticChapterService::class);
  1649. $textbookId = $params['textbook_id'] ?? null;
  1650. $studentId = (int) ($params['student_id'] ?? 0);
  1651. $grade = $params['grade'] ?? null;
  1652. $totalQuestions = $params['total_questions'] ?? 20;
  1653. Log::info('ExamTypeStrategy: 构建章节摸底参数', [
  1654. 'textbook_id' => $textbookId,
  1655. 'student_id' => $studentId,
  1656. ]);
  1657. if (!$textbookId) {
  1658. Log::warning('ExamTypeStrategy: 章节摸底需要 textbook_id 参数');
  1659. return $this->buildGeneralParams($params);
  1660. }
  1661. // 找第一个未摸底的章节
  1662. $chapterInfo = $diagnosticService->getFirstUndiagnosedChapter((int) $textbookId, $studentId);
  1663. if (empty($chapterInfo) || empty($chapterInfo['kp_codes'])) {
  1664. Log::warning('ExamTypeStrategy: 章节摸底未找到有效章节', [
  1665. 'textbook_id' => $textbookId,
  1666. 'student_id' => $studentId,
  1667. ]);
  1668. return $this->buildGeneralParams($params);
  1669. }
  1670. Log::info('ExamTypeStrategy: 章节摸底参数构建完成', [
  1671. 'textbook_id' => $textbookId,
  1672. 'chapter_id' => $chapterInfo['chapter_id'],
  1673. 'chapter_name' => $chapterInfo['chapter_name'] ?? '',
  1674. 'section_count' => count($chapterInfo['section_ids'] ?? []),
  1675. 'kp_count' => count($chapterInfo['kp_codes']),
  1676. 'total_questions' => $totalQuestions,
  1677. 'is_restart' => $chapterInfo['is_restart'] ?? false,
  1678. ]);
  1679. $enhanced = array_merge($params, [
  1680. 'kp_code_list' => $chapterInfo['kp_codes'],
  1681. 'chapter_id_list' => $chapterInfo['section_ids'],
  1682. 'diagnostic_chapter_id' => $chapterInfo['chapter_id'], // 记录摸底的章节ID
  1683. 'textbook_id' => $textbookId,
  1684. // 注意:不传 grade 参数,禁用"从其他知识点补充"的逻辑
  1685. // 用户需求:题目不够就不够,不从其他知识点补充
  1686. 'paper_name' => $params['paper_name'] ?? ('章节摸底_' . ($chapterInfo['chapter_name'] ?? '') . '_' . now()->format('Ymd_His')),
  1687. 'assembleType' => 0, // 确保 paper_type 记录为摸底
  1688. ]);
  1689. return $this->buildKnowledgePointAssembleParams($enhanced);
  1690. }
  1691. /**
  1692. * 按知识点顺序学习(新逻辑)
  1693. * - 找当前应该学习的章节(有未达标知识点的章节)
  1694. * - 如果该章节未摸底,返回摸底参数
  1695. * - 按顺序找未达标的知识点,最多2个
  1696. * - 如果都达标,进入下一章摸底
  1697. */
  1698. private function buildChapterIntelligentParams(array $params): array
  1699. {
  1700. $diagnosticService = app(DiagnosticChapterService::class);
  1701. $textbookId = $params['textbook_id'] ?? null;
  1702. $studentId = (int) ($params['student_id'] ?? 0);
  1703. $grade = $params['grade'] ?? null;
  1704. $totalQuestions = $params['total_questions'] ?? 20;
  1705. Log::info('ExamTypeStrategy: 构建按知识点顺序学习参数', [
  1706. 'textbook_id' => $textbookId,
  1707. 'student_id' => $studentId,
  1708. ]);
  1709. if (!$textbookId) {
  1710. Log::warning('ExamTypeStrategy: 智能组卷需要 textbook_id 参数');
  1711. return $this->buildGeneralParams($params);
  1712. }
  1713. // 获取当前应该学习的章节
  1714. $chapterInfo = $diagnosticService->getCurrentLearningChapter((int) $textbookId, $studentId, 0.9);
  1715. // 情况1: 所有章节都达标,从第一章重新开始摸底
  1716. if (empty($chapterInfo)) {
  1717. Log::info('ExamTypeStrategy: 所有章节都达标,从第一章重新开始摸底');
  1718. return $this->buildChapterDiagnosticParams($params);
  1719. }
  1720. // 情况2: 当前章节未摸底,需要先摸底
  1721. if (!($chapterInfo['has_diagnostic'] ?? false)) {
  1722. Log::info('ExamTypeStrategy: 当前章节未摸底,先进行摸底', [
  1723. 'chapter_id' => $chapterInfo['chapter_id'],
  1724. ]);
  1725. return $this->buildChapterDiagnosticParams($params);
  1726. }
  1727. // 情况3: 已摸底,按顺序找未达标的知识点
  1728. $unmasteredKpCodes = $diagnosticService->getUnmasteredKpCodesInOrder(
  1729. $studentId,
  1730. $chapterInfo['kp_codes'],
  1731. 0.9, // 阈值
  1732. 2, // 最多2个知识点
  1733. $totalQuestions
  1734. );
  1735. // 情况4: 当前章节所有知识点都达标,进入下一章摸底
  1736. if (empty($unmasteredKpCodes)) {
  1737. Log::info('ExamTypeStrategy: 当前章节所有知识点都达标,进入下一章', [
  1738. 'current_chapter_id' => $chapterInfo['chapter_id'],
  1739. ]);
  1740. // 获取下一章
  1741. $nextChapter = $diagnosticService->getNextChapter((int) $textbookId, $chapterInfo['chapter_id']);
  1742. if ($nextChapter) {
  1743. // 检查下一章是否已摸底
  1744. $hasNextDiagnostic = $diagnosticService->hasChapterDiagnostic($studentId, $nextChapter['chapter_id']);
  1745. if (!$hasNextDiagnostic) {
  1746. Log::info('ExamTypeStrategy: 下一章未摸底,进行摸底', [
  1747. 'next_chapter_id' => $nextChapter['chapter_id'],
  1748. ]);
  1749. // 直接设置下一章的参数,不递归调用
  1750. $enhanced = array_merge($params, [
  1751. 'kp_code_list' => $nextChapter['kp_codes'],
  1752. 'chapter_id_list' => $nextChapter['section_ids'],
  1753. 'diagnostic_chapter_id' => $nextChapter['chapter_id'],
  1754. 'textbook_id' => $textbookId,
  1755. // 注意:不传 grade 参数,禁用"从其他知识点补充"的逻辑
  1756. 'paper_name' => $params['paper_name'] ?? ('章节摸底_' . ($nextChapter['chapter_name'] ?? '') . '_' . now()->format('Ymd_His')),
  1757. 'assembleType' => 0,
  1758. ]);
  1759. return $this->buildKnowledgePointAssembleParams($enhanced);
  1760. } else {
  1761. // 下一章已摸底,找下一章的未达标知识点
  1762. $nextUnmasteredKpCodes = $diagnosticService->getUnmasteredKpCodesInOrder(
  1763. $studentId,
  1764. $nextChapter['kp_codes'],
  1765. 0.9,
  1766. 2,
  1767. $totalQuestions
  1768. );
  1769. if (!empty($nextUnmasteredKpCodes)) {
  1770. $unmasteredKpCodes = $nextUnmasteredKpCodes;
  1771. $chapterInfo = $nextChapter;
  1772. }
  1773. }
  1774. }
  1775. // 如果没有下一章或下一章也都达标,从头开始
  1776. if (empty($unmasteredKpCodes)) {
  1777. Log::info('ExamTypeStrategy: 所有章节都学完,从第一章重新开始');
  1778. return $this->buildChapterDiagnosticParams($params);
  1779. }
  1780. }
  1781. Log::info('ExamTypeStrategy: 按知识点顺序学习参数构建完成', [
  1782. 'textbook_id' => $textbookId,
  1783. 'chapter_id' => $chapterInfo['chapter_id'],
  1784. 'kp_codes' => $unmasteredKpCodes,
  1785. 'kp_count' => count($unmasteredKpCodes),
  1786. 'total_questions' => $totalQuestions,
  1787. ]);
  1788. $enhanced = array_merge($params, [
  1789. 'kp_code_list' => $unmasteredKpCodes,
  1790. 'explanation_kp_codes' => $unmasteredKpCodes, // 学案讲解只显示这些知识点(最多2个)
  1791. 'textbook_id' => $textbookId,
  1792. // 注意:不传 grade 参数,禁用"从其他知识点补充"的逻辑
  1793. // 用户需求:题目不够就不够,不从其他知识点补充
  1794. 'paper_name' => $params['paper_name'] ?? ('智能学习_' . now()->format('Ymd_His')),
  1795. 'assembleType' => 1, // paper_type 记录为智能组卷
  1796. ]);
  1797. return $this->buildKnowledgePointAssembleParams($enhanced);
  1798. }
  1799. }