ExamTypeStrategy.php 76 KB

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