ExamTypeStrategy.php 62 KB

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