ExamTypeStrategy.php 85 KB

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