ExamTypeStrategy.php 80 KB

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