ExamTypeStrategy.php 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182
  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. $kpCodesForPool = $kpCodeList;
  846. if ($assembleType === 2 && filter_var(config('question_bank.kp_assemble_include_parent_subtree', true), FILTER_VALIDATE_BOOLEAN)) {
  847. $kpCodesForPool = $this->expandKpCodesWithParentChapterSubtrees($kpCodeList);
  848. Log::info('ExamTypeStrategy: 知识点组卷已按父节点扩展整棵子树 KP', [
  849. 'original_kp_codes' => $kpCodeList,
  850. 'expanded_kp_codes' => $kpCodesForPool,
  851. 'original_count' => count($kpCodeList),
  852. 'expanded_count' => count($kpCodesForPool),
  853. ]);
  854. }
  855. Log::debug('ExamTypeStrategy: 知识点组卷', [
  856. 'kp_count' => count($kpCodeList),
  857. 'kp_pool_count' => count($kpCodesForPool),
  858. 'total_questions' => $totalQuestions
  859. ]);
  860. // assemble_type=2 走知识点扩展策略(复用 QuestionExpansionService)。
  861. // 只在基础题池不足时,才会触发子知识点补充(由扩展策略内部控制)。
  862. $priorityQuestionIds = [];
  863. $basePoolCount = 0;
  864. $finalPoolCount = 0;
  865. $childAddedCount = 0;
  866. if ($assembleType === 2) {
  867. $expansionStrategy = $this->questionExpansionService->expandQuestionsByKnowledgePoints(
  868. $params,
  869. $studentId ? (string) $studentId : null,
  870. $kpCodesForPool,
  871. [],
  872. (int) $totalQuestions
  873. );
  874. $priorityQuestionIds = array_values(array_unique(array_filter($expansionStrategy['mistake_question_ids'] ?? [])));
  875. $basePoolCount = (int) (
  876. ($expansionStrategy['expansion_details']['step1_direct_kp']['added_count'] ?? 0)
  877. + ($expansionStrategy['expansion_details']['step2_same_kp']['added_count'] ?? 0)
  878. );
  879. $finalPoolCount = count($priorityQuestionIds);
  880. $childAddedCount = max(0, $finalPoolCount - $basePoolCount);
  881. }
  882. // 如果有学生ID,获取已做过的题目ID列表(用于排除)
  883. $answeredQuestionIds = [];
  884. if ($studentId) {
  885. $answeredQuestionIds = $this->getStudentAnsweredQuestionIds($studentId, $kpCodeList);
  886. }
  887. Log::debug('ExamTypeStrategy: 知识点组卷题池评估', [
  888. 'kp_count' => count($kpCodeList),
  889. 'kp_pool_count' => count($kpCodesForPool),
  890. 'pool_count' => $finalPoolCount,
  891. 'exclude_count' => count($answeredQuestionIds),
  892. ]);
  893. // 组装增强参数
  894. $enhanced = array_merge($params, [
  895. 'kp_codes' => $kpCodesForPool,
  896. 'kp_code_list_original' => $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::debug('ExamTypeStrategy: 知识点组卷参数构建完成', [
  915. 'kp_count' => count($kpCodeList),
  916. 'kp_pool_count' => count($kpCodesForPool),
  917. 'exclude_count' => count($answeredQuestionIds),
  918. ]);
  919. return $enhanced;
  920. }
  921. /**
  922. * 将用户选中的 kp 扩展为:各选中知识点在 knowledge_points 中「直接父节点」下的整棵子树(含父节点自身及所有后代)之并集。
  923. * 多选且同属同一父章节(如 SIM01 下的 SIM01B/C/D)时,distinct parent 仅为 SIM01,等价于纳入 SIM01 整棵树(SIM01A–E 等)的全部 kp_code。
  924. * 不在此再上溯祖父:祖父在库中往往挂在更高层(如整册根),会造成超范围并题。
  925. *
  926. * @return array<string>
  927. */
  928. private function expandKpCodesWithParentChapterSubtrees(array $kpCodes): array
  929. {
  930. $kpCodes = array_values(array_unique(array_filter($kpCodes)));
  931. if ($kpCodes === []) {
  932. return [];
  933. }
  934. $expanded = [];
  935. foreach ($kpCodes as $kp) {
  936. $expanded[] = $kp;
  937. }
  938. $distinctParents = [];
  939. foreach ($kpCodes as $kp) {
  940. $p = KnowledgePoint::query()->where('kp_code', $kp)->value('parent_kp_code');
  941. if ($p !== null && $p !== '') {
  942. $distinctParents[(string) $p] = true;
  943. }
  944. }
  945. foreach (array_keys($distinctParents) as $parentKp) {
  946. $expanded = array_merge($expanded, $this->getDescendantKpCodesIncludingRoot($parentKp));
  947. }
  948. return array_values(array_unique(array_filter($expanded)));
  949. }
  950. /**
  951. * BFS 收集某 kp 节点在 knowledge_points 中的整棵后代子树(含根节点 kp_code)。
  952. *
  953. * @return array<string>
  954. */
  955. private function getDescendantKpCodesIncludingRoot(string $rootKpCode): array
  956. {
  957. $rootKpCode = trim($rootKpCode);
  958. if ($rootKpCode === '') {
  959. return [];
  960. }
  961. $seen = [$rootKpCode => true];
  962. $queue = [$rootKpCode];
  963. $guard = 0;
  964. $maxIter = 5000;
  965. while ($queue !== [] && $guard++ < $maxIter) {
  966. $cur = array_shift($queue);
  967. $children = KnowledgePoint::query()
  968. ->where('parent_kp_code', $cur)
  969. ->pluck('kp_code')
  970. ->all();
  971. foreach ($children as $child) {
  972. $c = (string) $child;
  973. if ($c === '') {
  974. continue;
  975. }
  976. if (! isset($seen[$c])) {
  977. $seen[$c] = true;
  978. $queue[] = $c;
  979. }
  980. }
  981. }
  982. return array_keys($seen);
  983. }
  984. /**
  985. * 教材组卷 (assembleType=3)
  986. * 根据 chapter_id_list 查询课本章节,获取知识点,然后组卷
  987. * 优化:按textbook_catalog_node_id筛选题目,添加章节知识点数量统计
  988. */
  989. private function buildTextbookAssembleParams(array $params): array
  990. {
  991. Log::debug('ExamTypeStrategy: 构建教材组卷参数', [
  992. 'chapter_count' => count($params['chapter_id_list'] ?? []),
  993. 'textbook_id' => $params['textbook_id'] ?? null
  994. ]);
  995. $chapterIdList = $params['chapter_id_list'] ?? [];
  996. $studentId = $params['student_id'] ?? null;
  997. $totalQuestions = $params['total_questions'] ?? 20;
  998. // 【优化】如果用户没有指定章节,自动从教材所有有题目的章节中选择
  999. if (empty($chapterIdList) && !empty($params['textbook_id'])) {
  1000. Log::info('ExamTypeStrategy: 用户未指定章节,自动从教材选择', [
  1001. 'textbook_id' => $params['textbook_id']
  1002. ]);
  1003. // 【修复】先查询教材下的所有章节,再筛选有题目的章节
  1004. // 步骤1:根据textbook_id获取该教材下的所有章节ID
  1005. $allChapterIds = DB::table('textbook_catalog_nodes')
  1006. ->where('textbook_id', $params['textbook_id'])
  1007. ->where('node_type', 'section')
  1008. ->pluck('id')
  1009. ->toArray();
  1010. if (empty($allChapterIds)) {
  1011. Log::warning('ExamTypeStrategy: 教材下未找到章节', [
  1012. 'textbook_id' => $params['textbook_id']
  1013. ]);
  1014. } else {
  1015. // 步骤2:从这些章节中筛选出有题目的章节
  1016. $chapterIdList = DB::table('questions')
  1017. ->whereIn('textbook_catalog_nodes_id', $allChapterIds)
  1018. ->whereNotNull('textbook_catalog_nodes_id')
  1019. ->where('textbook_catalog_nodes_id', '!=', '')
  1020. ->distinct()
  1021. ->pluck('textbook_catalog_nodes_id')
  1022. ->toArray();
  1023. Log::info('ExamTypeStrategy: 自动选择的章节列表', [
  1024. 'textbook_id' => $params['textbook_id'],
  1025. 'total_chapters' => count($allChapterIds),
  1026. 'chapters_with_questions' => count($chapterIdList),
  1027. 'chapter_ids' => $chapterIdList
  1028. ]);
  1029. }
  1030. }
  1031. // 【新增】如果用户指定了章节,解析章节节点类型并获取所有section/subsection节点
  1032. if (!empty($chapterIdList)) {
  1033. Log::info('ExamTypeStrategy: 用户指定了章节,开始解析节点类型', [
  1034. 'input_chapter_ids' => $chapterIdList
  1035. ]);
  1036. // 解析用户传入的chapter_id_list,获取所有section/subsection节点
  1037. $resolvedSectionIds = $this->resolveSectionNodesFromChapters($chapterIdList);
  1038. if (!empty($resolvedSectionIds)) {
  1039. // 使用解析后的section/subsection节点ID替换原有的chapterIdList
  1040. $originalChapterCount = count($chapterIdList);
  1041. $chapterIdList = $resolvedSectionIds;
  1042. Log::info('ExamTypeStrategy: 章节节点解析完成,使用解析后的节点', [
  1043. 'original_count' => $originalChapterCount,
  1044. 'resolved_count' => count($chapterIdList),
  1045. 'resolved_ids' => $chapterIdList
  1046. ]);
  1047. } else {
  1048. Log::warning('ExamTypeStrategy: 章节节点解析失败,使用原始节点列表', [
  1049. 'chapter_id_list' => $chapterIdList
  1050. ]);
  1051. }
  1052. }
  1053. if (empty($chapterIdList)) {
  1054. Log::warning('ExamTypeStrategy: 教材组卷需要 chapter_id_list 参数或有效的textbook_id');
  1055. return $this->buildGeneralParams($params);
  1056. }
  1057. Log::info('ExamTypeStrategy: 教材组卷', [
  1058. 'chapter_id_list' => $chapterIdList,
  1059. 'student_id' => $studentId,
  1060. 'total_questions' => $totalQuestions
  1061. ]);
  1062. // 【修复】第一步:根据章节ID查询知识点关联,并统计每个章节的知识点数量
  1063. $kpCodes = $this->getKnowledgePointsFromChapters($chapterIdList);
  1064. // 【新增】获取每个章节对应的知识点数量统计
  1065. $chapterKnowledgePointStats = $this->getChapterKnowledgePointStats($chapterIdList);
  1066. Log::info('ExamTypeStrategy: 获取章节知识点统计', [
  1067. 'chapter_stats' => $chapterKnowledgePointStats,
  1068. 'total_chapters' => count($chapterIdList)
  1069. ]);
  1070. // 【重要】教材组卷严格限制知识点数量,不进行任何扩展
  1071. if (empty($kpCodes)) {
  1072. Log::warning('ExamTypeStrategy: 未找到章节知识点关联,但保留章节筛选参数', [
  1073. 'chapter_id_list' => $chapterIdList,
  1074. 'note' => 'LearningAnalyticsService 将按 textbook_chapter_knowledge_relation 解析知识点后按 kp_code 选题',
  1075. ]);
  1076. } else {
  1077. Log::info('ExamTypeStrategy: 获取章节知识点(教材组卷严格限制)', [
  1078. 'kp_count' => count($kpCodes),
  1079. 'kp_codes' => $kpCodes,
  1080. 'note' => '教材组卷只返回章节关联的知识点,不进行扩展'
  1081. ]);
  1082. }
  1083. // 第二步:如果有学生ID,获取已做过的题目ID列表(用于排除)
  1084. $answeredQuestionIds = [];
  1085. if ($studentId) {
  1086. $answeredQuestionIds = $this->getStudentAnsweredQuestionIds($studentId, $kpCodes);
  1087. Log::info('ExamTypeStrategy: 获取学生已答题目', [
  1088. 'student_id' => $studentId,
  1089. 'answered_count' => count($answeredQuestionIds)
  1090. ]);
  1091. }
  1092. // 【优化】第三步:按textbook_catalog_node_id筛选题目,添加筛选条件
  1093. // 在LearningAnalyticsService中会使用这些参数进行题目筛选
  1094. $textbookCatalogNodeIds = $chapterIdList; // 直接使用章节ID作为textbook_catalog_node_id筛选条件
  1095. // 【重要】确保 grade 和 textbook_id 传给智能补充;章节节点归属教材,可由 chapter_id_list 反查 textbook_id
  1096. $textbookId = (int) ($params['textbook_id'] ?? 0);
  1097. if ($textbookId <= 0 && ! empty($chapterIdList)) {
  1098. $resolvedTextbookId = $this->resolveTextbookIdFromChapterNodes($chapterIdList);
  1099. if ($resolvedTextbookId !== null) {
  1100. $textbookId = $resolvedTextbookId;
  1101. Log::info('ExamTypeStrategy: 由 chapter_id_list 推断 textbook_id', [
  1102. 'textbook_id' => $textbookId,
  1103. 'chapter_id_list' => $chapterIdList,
  1104. ]);
  1105. }
  1106. }
  1107. $grade = $params['grade'] ?? null;
  1108. if ($textbookId && $grade === null) {
  1109. $grade = DB::table('textbooks')->where('id', $textbookId)->value('grade');
  1110. Log::info('ExamTypeStrategy: 教材组卷从教材推断 grade', [
  1111. 'textbook_id' => $textbookId,
  1112. 'inferred_grade' => $grade
  1113. ]);
  1114. }
  1115. // 组装增强参数
  1116. $enhanced = array_merge($params, [
  1117. 'kp_codes' => $kpCodes, // 可能为空,但仍保留
  1118. 'chapter_id_list' => $chapterIdList,
  1119. 'textbook_id' => $textbookId ?: ($params['textbook_id'] ?? null), // 保证智能补充有教材范围
  1120. 'grade' => $grade,
  1121. 'textbook_catalog_node_ids' => $textbookCatalogNodeIds, // 【重要】即使kpCodes为空也设置此参数
  1122. 'exclude_question_ids' => $answeredQuestionIds,
  1123. 'paper_name' => $params['paper_name'] ?? ('教材组题_' . now()->format('Ymd_His')),
  1124. // 教材组卷:按教材特点分配题型
  1125. 'question_type_ratio' => [
  1126. '选择题' => 40,
  1127. '填空题' => 30,
  1128. '解答题' => 30,
  1129. ],
  1130. 'difficulty_ratio' => [
  1131. '基础' => 25,
  1132. '中等' => 50,
  1133. '拔高' => 25,
  1134. ],
  1135. 'question_category' => 0, // question_category=0 代表普通题目
  1136. 'is_textbook_assemble' => true,
  1137. // 【新增】章节知识点数量统计
  1138. 'chapter_knowledge_point_stats' => $chapterKnowledgePointStats,
  1139. ]);
  1140. Log::info('ExamTypeStrategy: 教材组卷参数构建完成', [
  1141. 'chapter_count' => count($chapterIdList),
  1142. 'kp_count' => count($kpCodes),
  1143. 'exclude_count' => count($answeredQuestionIds),
  1144. 'total_questions' => $totalQuestions,
  1145. 'chapter_stats' => $chapterKnowledgePointStats
  1146. ]);
  1147. return $enhanced;
  1148. }
  1149. /**
  1150. * 章节节点 textbook_catalog_nodes 均归属某本教材;未传 textbook_id 时可根据节点 id 反查。
  1151. *
  1152. * @param array<int|string> $chapterIdList 解析后的章节/小节节点 id 列表
  1153. * @return int|null 唯一教材 id;无法解析或节点不存在时返回 null
  1154. */
  1155. private function resolveTextbookIdFromChapterNodes(array $chapterIdList): ?int
  1156. {
  1157. $ids = array_values(array_unique(array_filter(array_map(
  1158. static fn ($id) => (int) $id,
  1159. $chapterIdList
  1160. ), static fn (int $id) => $id > 0)));
  1161. if ($ids === []) {
  1162. return null;
  1163. }
  1164. $textbookIds = DB::table('textbook_catalog_nodes')
  1165. ->whereIn('id', $ids)
  1166. ->pluck('textbook_id')
  1167. ->unique()
  1168. ->values()
  1169. ->all();
  1170. if ($textbookIds === []) {
  1171. Log::warning('ExamTypeStrategy: chapter_id_list 在 textbook_catalog_nodes 中无匹配行', [
  1172. 'chapter_ids' => $ids,
  1173. ]);
  1174. return null;
  1175. }
  1176. if (count($textbookIds) > 1) {
  1177. Log::warning('ExamTypeStrategy: chapter_id_list 对应多本教材,取首个 textbook_id', [
  1178. 'textbook_ids' => $textbookIds,
  1179. 'chapter_ids' => $ids,
  1180. ]);
  1181. }
  1182. return (int) $textbookIds[0];
  1183. }
  1184. /**
  1185. * 根据课本ID获取章节ID列表
  1186. * @param int $textbookId 教材ID
  1187. * @param int|null $endCatalogId 截止章节ID(仅摸底使用),只返回该章节及之前的章节
  1188. */
  1189. private function getTextbookChapterIds(int $textbookId, ?int $endCatalogId = null): array
  1190. {
  1191. try {
  1192. $query = DB::table('textbook_catalog_nodes')
  1193. ->where('textbook_id', $textbookId)
  1194. ->where('node_type', 'section') // nodeType='section'
  1195. ->orderBy('sort_order');
  1196. // 如果指定了截止章节,只获取该章节及之前的章节
  1197. if ($endCatalogId) {
  1198. $endSortOrder = DB::table('textbook_catalog_nodes')
  1199. ->where('id', $endCatalogId)
  1200. ->value('sort_order');
  1201. if ($endSortOrder !== null) {
  1202. $query->where('sort_order', '<=', $endSortOrder);
  1203. Log::debug('ExamTypeStrategy: 应用截止章节过滤', [
  1204. 'end_catalog_id' => $endCatalogId,
  1205. 'end_sort_order' => $endSortOrder
  1206. ]);
  1207. } else {
  1208. Log::warning('ExamTypeStrategy: 截止章节ID无效', [
  1209. 'end_catalog_id' => $endCatalogId
  1210. ]);
  1211. }
  1212. }
  1213. $chapterIds = $query->pluck('id')->toArray();
  1214. Log::debug('ExamTypeStrategy: 查询课本章节ID', [
  1215. 'textbook_id' => $textbookId,
  1216. 'end_catalog_id' => $endCatalogId,
  1217. 'found_count' => count($chapterIds)
  1218. ]);
  1219. return $chapterIds;
  1220. } catch (\Exception $e) {
  1221. Log::error('ExamTypeStrategy: 查询课本章节ID失败', [
  1222. 'textbook_id' => $textbookId,
  1223. 'error' => $e->getMessage()
  1224. ]);
  1225. return [];
  1226. }
  1227. }
  1228. /**
  1229. * 根据章节ID列表获取知识点代码列表(均等抽样版本)
  1230. * 使用"知识点均等抽样"算法,确保覆盖全书章节
  1231. *
  1232. * @param array $chapterIds 章节ID列表
  1233. * @param int $limit 目标题目数量(默认25)
  1234. * @return array 抽样后的知识点代码列表
  1235. */
  1236. private function getKnowledgePointsFromChapters(array $chapterIds, int $limit = 25): array
  1237. {
  1238. try {
  1239. // 如果章节数较少,使用原有逻辑
  1240. if (count($chapterIds) <= 15) {
  1241. Log::info('ExamTypeStrategy: 章节数较少,使用原有逻辑', [
  1242. 'chapter_count' => count($chapterIds)
  1243. ]);
  1244. return $this->getKnowledgePointsFromChaptersLegacy($chapterIds, $limit);
  1245. }
  1246. // ========== 步骤1: 构建全量有序池 ==========
  1247. // 查询所有知识点,按章节顺序排列,去重后得到有序数组
  1248. $allKpData = DB::table('textbook_chapter_knowledge_relation as tckr')
  1249. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  1250. ->whereIn('tckr.catalog_chapter_id', $chapterIds)
  1251. ->where(function ($q) {
  1252. $q->where('tckr.is_deleted', 0)->orWhereNull('tckr.is_deleted');
  1253. })
  1254. ->select('tckr.kp_code', 'tcn.sort_order', 'tcn.id as chapter_id', 'tcn.title as chapter_title')
  1255. ->orderBy('tcn.sort_order', 'asc')
  1256. ->orderBy('tckr.kp_code', 'asc')
  1257. ->get();
  1258. // 去重并构建有序数组
  1259. $allKpCodes = [];
  1260. $chapterInfo = [];
  1261. foreach ($allKpData as $row) {
  1262. if (!in_array($row->kp_code, $allKpCodes)) {
  1263. $allKpCodes[] = $row->kp_code;
  1264. $chapterInfo[$row->kp_code] = [
  1265. 'chapter_id' => $row->chapter_id,
  1266. 'chapter_title' => $row->chapter_title,
  1267. 'sort_order' => $row->sort_order
  1268. ];
  1269. }
  1270. }
  1271. $totalKps = count($allKpCodes);
  1272. Log::info('ExamTypeStrategy: 构建全量有序池完成', [
  1273. 'chapter_count' => count($chapterIds),
  1274. 'total_knowledge_points' => $totalKps,
  1275. 'target_questions' => $limit
  1276. ]);
  1277. // ========== 步骤2: 计算抽样步长 ==========
  1278. $step = $totalKps > 0 ? $totalKps / $limit : 1;
  1279. Log::info('ExamTypeStrategy: 计算抽样步长', [
  1280. 'step' => $step
  1281. ]);
  1282. // ========== 步骤3: 等距取样 ==========
  1283. $selectedKps = [];
  1284. $selectedCount = 0;
  1285. $currentIndex = 0;
  1286. while ($selectedCount < $limit && $selectedCount < $totalKps) {
  1287. $index = (int) floor($currentIndex);
  1288. if ($index < $totalKps && isset($allKpCodes[$index])) {
  1289. $kpCode = $allKpCodes[$index];
  1290. if (!in_array($kpCode, $selectedKps)) {
  1291. $selectedKps[] = $kpCode;
  1292. $selectedCount++;
  1293. }
  1294. }
  1295. $currentIndex += $step;
  1296. }
  1297. // 如果数量不足,循环取样
  1298. if (count($selectedKps) < $limit && $totalKps > 0) {
  1299. Log::info('ExamTypeStrategy: 第一次抽样不足,进行循环取样', [
  1300. 'selected_count' => count($selectedKps),
  1301. 'target_count' => $limit
  1302. ]);
  1303. $needed = $limit - count($selectedKps);
  1304. $startIndex = 0;
  1305. for ($i = 0; $i < $needed && count($selectedKps) < $limit; $i++) {
  1306. $index = ($startIndex + $i) % $totalKps;
  1307. $kpCode = $allKpCodes[$index];
  1308. if (!in_array($kpCode, $selectedKps)) {
  1309. $selectedKps[] = $kpCode;
  1310. }
  1311. }
  1312. }
  1313. // ========== 步骤4: 记录抽样统计 ==========
  1314. $chapterDistribution = [];
  1315. foreach ($selectedKps as $kpCode) {
  1316. if (isset($chapterInfo[$kpCode])) {
  1317. $chapterId = $chapterInfo[$kpCode]['chapter_id'];
  1318. if (!isset($chapterDistribution[$chapterId])) {
  1319. $chapterDistribution[$chapterId] = [
  1320. 'count' => 0,
  1321. 'title' => $chapterInfo[$kpCode]['chapter_title']
  1322. ];
  1323. }
  1324. $chapterDistribution[$chapterId]['count']++;
  1325. }
  1326. }
  1327. Log::info('ExamTypeStrategy: 等距抽样完成', [
  1328. 'total_kps' => $totalKps,
  1329. 'selected_kps' => count($selectedKps),
  1330. 'step' => $step,
  1331. 'chapter_distribution' => $chapterDistribution,
  1332. 'sample_kp_codes' => array_slice($selectedKps, 0, 10)
  1333. ]);
  1334. return array_filter($selectedKps);
  1335. } catch (\Exception $e) {
  1336. Log::error('ExamTypeStrategy: 均等抽样获取章节知识点失败,使用原有逻辑', [
  1337. 'chapter_ids' => $chapterIds,
  1338. 'error' => $e->getMessage()
  1339. ]);
  1340. // 失败时回退到原有逻辑
  1341. return $this->getKnowledgePointsFromChaptersLegacy($chapterIds, $limit);
  1342. }
  1343. }
  1344. /**
  1345. * 原有逻辑(保留作为回退方案)
  1346. * 修复:解决DISTINCT和ORDER BY冲突问题
  1347. */
  1348. private function getKnowledgePointsFromChaptersLegacy(array $chapterIds, int $limit = 25): array
  1349. {
  1350. try {
  1351. // 修复方案1:使用GROUP BY替代DISTINCT,并选择需要的字段
  1352. $kpCodes = DB::table('textbook_chapter_knowledge_relation')
  1353. ->whereIn('catalog_chapter_id', $chapterIds)
  1354. ->where(function ($q) {
  1355. $q->where('is_deleted', 0)->orWhereNull('is_deleted');
  1356. })
  1357. ->select('kp_code')
  1358. ->groupBy('kp_code')
  1359. ->pluck('kp_code')
  1360. ->toArray();
  1361. Log::debug('ExamTypeStrategy: 查询章节知识点(原有逻辑)', [
  1362. 'chapter_count' => count($chapterIds),
  1363. 'found_kp_count' => count($kpCodes)
  1364. ]);
  1365. return array_filter($kpCodes); // 移除空值
  1366. } catch (\Exception $e) {
  1367. Log::error('ExamTypeStrategy: 查询章节知识点失败', [
  1368. 'chapter_ids' => $chapterIds,
  1369. 'error' => $e->getMessage()
  1370. ]);
  1371. return [];
  1372. }
  1373. }
  1374. /**
  1375. * 获取学生已做题目ID列表(用于排除)
  1376. *
  1377. * 唯一来源:从 paper_questions 中取该学生名下所有试卷的题目 ID(questions.id)
  1378. * 确保新卷子不会出现学生做过的重复题目
  1379. */
  1380. private function getStudentAnsweredQuestionIds(string $studentId, array $kpCodes): array
  1381. {
  1382. try {
  1383. $questionIds = PaperQuestion::query()
  1384. ->whereHas('paper', fn ($q) => $q->where('student_id', $studentId))
  1385. ->whereNotNull('question_bank_id')
  1386. ->where('question_bank_id', '>', 0)
  1387. ->distinct()
  1388. ->pluck('question_bank_id')
  1389. ->map(fn ($v) => (int) $v)
  1390. ->values()
  1391. ->toArray();
  1392. Log::debug('ExamTypeStrategy: 从 paper_questions 获取学生已做题目', [
  1393. 'student_id' => $studentId,
  1394. 'exclude_count' => count($questionIds),
  1395. ]);
  1396. return $questionIds;
  1397. } catch (\Exception $e) {
  1398. Log::error('ExamTypeStrategy: 获取学生已做题目失败', [
  1399. 'student_id' => $studentId,
  1400. 'error' => $e->getMessage()
  1401. ]);
  1402. return [];
  1403. }
  1404. }
  1405. /**
  1406. * 通过卷子ID列表查询错题
  1407. * 注意:paper_ids 使用的是 papers 表中的 paper_id 字段,不是 id 字段
  1408. * 错题数据从 mistake_records 表中获取,该表已包含 paper_id 字段
  1409. * 注意:不按学生ID过滤,因为卷子可能包含其他同学的错题,需要收集所有错题
  1410. */
  1411. private function getMistakeQuestionsFromPapers(array $paperIds, ?string $studentId = null): array
  1412. {
  1413. try {
  1414. // 使用 Eloquent 模型查询,从 mistake_records 表中获取错题记录
  1415. // 不按 student_id 过滤,因为要收集所有学生的错题
  1416. $mistakeRecords = MistakeRecord::query()
  1417. ->whereIn('paper_id', $paperIds)
  1418. ->get();
  1419. if ($mistakeRecords->isEmpty()) {
  1420. Log::warning('ExamTypeStrategy: 卷子中未找到错题记录', [
  1421. 'paper_ids' => $paperIds
  1422. ]);
  1423. return [];
  1424. }
  1425. // 收集所有错题的 question_id
  1426. $questionIds = $mistakeRecords->pluck('question_id')
  1427. ->filter()
  1428. ->unique()
  1429. ->values()
  1430. ->toArray();
  1431. Log::info('ExamTypeStrategy: 查询卷子错题完成', [
  1432. 'paper_count' => count($paperIds),
  1433. 'paper_ids_input' => $paperIds,
  1434. 'mistake_record_count' => $mistakeRecords->count(),
  1435. 'unique_question_count' => count($questionIds),
  1436. 'question_ids' => array_slice($questionIds, 0, 20), // 最多记录20个ID
  1437. 'per_paper_stats' => $mistakeRecords->groupBy('paper_id')->map->count()->toArray()
  1438. ]);
  1439. return array_filter($questionIds);
  1440. } catch (\Exception $e) {
  1441. Log::error('ExamTypeStrategy: 查询卷子错题失败', [
  1442. 'paper_ids' => $paperIds,
  1443. 'error' => $e->getMessage()
  1444. ]);
  1445. return [];
  1446. }
  1447. }
  1448. /**
  1449. * 通过题目ID列表获取知识点代码列表
  1450. */
  1451. private function getKnowledgePointsFromQuestions(array $questionIds): array
  1452. {
  1453. try {
  1454. // 使用 Eloquent 模型查询,获取题目的知识点
  1455. $questions = Question::whereIn('id', $questionIds)
  1456. ->whereNotNull('kp_code')
  1457. ->where('kp_code', '!=', '')
  1458. ->distinct()
  1459. ->pluck('kp_code')
  1460. ->toArray();
  1461. Log::debug('ExamTypeStrategy: 查询题目知识点', [
  1462. 'question_count' => count($questionIds),
  1463. 'kp_count' => count($questions)
  1464. ]);
  1465. return array_filter($questions);
  1466. } catch (\Exception $e) {
  1467. Log::error('ExamTypeStrategy: 查询题目知识点失败', [
  1468. 'question_ids' => array_slice($questionIds, 0, 10), // 只记录前10个
  1469. 'error' => $e->getMessage()
  1470. ]);
  1471. return [];
  1472. }
  1473. }
  1474. /**
  1475. * 通过卷子ID列表获取卷子题目ID
  1476. */
  1477. private function getQuestionIdsFromPapers(array $paperIds): array
  1478. {
  1479. try {
  1480. $questionIds = DB::table('paper_questions')
  1481. ->whereIn('paper_id', $paperIds)
  1482. ->pluck('question_bank_id')
  1483. ->unique()
  1484. ->filter()
  1485. ->values()
  1486. ->toArray();
  1487. Log::debug('ExamTypeStrategy: 获取卷子题目ID', [
  1488. 'paper_ids' => $paperIds,
  1489. 'question_count' => count($questionIds)
  1490. ]);
  1491. return $questionIds;
  1492. } catch (\Exception $e) {
  1493. Log::error('ExamTypeStrategy: 获取卷子题目ID失败', [
  1494. 'paper_ids' => $paperIds,
  1495. 'error' => $e->getMessage()
  1496. ]);
  1497. return [];
  1498. }
  1499. }
  1500. /**
  1501. * 通过卷子ID列表获取题目知识点(直接使用 paper_questions.knowledge_point)
  1502. */
  1503. private function getKnowledgePointsFromPaperQuestions(array $paperIds): array
  1504. {
  1505. try {
  1506. $knowledgePoints = DB::table('paper_questions')
  1507. ->whereIn('paper_id', $paperIds)
  1508. ->whereNotNull('knowledge_point')
  1509. ->where('knowledge_point', '!=', '')
  1510. ->pluck('knowledge_point')
  1511. ->unique()
  1512. ->filter()
  1513. ->values()
  1514. ->toArray();
  1515. Log::debug('ExamTypeStrategy: 获取卷子题目知识点', [
  1516. 'paper_ids' => $paperIds,
  1517. 'kp_count' => count($knowledgePoints),
  1518. ]);
  1519. return $knowledgePoints;
  1520. } catch (\Exception $e) {
  1521. Log::error('ExamTypeStrategy: 获取卷子题目知识点失败', [
  1522. 'paper_ids' => $paperIds,
  1523. 'error' => $e->getMessage()
  1524. ]);
  1525. return [];
  1526. }
  1527. }
  1528. /**
  1529. * 通过卷子ID列表获取难度/题量/总分的聚合信息
  1530. */
  1531. private function getPaperAggregateStats(array $paperIds): array
  1532. {
  1533. try {
  1534. $rows = DB::table('papers')
  1535. ->whereIn('paper_id', $paperIds)
  1536. ->select(['paper_id', 'difficulty_category', 'total_questions', 'total_score'])
  1537. ->get();
  1538. $perPaper = [];
  1539. $difficultyValues = [];
  1540. $questionValues = [];
  1541. $scoreValues = [];
  1542. foreach ($rows as $row) {
  1543. $difficulty = is_null($row->difficulty_category) ? null : (int) $row->difficulty_category;
  1544. $totalQuestions = is_null($row->total_questions) ? null : (int) $row->total_questions;
  1545. $totalScore = is_null($row->total_score) ? null : (float) $row->total_score;
  1546. $perPaper[$row->paper_id] = [
  1547. 'difficulty_category' => $difficulty,
  1548. 'total_questions' => $totalQuestions,
  1549. 'total_score' => $totalScore,
  1550. 'raw_total_questions' => $row->total_questions,
  1551. ];
  1552. if (!is_null($difficulty)) {
  1553. $difficultyValues[] = $difficulty;
  1554. }
  1555. if (!empty($totalQuestions)) {
  1556. $questionValues[] = $totalQuestions;
  1557. }
  1558. if (!is_null($totalScore)) {
  1559. $scoreValues[] = $totalScore;
  1560. }
  1561. }
  1562. $stats = [
  1563. 'difficulty_category_min' => empty($difficultyValues) ? null : min($difficultyValues),
  1564. 'total_questions_max' => empty($questionValues) ? null : max($questionValues),
  1565. 'total_score_max' => empty($scoreValues) ? null : max($scoreValues),
  1566. ];
  1567. if (empty($stats['total_questions_max'])) {
  1568. $stats['total_questions_max'] = DB::table('paper_questions')
  1569. ->whereIn('paper_id', $paperIds)
  1570. ->selectRaw('paper_id, COUNT(*) as cnt')
  1571. ->groupBy('paper_id')
  1572. ->pluck('cnt')
  1573. ->max();
  1574. }
  1575. Log::info('ExamTypeStrategy: 获取卷子聚合信息', [
  1576. 'paper_ids' => $paperIds,
  1577. 'per_paper' => $perPaper,
  1578. 'stats' => $stats,
  1579. ]);
  1580. return $stats;
  1581. } catch (\Exception $e) {
  1582. Log::error('ExamTypeStrategy: 获取卷子聚合信息失败', [
  1583. 'paper_ids' => $paperIds,
  1584. 'error' => $e->getMessage()
  1585. ]);
  1586. return [];
  1587. }
  1588. }
  1589. /**
  1590. * 【新增】获取每个章节对应的知识点数量统计
  1591. * 通过textbook_chapter_knowledge_relation表关联查询
  1592. *
  1593. * @param array $chapterIdList 章节ID列表
  1594. * @return array 章节知识点数量统计
  1595. */
  1596. private function getChapterKnowledgePointStats(array $chapterIdList): array
  1597. {
  1598. try {
  1599. // 查询每个章节对应的知识点数量
  1600. $stats = DB::table('textbook_chapter_knowledge_relation as tckr')
  1601. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  1602. ->whereIn('tckr.catalog_chapter_id', $chapterIdList)
  1603. ->where(function ($q) {
  1604. $q->where('tckr.is_deleted', 0)->orWhereNull('tckr.is_deleted');
  1605. })
  1606. ->select(
  1607. 'tckr.catalog_chapter_id as chapter_id',
  1608. 'tcn.title as chapter_title',
  1609. DB::raw('COUNT(DISTINCT tckr.kp_code) as knowledge_point_count')
  1610. )
  1611. ->groupBy('tckr.catalog_chapter_id', 'tcn.title')
  1612. ->orderBy('tckr.catalog_chapter_id')
  1613. ->get();
  1614. // 转换为数组格式
  1615. $result = [];
  1616. foreach ($stats as $stat) {
  1617. $result[] = [
  1618. 'chapter_id' => $stat->chapter_id,
  1619. 'chapter_title' => $stat->chapter_title,
  1620. 'knowledge_point_count' => (int) $stat->knowledge_point_count
  1621. ];
  1622. }
  1623. Log::debug('ExamTypeStrategy: 获取章节知识点统计', [
  1624. 'chapter_count' => count($chapterIdList),
  1625. 'stats_count' => count($result),
  1626. 'stats' => $result
  1627. ]);
  1628. return $result;
  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. * 【新增】递归获取section节点ID列表
  1640. * 根据用户传入的chapter_id_list,自动识别节点类型:
  1641. * - 如果是chapter节点,查找其下的所有section子节点(不包含subsection)
  1642. * - 如果是section节点,直接使用
  1643. *
  1644. * @param array $chapterIdList 用户传入的章节ID列表
  1645. * @return array 最终用于查询知识点的section节点ID列表
  1646. */
  1647. private function resolveSectionNodesFromChapters(array $chapterIdList): array
  1648. {
  1649. try {
  1650. if (empty($chapterIdList)) {
  1651. return [];
  1652. }
  1653. Log::info('ExamTypeStrategy: 开始解析章节节点', [
  1654. 'input_chapter_ids' => $chapterIdList
  1655. ]);
  1656. $finalSectionIds = [];
  1657. foreach ($chapterIdList as $nodeId) {
  1658. // 查询节点信息
  1659. $node = DB::table('textbook_catalog_nodes')
  1660. ->where('id', $nodeId)
  1661. ->first();
  1662. if (!$node) {
  1663. Log::warning('ExamTypeStrategy: 未找到节点', ['node_id' => $nodeId]);
  1664. continue;
  1665. }
  1666. Log::debug('ExamTypeStrategy: 处理节点', [
  1667. 'node_id' => $nodeId,
  1668. 'node_type' => $node->node_type,
  1669. 'title' => $node->title
  1670. ]);
  1671. // 根据节点类型处理
  1672. switch ($node->node_type) {
  1673. case 'chapter':
  1674. // 如果是chapter节点,查找其下的所有section子节点
  1675. $childNodes = DB::table('textbook_catalog_nodes')
  1676. ->where('parent_id', $nodeId)
  1677. ->where('node_type', 'section')
  1678. ->orderBy('sort_order')
  1679. ->get();
  1680. Log::info('ExamTypeStrategy: 解析chapter节点', [
  1681. 'chapter_id' => $nodeId,
  1682. 'chapter_title' => $node->title,
  1683. 'section_count' => count($childNodes)
  1684. ]);
  1685. foreach ($childNodes as $child) {
  1686. if (!in_array($child->id, $finalSectionIds)) {
  1687. $finalSectionIds[] = $child->id;
  1688. Log::debug('ExamTypeStrategy: 添加section子节点', [
  1689. 'parent_chapter' => $nodeId,
  1690. 'child_node_id' => $child->id,
  1691. 'child_title' => $child->title,
  1692. 'child_type' => $child->node_type
  1693. ]);
  1694. }
  1695. }
  1696. break;
  1697. case 'section':
  1698. // 如果是section节点,直接使用
  1699. if (!in_array($nodeId, $finalSectionIds)) {
  1700. $finalSectionIds[] = $nodeId;
  1701. Log::debug('ExamTypeStrategy: 直接使用section节点', [
  1702. 'node_id' => $nodeId,
  1703. 'title' => $node->title,
  1704. 'node_type' => $node->node_type
  1705. ]);
  1706. }
  1707. break;
  1708. case 'subsection':
  1709. // 如果是subsection节点,需要找到其父级section节点
  1710. $parentSection = DB::table('textbook_catalog_nodes')
  1711. ->where('id', $node->parent_id)
  1712. ->where('node_type', 'section')
  1713. ->first();
  1714. if ($parentSection && !in_array($parentSection->id, $finalSectionIds)) {
  1715. $finalSectionIds[] = $parentSection->id;
  1716. Log::debug('ExamTypeStrategy: 通过subsection找到父级section', [
  1717. 'subsection_id' => $nodeId,
  1718. 'subsection_title' => $node->title,
  1719. 'parent_section_id' => $parentSection->id,
  1720. 'parent_section_title' => $parentSection->title
  1721. ]);
  1722. }
  1723. break;
  1724. default:
  1725. Log::warning('ExamTypeStrategy: 未知节点类型', [
  1726. 'node_id' => $nodeId,
  1727. 'node_type' => $node->node_type
  1728. ]);
  1729. break;
  1730. }
  1731. }
  1732. Log::info('ExamTypeStrategy: 章节节点解析完成', [
  1733. 'input_count' => count($chapterIdList),
  1734. 'output_section_count' => count($finalSectionIds),
  1735. 'section_ids' => $finalSectionIds
  1736. ]);
  1737. return $finalSectionIds;
  1738. } catch (\Exception $e) {
  1739. Log::error('ExamTypeStrategy: 解析章节节点失败', [
  1740. 'chapter_id_list' => $chapterIdList,
  1741. 'error' => $e->getMessage()
  1742. ]);
  1743. // 出错时返回空数组
  1744. return [];
  1745. }
  1746. }
  1747. // ========== 以下是新增的章节摸底和智能组卷方法 ==========
  1748. /**
  1749. * 章节摸底(新逻辑)
  1750. * - 找第一个未摸底的章节
  1751. * - 用该章节的知识点出题(不扩展子知识点)
  1752. * - 过滤掉没有题目的知识点
  1753. * - 保存时记录 diagnostic_chapter_id
  1754. */
  1755. private function buildChapterDiagnosticParams(array $params): array
  1756. {
  1757. $diagnosticService = app(DiagnosticChapterService::class);
  1758. $textbookId = $params['textbook_id'] ?? null;
  1759. $studentId = (int) ($params['student_id'] ?? 0);
  1760. $grade = $params['grade'] ?? null;
  1761. $totalQuestions = $params['total_questions'] ?? 20;
  1762. Log::info('ExamTypeStrategy: 构建章节摸底参数', [
  1763. 'textbook_id' => $textbookId,
  1764. 'student_id' => $studentId,
  1765. ]);
  1766. if (!$textbookId) {
  1767. Log::warning('ExamTypeStrategy: 章节摸底需要 textbook_id 参数');
  1768. return $this->buildGeneralParams($params);
  1769. }
  1770. // 找第一个未摸底的章节
  1771. $chapterInfo = $diagnosticService->getFirstUndiagnosedChapter((int) $textbookId, $studentId);
  1772. if (empty($chapterInfo) || empty($chapterInfo['kp_codes'])) {
  1773. Log::warning('ExamTypeStrategy: 章节摸底未找到有效章节', [
  1774. 'textbook_id' => $textbookId,
  1775. 'student_id' => $studentId,
  1776. ]);
  1777. return $this->buildGeneralParams($params);
  1778. }
  1779. Log::info('ExamTypeStrategy: 章节摸底参数构建完成', [
  1780. 'textbook_id' => $textbookId,
  1781. 'chapter_id' => $chapterInfo['chapter_id'],
  1782. 'chapter_name' => $chapterInfo['chapter_name'] ?? '',
  1783. 'section_count' => count($chapterInfo['section_ids'] ?? []),
  1784. 'kp_count' => count($chapterInfo['kp_codes']),
  1785. 'total_questions' => $totalQuestions,
  1786. 'is_restart' => $chapterInfo['is_restart'] ?? false,
  1787. ]);
  1788. $enhanced = array_merge($params, [
  1789. 'kp_code_list' => $chapterInfo['kp_codes'],
  1790. 'chapter_id_list' => $chapterInfo['section_ids'],
  1791. 'diagnostic_chapter_id' => $chapterInfo['chapter_id'], // 记录摸底的章节ID
  1792. 'textbook_id' => $textbookId,
  1793. // 注意:不传 grade 参数,禁用"从其他知识点补充"的逻辑
  1794. // 用户需求:题目不够就不够,不从其他知识点补充
  1795. 'paper_name' => $params['paper_name'] ?? ('章节摸底_' . ($chapterInfo['chapter_name'] ?? '') . '_' . now()->format('Ymd_His')),
  1796. 'assembleType' => 0, // 确保 paper_type 记录为摸底
  1797. ]);
  1798. return $this->buildKnowledgePointAssembleParams($enhanced);
  1799. }
  1800. /**
  1801. * 按知识点顺序学习(新逻辑)
  1802. * - 找当前应该学习的章节(有未达标知识点的章节)
  1803. * - 如果该章节未摸底,返回摸底参数
  1804. * - 按顺序找未达标的知识点,最多2个
  1805. * - 如果都达标,进入下一章摸底
  1806. */
  1807. private function buildChapterIntelligentParams(array $params): array
  1808. {
  1809. $diagnosticService = app(DiagnosticChapterService::class);
  1810. $textbookId = $params['textbook_id'] ?? null;
  1811. $studentId = (int) ($params['student_id'] ?? 0);
  1812. $grade = $params['grade'] ?? null;
  1813. $totalQuestions = $params['total_questions'] ?? 20;
  1814. Log::info('ExamTypeStrategy: 构建按知识点顺序学习参数', [
  1815. 'textbook_id' => $textbookId,
  1816. 'student_id' => $studentId,
  1817. ]);
  1818. if (!$textbookId) {
  1819. Log::warning('ExamTypeStrategy: 智能组卷需要 textbook_id 参数');
  1820. return $this->buildGeneralParams($params);
  1821. }
  1822. // 获取当前应该学习的章节
  1823. $chapterInfo = $diagnosticService->getCurrentLearningChapter((int) $textbookId, $studentId, 0.9);
  1824. // 情况1: 所有章节都达标,从第一章重新开始摸底
  1825. if (empty($chapterInfo)) {
  1826. Log::info('ExamTypeStrategy: 所有章节都达标,从第一章重新开始摸底');
  1827. return $this->buildChapterDiagnosticParams($params);
  1828. }
  1829. // 情况2: 当前章节未摸底,需要先摸底
  1830. if (!($chapterInfo['has_diagnostic'] ?? false)) {
  1831. Log::info('ExamTypeStrategy: 当前章节未摸底,先进行摸底', [
  1832. 'chapter_id' => $chapterInfo['chapter_id'],
  1833. ]);
  1834. return $this->buildChapterDiagnosticParams($params);
  1835. }
  1836. // 情况3: 已摸底,按顺序找未达标的知识点
  1837. $unmasteredKpCodes = $diagnosticService->getUnmasteredKpCodesInOrder(
  1838. $studentId,
  1839. $chapterInfo['kp_codes'],
  1840. 0.9, // 阈值
  1841. 2, // 最多2个知识点
  1842. $totalQuestions
  1843. );
  1844. // 情况4: 当前章节所有知识点都达标,进入下一章摸底
  1845. if (empty($unmasteredKpCodes)) {
  1846. Log::info('ExamTypeStrategy: 当前章节所有知识点都达标,进入下一章', [
  1847. 'current_chapter_id' => $chapterInfo['chapter_id'],
  1848. ]);
  1849. // 获取下一章
  1850. $nextChapter = $diagnosticService->getNextChapter((int) $textbookId, $chapterInfo['chapter_id']);
  1851. if ($nextChapter) {
  1852. // 检查下一章是否已摸底
  1853. $hasNextDiagnostic = $diagnosticService->hasChapterDiagnostic($studentId, $nextChapter['chapter_id']);
  1854. if (!$hasNextDiagnostic) {
  1855. Log::info('ExamTypeStrategy: 下一章未摸底,进行摸底', [
  1856. 'next_chapter_id' => $nextChapter['chapter_id'],
  1857. ]);
  1858. // 直接设置下一章的参数,不递归调用
  1859. $enhanced = array_merge($params, [
  1860. 'kp_code_list' => $nextChapter['kp_codes'],
  1861. 'chapter_id_list' => $nextChapter['section_ids'],
  1862. 'diagnostic_chapter_id' => $nextChapter['chapter_id'],
  1863. 'textbook_id' => $textbookId,
  1864. // 注意:不传 grade 参数,禁用"从其他知识点补充"的逻辑
  1865. 'paper_name' => $params['paper_name'] ?? ('章节摸底_' . ($nextChapter['chapter_name'] ?? '') . '_' . now()->format('Ymd_His')),
  1866. 'assembleType' => 0,
  1867. ]);
  1868. return $this->buildKnowledgePointAssembleParams($enhanced);
  1869. } else {
  1870. // 下一章已摸底,找下一章的未达标知识点
  1871. $nextUnmasteredKpCodes = $diagnosticService->getUnmasteredKpCodesInOrder(
  1872. $studentId,
  1873. $nextChapter['kp_codes'],
  1874. 0.9,
  1875. 2,
  1876. $totalQuestions
  1877. );
  1878. if (!empty($nextUnmasteredKpCodes)) {
  1879. $unmasteredKpCodes = $nextUnmasteredKpCodes;
  1880. $chapterInfo = $nextChapter;
  1881. }
  1882. }
  1883. }
  1884. // 如果没有下一章或下一章也都达标,从头开始
  1885. if (empty($unmasteredKpCodes)) {
  1886. Log::info('ExamTypeStrategy: 所有章节都学完,从第一章重新开始');
  1887. return $this->buildChapterDiagnosticParams($params);
  1888. }
  1889. }
  1890. Log::info('ExamTypeStrategy: 按知识点顺序学习参数构建完成', [
  1891. 'textbook_id' => $textbookId,
  1892. 'chapter_id' => $chapterInfo['chapter_id'],
  1893. 'kp_codes' => $unmasteredKpCodes,
  1894. 'kp_count' => count($unmasteredKpCodes),
  1895. 'total_questions' => $totalQuestions,
  1896. ]);
  1897. $enhanced = array_merge($params, [
  1898. 'kp_code_list' => $unmasteredKpCodes,
  1899. 'explanation_kp_codes' => $unmasteredKpCodes, // 学案讲解只显示这些知识点(最多2个)
  1900. 'textbook_id' => $textbookId,
  1901. // 注意:不传 grade 参数,禁用"从其他知识点补充"的逻辑
  1902. // 用户需求:题目不够就不够,不从其他知识点补充
  1903. 'paper_name' => $params['paper_name'] ?? ('智能学习_' . now()->format('Ymd_His')),
  1904. 'assembleType' => 1, // paper_type 记录为智能组卷
  1905. ]);
  1906. return $this->buildKnowledgePointAssembleParams($enhanced);
  1907. }
  1908. }