ExamTypeStrategy.php 61 KB

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