ExamTypeStrategy.php 88 KB

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