ExamTypeStrategy.php 88 KB

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