ExamTypeStrategy.php 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204
  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. $kpSupplementSubtreeCodes = [];
  1124. if (!empty($kpCodes)) {
  1125. $expandedKpCodes = $this->expandKpCodesWithParentChapterSubtrees($kpCodes);
  1126. $kpSupplementSubtreeCodes = array_values(array_diff($expandedKpCodes, $kpCodes));
  1127. }
  1128. // 组装增强参数
  1129. $enhanced = array_merge($params, [
  1130. 'kp_codes' => $kpCodes, // 可能为空,但仍保留
  1131. 'kp_supplement_subtree_codes' => $kpSupplementSubtreeCodes,
  1132. 'chapter_id_list' => $chapterIdList,
  1133. 'textbook_id' => $textbookId ?: ($params['textbook_id'] ?? null), // 保证智能补充有教材范围
  1134. 'grade' => $grade,
  1135. 'textbook_catalog_node_ids' => $textbookCatalogNodeIds, // 【重要】即使kpCodes为空也设置此参数
  1136. 'exclude_question_ids' => $answeredQuestionIds,
  1137. 'paper_name' => $params['paper_name'] ?? ('教材组题_' . now()->format('Ymd_His')),
  1138. // 教材组卷:按教材特点分配题型
  1139. 'question_type_ratio' => [
  1140. '选择题' => 40,
  1141. '填空题' => 30,
  1142. '解答题' => 30,
  1143. ],
  1144. 'difficulty_ratio' => [
  1145. '基础' => 25,
  1146. '中等' => 50,
  1147. '拔高' => 25,
  1148. ],
  1149. 'question_category' => 0, // question_category=0 代表普通题目
  1150. 'is_textbook_assemble' => true,
  1151. // 【新增】章节知识点数量统计
  1152. 'chapter_knowledge_point_stats' => $chapterKnowledgePointStats,
  1153. ]);
  1154. Log::info('ExamTypeStrategy: 教材组卷参数构建完成', [
  1155. 'chapter_count' => count($chapterIdList),
  1156. 'kp_count' => count($kpCodes),
  1157. 'exclude_count' => count($answeredQuestionIds),
  1158. 'total_questions' => $totalQuestions,
  1159. 'chapter_stats' => $chapterKnowledgePointStats
  1160. ]);
  1161. return $enhanced;
  1162. }
  1163. /**
  1164. * 章节节点 textbook_catalog_nodes 均归属某本教材;未传 textbook_id 时可根据节点 id 反查。
  1165. *
  1166. * @param array<int|string> $chapterIdList 解析后的章节/小节节点 id 列表
  1167. * @return int|null 唯一教材 id;无法解析或节点不存在时返回 null
  1168. */
  1169. private function resolveTextbookIdFromChapterNodes(array $chapterIdList): ?int
  1170. {
  1171. $ids = array_values(array_unique(array_filter(array_map(
  1172. static fn ($id) => (int) $id,
  1173. $chapterIdList
  1174. ), static fn (int $id) => $id > 0)));
  1175. if ($ids === []) {
  1176. return null;
  1177. }
  1178. $textbookIds = DB::table('textbook_catalog_nodes')
  1179. ->whereIn('id', $ids)
  1180. ->pluck('textbook_id')
  1181. ->unique()
  1182. ->values()
  1183. ->all();
  1184. if ($textbookIds === []) {
  1185. Log::warning('ExamTypeStrategy: chapter_id_list 在 textbook_catalog_nodes 中无匹配行', [
  1186. 'chapter_ids' => $ids,
  1187. ]);
  1188. return null;
  1189. }
  1190. if (count($textbookIds) > 1) {
  1191. Log::warning('ExamTypeStrategy: chapter_id_list 对应多本教材,取首个 textbook_id', [
  1192. 'textbook_ids' => $textbookIds,
  1193. 'chapter_ids' => $ids,
  1194. ]);
  1195. }
  1196. return (int) $textbookIds[0];
  1197. }
  1198. /**
  1199. * 根据课本ID获取章节ID列表
  1200. * @param int $textbookId 教材ID
  1201. * @param int|null $endCatalogId 截止章节ID(仅摸底使用),只返回该章节及之前的章节
  1202. */
  1203. private function getTextbookChapterIds(int $textbookId, ?int $endCatalogId = null): array
  1204. {
  1205. try {
  1206. $query = DB::table('textbook_catalog_nodes')
  1207. ->where('textbook_id', $textbookId)
  1208. ->where('node_type', 'section') // nodeType='section'
  1209. ->orderBy('sort_order');
  1210. // 如果指定了截止章节,只获取该章节及之前的章节
  1211. if ($endCatalogId) {
  1212. $endSortOrder = DB::table('textbook_catalog_nodes')
  1213. ->where('id', $endCatalogId)
  1214. ->value('sort_order');
  1215. if ($endSortOrder !== null) {
  1216. $query->where('sort_order', '<=', $endSortOrder);
  1217. Log::debug('ExamTypeStrategy: 应用截止章节过滤', [
  1218. 'end_catalog_id' => $endCatalogId,
  1219. 'end_sort_order' => $endSortOrder
  1220. ]);
  1221. } else {
  1222. Log::warning('ExamTypeStrategy: 截止章节ID无效', [
  1223. 'end_catalog_id' => $endCatalogId
  1224. ]);
  1225. }
  1226. }
  1227. $chapterIds = $query->pluck('id')->toArray();
  1228. Log::debug('ExamTypeStrategy: 查询课本章节ID', [
  1229. 'textbook_id' => $textbookId,
  1230. 'end_catalog_id' => $endCatalogId,
  1231. 'found_count' => count($chapterIds)
  1232. ]);
  1233. return $chapterIds;
  1234. } catch (\Exception $e) {
  1235. Log::error('ExamTypeStrategy: 查询课本章节ID失败', [
  1236. 'textbook_id' => $textbookId,
  1237. 'error' => $e->getMessage()
  1238. ]);
  1239. return [];
  1240. }
  1241. }
  1242. /**
  1243. * 根据章节ID列表获取知识点代码列表(均等抽样版本)
  1244. * 使用"知识点均等抽样"算法,确保覆盖全书章节
  1245. *
  1246. * @param array $chapterIds 章节ID列表
  1247. * @param int $limit 目标题目数量(默认25)
  1248. * @return array 抽样后的知识点代码列表
  1249. */
  1250. private function getKnowledgePointsFromChapters(array $chapterIds, int $limit = 25): array
  1251. {
  1252. try {
  1253. // 如果章节数较少,使用原有逻辑
  1254. if (count($chapterIds) <= 15) {
  1255. Log::info('ExamTypeStrategy: 章节数较少,使用原有逻辑', [
  1256. 'chapter_count' => count($chapterIds)
  1257. ]);
  1258. return $this->getKnowledgePointsFromChaptersLegacy($chapterIds, $limit);
  1259. }
  1260. // ========== 步骤1: 构建全量有序池 ==========
  1261. // 查询所有知识点,按章节顺序排列,去重后得到有序数组
  1262. $allKpData = DB::table('textbook_chapter_knowledge_relation as tckr')
  1263. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  1264. ->whereIn('tckr.catalog_chapter_id', $chapterIds)
  1265. ->where(function ($q) {
  1266. $q->where('tckr.is_deleted', 0)->orWhereNull('tckr.is_deleted');
  1267. })
  1268. ->select('tckr.kp_code', 'tcn.sort_order', 'tcn.id as chapter_id', 'tcn.title as chapter_title')
  1269. ->orderBy('tcn.sort_order', 'asc')
  1270. ->orderBy('tckr.kp_code', 'asc')
  1271. ->get();
  1272. // 去重并构建有序数组
  1273. $allKpCodes = [];
  1274. $chapterInfo = [];
  1275. foreach ($allKpData as $row) {
  1276. if (!in_array($row->kp_code, $allKpCodes)) {
  1277. $allKpCodes[] = $row->kp_code;
  1278. $chapterInfo[$row->kp_code] = [
  1279. 'chapter_id' => $row->chapter_id,
  1280. 'chapter_title' => $row->chapter_title,
  1281. 'sort_order' => $row->sort_order
  1282. ];
  1283. }
  1284. }
  1285. $totalKps = count($allKpCodes);
  1286. Log::info('ExamTypeStrategy: 构建全量有序池完成', [
  1287. 'chapter_count' => count($chapterIds),
  1288. 'total_knowledge_points' => $totalKps,
  1289. 'target_questions' => $limit
  1290. ]);
  1291. // ========== 步骤2: 计算抽样步长 ==========
  1292. $step = $totalKps > 0 ? $totalKps / $limit : 1;
  1293. Log::info('ExamTypeStrategy: 计算抽样步长', [
  1294. 'step' => $step
  1295. ]);
  1296. // ========== 步骤3: 等距取样 ==========
  1297. $selectedKps = [];
  1298. $selectedCount = 0;
  1299. $currentIndex = 0;
  1300. while ($selectedCount < $limit && $selectedCount < $totalKps) {
  1301. $index = (int) floor($currentIndex);
  1302. if ($index < $totalKps && isset($allKpCodes[$index])) {
  1303. $kpCode = $allKpCodes[$index];
  1304. if (!in_array($kpCode, $selectedKps)) {
  1305. $selectedKps[] = $kpCode;
  1306. $selectedCount++;
  1307. }
  1308. }
  1309. $currentIndex += $step;
  1310. }
  1311. // 如果数量不足,循环取样
  1312. if (count($selectedKps) < $limit && $totalKps > 0) {
  1313. Log::info('ExamTypeStrategy: 第一次抽样不足,进行循环取样', [
  1314. 'selected_count' => count($selectedKps),
  1315. 'target_count' => $limit
  1316. ]);
  1317. $needed = $limit - count($selectedKps);
  1318. $startIndex = 0;
  1319. for ($i = 0; $i < $needed && count($selectedKps) < $limit; $i++) {
  1320. $index = ($startIndex + $i) % $totalKps;
  1321. $kpCode = $allKpCodes[$index];
  1322. if (!in_array($kpCode, $selectedKps)) {
  1323. $selectedKps[] = $kpCode;
  1324. }
  1325. }
  1326. }
  1327. // ========== 步骤4: 记录抽样统计 ==========
  1328. $chapterDistribution = [];
  1329. foreach ($selectedKps as $kpCode) {
  1330. if (isset($chapterInfo[$kpCode])) {
  1331. $chapterId = $chapterInfo[$kpCode]['chapter_id'];
  1332. if (!isset($chapterDistribution[$chapterId])) {
  1333. $chapterDistribution[$chapterId] = [
  1334. 'count' => 0,
  1335. 'title' => $chapterInfo[$kpCode]['chapter_title']
  1336. ];
  1337. }
  1338. $chapterDistribution[$chapterId]['count']++;
  1339. }
  1340. }
  1341. Log::info('ExamTypeStrategy: 等距抽样完成', [
  1342. 'total_kps' => $totalKps,
  1343. 'selected_kps' => count($selectedKps),
  1344. 'step' => $step,
  1345. 'chapter_distribution' => $chapterDistribution,
  1346. 'sample_kp_codes' => array_slice($selectedKps, 0, 10)
  1347. ]);
  1348. return array_filter($selectedKps);
  1349. } catch (\Exception $e) {
  1350. Log::error('ExamTypeStrategy: 均等抽样获取章节知识点失败,使用原有逻辑', [
  1351. 'chapter_ids' => $chapterIds,
  1352. 'error' => $e->getMessage()
  1353. ]);
  1354. // 失败时回退到原有逻辑
  1355. return $this->getKnowledgePointsFromChaptersLegacy($chapterIds, $limit);
  1356. }
  1357. }
  1358. /**
  1359. * 原有逻辑(保留作为回退方案)
  1360. * 修复:解决DISTINCT和ORDER BY冲突问题
  1361. */
  1362. private function getKnowledgePointsFromChaptersLegacy(array $chapterIds, int $limit = 25): array
  1363. {
  1364. try {
  1365. // 修复方案1:使用GROUP BY替代DISTINCT,并选择需要的字段
  1366. $kpCodes = DB::table('textbook_chapter_knowledge_relation')
  1367. ->whereIn('catalog_chapter_id', $chapterIds)
  1368. ->where(function ($q) {
  1369. $q->where('is_deleted', 0)->orWhereNull('is_deleted');
  1370. })
  1371. ->select('kp_code')
  1372. ->groupBy('kp_code')
  1373. ->pluck('kp_code')
  1374. ->toArray();
  1375. Log::debug('ExamTypeStrategy: 查询章节知识点(原有逻辑)', [
  1376. 'chapter_count' => count($chapterIds),
  1377. 'found_kp_count' => count($kpCodes)
  1378. ]);
  1379. return array_filter($kpCodes); // 移除空值
  1380. } catch (\Exception $e) {
  1381. Log::error('ExamTypeStrategy: 查询章节知识点失败', [
  1382. 'chapter_ids' => $chapterIds,
  1383. 'error' => $e->getMessage()
  1384. ]);
  1385. return [];
  1386. }
  1387. }
  1388. /**
  1389. * 获取学生已做题目ID列表(用于排除)
  1390. *
  1391. * 唯一来源:从 paper_questions 中取该学生名下所有试卷的题目 ID(questions.id)
  1392. * 确保新卷子不会出现学生做过的重复题目
  1393. */
  1394. private function getStudentAnsweredQuestionIds(string $studentId, array $kpCodes): array
  1395. {
  1396. try {
  1397. $questionIds = PaperQuestion::query()
  1398. ->whereHas('paper', fn ($q) => $q->where('student_id', $studentId))
  1399. ->whereNotNull('question_bank_id')
  1400. ->where('question_bank_id', '>', 0)
  1401. ->distinct()
  1402. ->pluck('question_bank_id')
  1403. ->map(fn ($v) => (int) $v)
  1404. ->values()
  1405. ->toArray();
  1406. Log::debug('ExamTypeStrategy: 从 paper_questions 获取学生已做题目', [
  1407. 'student_id' => $studentId,
  1408. 'exclude_count' => count($questionIds),
  1409. ]);
  1410. return $questionIds;
  1411. } catch (\Exception $e) {
  1412. Log::error('ExamTypeStrategy: 获取学生已做题目失败', [
  1413. 'student_id' => $studentId,
  1414. 'error' => $e->getMessage()
  1415. ]);
  1416. return [];
  1417. }
  1418. }
  1419. /**
  1420. * 通过卷子ID列表查询错题
  1421. * 注意:paper_ids 使用的是 papers 表中的 paper_id 字段,不是 id 字段
  1422. * 错题数据从 mistake_records 表中获取,该表已包含 paper_id 字段
  1423. * 注意:不按学生ID过滤,因为卷子可能包含其他同学的错题,需要收集所有错题
  1424. */
  1425. private function getMistakeQuestionsFromPapers(array $paperIds, ?string $studentId = null): array
  1426. {
  1427. try {
  1428. // 使用 Eloquent 模型查询,从 mistake_records 表中获取错题记录
  1429. // 不按 student_id 过滤,因为要收集所有学生的错题
  1430. $mistakeRecords = MistakeRecord::query()
  1431. ->whereIn('paper_id', $paperIds)
  1432. ->get();
  1433. if ($mistakeRecords->isEmpty()) {
  1434. Log::warning('ExamTypeStrategy: 卷子中未找到错题记录', [
  1435. 'paper_ids' => $paperIds
  1436. ]);
  1437. return [];
  1438. }
  1439. // 收集所有错题的 question_id
  1440. $questionIds = $mistakeRecords->pluck('question_id')
  1441. ->filter()
  1442. ->unique()
  1443. ->values()
  1444. ->toArray();
  1445. Log::info('ExamTypeStrategy: 查询卷子错题完成', [
  1446. 'paper_count' => count($paperIds),
  1447. 'paper_ids_input' => $paperIds,
  1448. 'mistake_record_count' => $mistakeRecords->count(),
  1449. 'unique_question_count' => count($questionIds),
  1450. 'question_ids' => array_slice($questionIds, 0, 20), // 最多记录20个ID
  1451. 'per_paper_stats' => $mistakeRecords->groupBy('paper_id')->map->count()->toArray()
  1452. ]);
  1453. return array_filter($questionIds);
  1454. } catch (\Exception $e) {
  1455. Log::error('ExamTypeStrategy: 查询卷子错题失败', [
  1456. 'paper_ids' => $paperIds,
  1457. 'error' => $e->getMessage()
  1458. ]);
  1459. return [];
  1460. }
  1461. }
  1462. /**
  1463. * 通过题目ID列表获取知识点代码列表
  1464. */
  1465. private function getKnowledgePointsFromQuestions(array $questionIds): array
  1466. {
  1467. try {
  1468. // 使用 Eloquent 模型查询,获取题目的知识点
  1469. $questions = Question::whereIn('id', $questionIds)
  1470. ->whereNotNull('kp_code')
  1471. ->where('kp_code', '!=', '')
  1472. ->distinct()
  1473. ->pluck('kp_code')
  1474. ->toArray();
  1475. Log::debug('ExamTypeStrategy: 查询题目知识点', [
  1476. 'question_count' => count($questionIds),
  1477. 'kp_count' => count($questions)
  1478. ]);
  1479. return array_filter($questions);
  1480. } catch (\Exception $e) {
  1481. Log::error('ExamTypeStrategy: 查询题目知识点失败', [
  1482. 'question_ids' => array_slice($questionIds, 0, 10), // 只记录前10个
  1483. 'error' => $e->getMessage()
  1484. ]);
  1485. return [];
  1486. }
  1487. }
  1488. /**
  1489. * 通过卷子ID列表获取卷子题目ID
  1490. */
  1491. private function getQuestionIdsFromPapers(array $paperIds): array
  1492. {
  1493. try {
  1494. $questionIds = DB::table('paper_questions')
  1495. ->whereIn('paper_id', $paperIds)
  1496. ->pluck('question_bank_id')
  1497. ->unique()
  1498. ->filter()
  1499. ->values()
  1500. ->toArray();
  1501. Log::debug('ExamTypeStrategy: 获取卷子题目ID', [
  1502. 'paper_ids' => $paperIds,
  1503. 'question_count' => count($questionIds)
  1504. ]);
  1505. return $questionIds;
  1506. } catch (\Exception $e) {
  1507. Log::error('ExamTypeStrategy: 获取卷子题目ID失败', [
  1508. 'paper_ids' => $paperIds,
  1509. 'error' => $e->getMessage()
  1510. ]);
  1511. return [];
  1512. }
  1513. }
  1514. /**
  1515. * 通过卷子ID列表获取题目知识点(直接使用 paper_questions.knowledge_point)
  1516. */
  1517. private function getKnowledgePointsFromPaperQuestions(array $paperIds): array
  1518. {
  1519. try {
  1520. $knowledgePoints = DB::table('paper_questions')
  1521. ->whereIn('paper_id', $paperIds)
  1522. ->whereNotNull('knowledge_point')
  1523. ->where('knowledge_point', '!=', '')
  1524. ->pluck('knowledge_point')
  1525. ->unique()
  1526. ->filter()
  1527. ->values()
  1528. ->toArray();
  1529. Log::debug('ExamTypeStrategy: 获取卷子题目知识点', [
  1530. 'paper_ids' => $paperIds,
  1531. 'kp_count' => count($knowledgePoints),
  1532. ]);
  1533. return $knowledgePoints;
  1534. } catch (\Exception $e) {
  1535. Log::error('ExamTypeStrategy: 获取卷子题目知识点失败', [
  1536. 'paper_ids' => $paperIds,
  1537. 'error' => $e->getMessage()
  1538. ]);
  1539. return [];
  1540. }
  1541. }
  1542. /**
  1543. * 通过卷子ID列表获取难度/题量/总分的聚合信息
  1544. */
  1545. private function getPaperAggregateStats(array $paperIds): array
  1546. {
  1547. try {
  1548. $rows = DB::table('papers')
  1549. ->whereIn('paper_id', $paperIds)
  1550. ->select(['paper_id', 'difficulty_category', 'total_questions', 'total_score'])
  1551. ->get();
  1552. $perPaper = [];
  1553. $difficultyValues = [];
  1554. $questionValues = [];
  1555. $scoreValues = [];
  1556. foreach ($rows as $row) {
  1557. $difficulty = is_null($row->difficulty_category) ? null : (int) $row->difficulty_category;
  1558. $totalQuestions = is_null($row->total_questions) ? null : (int) $row->total_questions;
  1559. $totalScore = is_null($row->total_score) ? null : (float) $row->total_score;
  1560. $perPaper[$row->paper_id] = [
  1561. 'difficulty_category' => $difficulty,
  1562. 'total_questions' => $totalQuestions,
  1563. 'total_score' => $totalScore,
  1564. 'raw_total_questions' => $row->total_questions,
  1565. ];
  1566. if (!is_null($difficulty)) {
  1567. $difficultyValues[] = $difficulty;
  1568. }
  1569. if (!empty($totalQuestions)) {
  1570. $questionValues[] = $totalQuestions;
  1571. }
  1572. if (!is_null($totalScore)) {
  1573. $scoreValues[] = $totalScore;
  1574. }
  1575. }
  1576. $stats = [
  1577. 'difficulty_category_min' => empty($difficultyValues) ? null : min($difficultyValues),
  1578. 'total_questions_max' => empty($questionValues) ? null : max($questionValues),
  1579. 'total_score_max' => empty($scoreValues) ? null : max($scoreValues),
  1580. ];
  1581. if (empty($stats['total_questions_max'])) {
  1582. $stats['total_questions_max'] = DB::table('paper_questions')
  1583. ->whereIn('paper_id', $paperIds)
  1584. ->selectRaw('paper_id, COUNT(*) as cnt')
  1585. ->groupBy('paper_id')
  1586. ->pluck('cnt')
  1587. ->max();
  1588. }
  1589. Log::info('ExamTypeStrategy: 获取卷子聚合信息', [
  1590. 'paper_ids' => $paperIds,
  1591. 'per_paper' => $perPaper,
  1592. 'stats' => $stats,
  1593. ]);
  1594. return $stats;
  1595. } catch (\Exception $e) {
  1596. Log::error('ExamTypeStrategy: 获取卷子聚合信息失败', [
  1597. 'paper_ids' => $paperIds,
  1598. 'error' => $e->getMessage()
  1599. ]);
  1600. return [];
  1601. }
  1602. }
  1603. /**
  1604. * 【新增】获取每个章节对应的知识点数量统计
  1605. * 通过textbook_chapter_knowledge_relation表关联查询
  1606. *
  1607. * @param array $chapterIdList 章节ID列表
  1608. * @return array 章节知识点数量统计
  1609. */
  1610. private function getChapterKnowledgePointStats(array $chapterIdList): array
  1611. {
  1612. try {
  1613. // 查询每个章节对应的知识点数量
  1614. $stats = DB::table('textbook_chapter_knowledge_relation as tckr')
  1615. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  1616. ->whereIn('tckr.catalog_chapter_id', $chapterIdList)
  1617. ->where(function ($q) {
  1618. $q->where('tckr.is_deleted', 0)->orWhereNull('tckr.is_deleted');
  1619. })
  1620. ->select(
  1621. 'tckr.catalog_chapter_id as chapter_id',
  1622. 'tcn.title as chapter_title',
  1623. DB::raw('COUNT(DISTINCT tckr.kp_code) as knowledge_point_count')
  1624. )
  1625. ->groupBy('tckr.catalog_chapter_id', 'tcn.title')
  1626. ->orderBy('tckr.catalog_chapter_id')
  1627. ->get();
  1628. // 转换为数组格式
  1629. $result = [];
  1630. foreach ($stats as $stat) {
  1631. $result[] = [
  1632. 'chapter_id' => $stat->chapter_id,
  1633. 'chapter_title' => $stat->chapter_title,
  1634. 'knowledge_point_count' => (int) $stat->knowledge_point_count
  1635. ];
  1636. }
  1637. Log::debug('ExamTypeStrategy: 获取章节知识点统计', [
  1638. 'chapter_count' => count($chapterIdList),
  1639. 'stats_count' => count($result),
  1640. 'stats' => $result
  1641. ]);
  1642. return $result;
  1643. } catch (\Exception $e) {
  1644. Log::error('ExamTypeStrategy: 获取章节知识点统计失败', [
  1645. 'chapter_id_list' => $chapterIdList,
  1646. 'error' => $e->getMessage()
  1647. ]);
  1648. // 返回空数组,不影响组卷流程
  1649. return [];
  1650. }
  1651. }
  1652. /**
  1653. * 【新增】递归获取section节点ID列表
  1654. * 根据用户传入的chapter_id_list,自动识别节点类型:
  1655. * - 如果是chapter节点,查找其下的所有section子节点(不包含subsection)
  1656. * - 如果是section节点,直接使用
  1657. *
  1658. * @param array $chapterIdList 用户传入的章节ID列表
  1659. * @return array 最终用于查询知识点的section节点ID列表
  1660. */
  1661. private function resolveSectionNodesFromChapters(array $chapterIdList): array
  1662. {
  1663. try {
  1664. if (empty($chapterIdList)) {
  1665. return [];
  1666. }
  1667. Log::info('ExamTypeStrategy: 开始解析章节节点', [
  1668. 'input_chapter_ids' => $chapterIdList
  1669. ]);
  1670. $finalSectionIds = [];
  1671. foreach ($chapterIdList as $nodeId) {
  1672. // 查询节点信息
  1673. $node = DB::table('textbook_catalog_nodes')
  1674. ->where('id', $nodeId)
  1675. ->first();
  1676. if (!$node) {
  1677. Log::warning('ExamTypeStrategy: 未找到节点', ['node_id' => $nodeId]);
  1678. continue;
  1679. }
  1680. Log::debug('ExamTypeStrategy: 处理节点', [
  1681. 'node_id' => $nodeId,
  1682. 'node_type' => $node->node_type,
  1683. 'title' => $node->title
  1684. ]);
  1685. // 根据节点类型处理
  1686. switch ($node->node_type) {
  1687. case 'chapter':
  1688. // 如果是chapter节点,查找其下的所有section子节点
  1689. $childNodes = DB::table('textbook_catalog_nodes')
  1690. ->where('parent_id', $nodeId)
  1691. ->where('node_type', 'section')
  1692. ->orderBy('sort_order')
  1693. ->get();
  1694. Log::info('ExamTypeStrategy: 解析chapter节点', [
  1695. 'chapter_id' => $nodeId,
  1696. 'chapter_title' => $node->title,
  1697. 'section_count' => count($childNodes)
  1698. ]);
  1699. foreach ($childNodes as $child) {
  1700. if (!in_array($child->id, $finalSectionIds)) {
  1701. $finalSectionIds[] = $child->id;
  1702. Log::debug('ExamTypeStrategy: 添加section子节点', [
  1703. 'parent_chapter' => $nodeId,
  1704. 'child_node_id' => $child->id,
  1705. 'child_title' => $child->title,
  1706. 'child_type' => $child->node_type
  1707. ]);
  1708. }
  1709. }
  1710. break;
  1711. case 'section':
  1712. // 如果是section节点,直接使用
  1713. if (!in_array($nodeId, $finalSectionIds)) {
  1714. $finalSectionIds[] = $nodeId;
  1715. Log::debug('ExamTypeStrategy: 直接使用section节点', [
  1716. 'node_id' => $nodeId,
  1717. 'title' => $node->title,
  1718. 'node_type' => $node->node_type
  1719. ]);
  1720. }
  1721. break;
  1722. case 'subsection':
  1723. // 如果是subsection节点,需要找到其父级section节点
  1724. $parentSection = DB::table('textbook_catalog_nodes')
  1725. ->where('id', $node->parent_id)
  1726. ->where('node_type', 'section')
  1727. ->first();
  1728. if ($parentSection && !in_array($parentSection->id, $finalSectionIds)) {
  1729. $finalSectionIds[] = $parentSection->id;
  1730. Log::debug('ExamTypeStrategy: 通过subsection找到父级section', [
  1731. 'subsection_id' => $nodeId,
  1732. 'subsection_title' => $node->title,
  1733. 'parent_section_id' => $parentSection->id,
  1734. 'parent_section_title' => $parentSection->title
  1735. ]);
  1736. }
  1737. break;
  1738. default:
  1739. Log::warning('ExamTypeStrategy: 未知节点类型', [
  1740. 'node_id' => $nodeId,
  1741. 'node_type' => $node->node_type
  1742. ]);
  1743. break;
  1744. }
  1745. }
  1746. Log::info('ExamTypeStrategy: 章节节点解析完成', [
  1747. 'input_count' => count($chapterIdList),
  1748. 'output_section_count' => count($finalSectionIds),
  1749. 'section_ids' => $finalSectionIds
  1750. ]);
  1751. return $finalSectionIds;
  1752. } catch (\Exception $e) {
  1753. Log::error('ExamTypeStrategy: 解析章节节点失败', [
  1754. 'chapter_id_list' => $chapterIdList,
  1755. 'error' => $e->getMessage()
  1756. ]);
  1757. // 出错时返回空数组
  1758. return [];
  1759. }
  1760. }
  1761. // ========== 以下是新增的章节摸底和智能组卷方法 ==========
  1762. /**
  1763. * 章节摸底(新逻辑)
  1764. * - 找第一个未摸底的章节
  1765. * - 用该章节的知识点出题(不扩展子知识点)
  1766. * - 过滤掉没有题目的知识点
  1767. * - 保存时记录 diagnostic_chapter_id
  1768. */
  1769. private function buildChapterDiagnosticParams(array $params): array
  1770. {
  1771. $diagnosticService = app(DiagnosticChapterService::class);
  1772. $textbookId = $params['textbook_id'] ?? null;
  1773. $studentId = (int) ($params['student_id'] ?? 0);
  1774. $grade = $params['grade'] ?? null;
  1775. $totalQuestions = $params['total_questions'] ?? self::defaultTotalQuestions();
  1776. Log::info('ExamTypeStrategy: 构建章节摸底参数', [
  1777. 'textbook_id' => $textbookId,
  1778. 'student_id' => $studentId,
  1779. ]);
  1780. if (!$textbookId) {
  1781. Log::warning('ExamTypeStrategy: 章节摸底需要 textbook_id 参数');
  1782. return $this->buildGeneralParams($params);
  1783. }
  1784. // 找章节摸底目标:
  1785. // - 传了 chapter_id_list:按指定章节顺序找有题章节(允许重复摸底)
  1786. // - 未传:走默认未摸底优先逻辑
  1787. $chapterInfo = $diagnosticService->getFirstUndiagnosedChapter(
  1788. (int) $textbookId,
  1789. $studentId,
  1790. $params['chapter_id_list'] ?? null
  1791. );
  1792. if (empty($chapterInfo) || empty($chapterInfo['kp_codes'])) {
  1793. Log::warning('ExamTypeStrategy: 章节摸底未找到有效章节', [
  1794. 'textbook_id' => $textbookId,
  1795. 'student_id' => $studentId,
  1796. ]);
  1797. return $this->buildGeneralParams($params);
  1798. }
  1799. Log::info('ExamTypeStrategy: 章节摸底参数构建完成', [
  1800. 'textbook_id' => $textbookId,
  1801. 'chapter_id' => $chapterInfo['chapter_id'],
  1802. 'chapter_name' => $chapterInfo['chapter_name'] ?? '',
  1803. 'section_count' => count($chapterInfo['section_ids'] ?? []),
  1804. 'kp_count' => count($chapterInfo['kp_codes']),
  1805. 'total_questions' => $totalQuestions,
  1806. 'is_restart' => $chapterInfo['is_restart'] ?? false,
  1807. ]);
  1808. $enhanced = array_merge($params, [
  1809. 'kp_code_list' => $chapterInfo['kp_codes'],
  1810. 'chapter_id_list' => $chapterInfo['section_ids'],
  1811. 'diagnostic_chapter_id' => $chapterInfo['chapter_id'], // 记录摸底的章节ID
  1812. 'textbook_id' => $textbookId,
  1813. // 注意:不传 grade 参数,禁用"从其他知识点补充"的逻辑
  1814. // 用户需求:题目不够就不够,不从其他知识点补充
  1815. 'paper_name' => $params['paper_name'] ?? ('章节摸底_' . ($chapterInfo['chapter_name'] ?? '') . '_' . now()->format('Ymd_His')),
  1816. 'assembleType' => 0, // 确保 paper_type 记录为摸底
  1817. ]);
  1818. return $this->buildKnowledgePointAssembleParams($enhanced);
  1819. }
  1820. /**
  1821. * 按知识点顺序学习(新逻辑)
  1822. * - 找当前应该学习的章节(有未达标知识点的章节)
  1823. * - 如果该章节未摸底,返回摸底参数
  1824. * - 按顺序找未达标的知识点,最多2个
  1825. * - 如果都达标,进入下一章摸底
  1826. */
  1827. private function buildChapterIntelligentParams(array $params): array
  1828. {
  1829. $diagnosticService = app(DiagnosticChapterService::class);
  1830. $textbookId = $params['textbook_id'] ?? null;
  1831. $studentId = (int) ($params['student_id'] ?? 0);
  1832. $grade = $params['grade'] ?? null;
  1833. $totalQuestions = $params['total_questions'] ?? self::defaultTotalQuestions();
  1834. Log::info('ExamTypeStrategy: 构建按知识点顺序学习参数', [
  1835. 'textbook_id' => $textbookId,
  1836. 'student_id' => $studentId,
  1837. ]);
  1838. if (!$textbookId) {
  1839. Log::warning('ExamTypeStrategy: 智能组卷需要 textbook_id 参数');
  1840. return $this->buildGeneralParams($params);
  1841. }
  1842. // 获取当前应该学习的章节
  1843. $chapterInfo = $diagnosticService->getCurrentLearningChapter((int) $textbookId, $studentId, 0.9);
  1844. // 情况1: 所有章节都达标,从第一章重新开始摸底
  1845. if (empty($chapterInfo)) {
  1846. Log::info('ExamTypeStrategy: 所有章节都达标,从第一章重新开始摸底');
  1847. return $this->buildChapterDiagnosticParams($params);
  1848. }
  1849. // 情况2: 当前章节未摸底,需要先摸底
  1850. if (!($chapterInfo['has_diagnostic'] ?? false)) {
  1851. Log::info('ExamTypeStrategy: 当前章节未摸底,先进行摸底', [
  1852. 'chapter_id' => $chapterInfo['chapter_id'],
  1853. ]);
  1854. return $this->buildChapterDiagnosticParams($params);
  1855. }
  1856. // 情况3: 已摸底,按顺序找未达标的知识点
  1857. $unmasteredKpCodes = $diagnosticService->getUnmasteredKpCodesInOrder(
  1858. $studentId,
  1859. $chapterInfo['kp_codes'],
  1860. 0.9, // 阈值
  1861. 2, // 最多2个知识点
  1862. $totalQuestions
  1863. );
  1864. // 情况4: 当前章节所有知识点都达标,进入下一章摸底
  1865. if (empty($unmasteredKpCodes)) {
  1866. Log::info('ExamTypeStrategy: 当前章节所有知识点都达标,进入下一章', [
  1867. 'current_chapter_id' => $chapterInfo['chapter_id'],
  1868. ]);
  1869. // 获取下一章
  1870. $nextChapter = $diagnosticService->getNextChapter((int) $textbookId, $chapterInfo['chapter_id']);
  1871. if ($nextChapter) {
  1872. // 检查下一章是否已摸底
  1873. $hasNextDiagnostic = $diagnosticService->hasChapterDiagnostic($studentId, $nextChapter['chapter_id']);
  1874. if (!$hasNextDiagnostic) {
  1875. Log::info('ExamTypeStrategy: 下一章未摸底,进行摸底', [
  1876. 'next_chapter_id' => $nextChapter['chapter_id'],
  1877. ]);
  1878. // 直接设置下一章的参数,不递归调用
  1879. $enhanced = array_merge($params, [
  1880. 'kp_code_list' => $nextChapter['kp_codes'],
  1881. 'chapter_id_list' => $nextChapter['section_ids'],
  1882. 'diagnostic_chapter_id' => $nextChapter['chapter_id'],
  1883. 'textbook_id' => $textbookId,
  1884. // 注意:不传 grade 参数,禁用"从其他知识点补充"的逻辑
  1885. 'paper_name' => $params['paper_name'] ?? ('章节摸底_' . ($nextChapter['chapter_name'] ?? '') . '_' . now()->format('Ymd_His')),
  1886. 'assembleType' => 0,
  1887. ]);
  1888. return $this->buildKnowledgePointAssembleParams($enhanced);
  1889. } else {
  1890. // 下一章已摸底,找下一章的未达标知识点
  1891. $nextUnmasteredKpCodes = $diagnosticService->getUnmasteredKpCodesInOrder(
  1892. $studentId,
  1893. $nextChapter['kp_codes'],
  1894. 0.9,
  1895. 2,
  1896. $totalQuestions
  1897. );
  1898. if (!empty($nextUnmasteredKpCodes)) {
  1899. $unmasteredKpCodes = $nextUnmasteredKpCodes;
  1900. $chapterInfo = $nextChapter;
  1901. }
  1902. }
  1903. }
  1904. // 如果没有下一章或下一章也都达标,从头开始
  1905. if (empty($unmasteredKpCodes)) {
  1906. Log::info('ExamTypeStrategy: 所有章节都学完,从第一章重新开始');
  1907. return $this->buildChapterDiagnosticParams($params);
  1908. }
  1909. }
  1910. Log::info('ExamTypeStrategy: 按知识点顺序学习参数构建完成', [
  1911. 'textbook_id' => $textbookId,
  1912. 'chapter_id' => $chapterInfo['chapter_id'],
  1913. 'kp_codes' => $unmasteredKpCodes,
  1914. 'kp_count' => count($unmasteredKpCodes),
  1915. 'total_questions' => $totalQuestions,
  1916. ]);
  1917. $enhanced = array_merge($params, [
  1918. 'kp_code_list' => $unmasteredKpCodes,
  1919. 'explanation_kp_codes' => $unmasteredKpCodes, // 学案讲解只显示这些知识点(最多2个)
  1920. 'textbook_id' => $textbookId,
  1921. // 注意:不传 grade 参数,禁用"从其他知识点补充"的逻辑
  1922. // 用户需求:题目不够就不够,不从其他知识点补充
  1923. 'paper_name' => $params['paper_name'] ?? ('智能学习_' . now()->format('Ymd_His')),
  1924. 'assembleType' => 1, // paper_type 记录为智能组卷
  1925. ]);
  1926. return $this->buildKnowledgePointAssembleParams($enhanced);
  1927. }
  1928. }