ExamTypeStrategy.php 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  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. */
  1059. private function getKnowledgePointsFromChaptersLegacy(array $chapterIds, int $limit = 25): array
  1060. {
  1061. try {
  1062. // 查询 textbook_chapter_knowledge_relation 表(修复:添加排序避免数据偏向)
  1063. $kpCodes = DB::table('textbook_chapter_knowledge_relation as tckr')
  1064. ->leftJoin('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  1065. ->whereIn('tckr.catalog_chapter_id', $chapterIds)
  1066. ->orderBy('tcn.sort_order', 'asc')
  1067. ->orderBy('tckr.kp_code', 'asc')
  1068. ->limit($limit)
  1069. ->distinct()
  1070. ->pluck('tckr.kp_code')
  1071. ->toArray();
  1072. Log::debug('ExamTypeStrategy: 查询章节知识点(原有逻辑)', [
  1073. 'chapter_count' => count($chapterIds),
  1074. 'found_kp_count' => count($kpCodes)
  1075. ]);
  1076. return array_filter($kpCodes); // 移除空值
  1077. } catch (\Exception $e) {
  1078. Log::error('ExamTypeStrategy: 查询章节知识点失败', [
  1079. 'chapter_ids' => $chapterIds,
  1080. 'error' => $e->getMessage()
  1081. ]);
  1082. return [];
  1083. }
  1084. }
  1085. /**
  1086. * 获取学生已答题目ID列表(用于排除)
  1087. */
  1088. private function getStudentAnsweredQuestionIds(string $studentId, array $kpCodes): array
  1089. {
  1090. try {
  1091. // 【修复】查询 student_answer_questions 表,不使用 kp_code 过滤(该字段可能不存在)
  1092. $query = DB::table('student_answer_questions')
  1093. ->where('student_id', $studentId)
  1094. ->distinct();
  1095. // 如果有 question_id 字段,直接查询
  1096. $questionIds = $query->pluck('question_id')->toArray();
  1097. Log::debug('ExamTypeStrategy: 查询学生已答题目', [
  1098. 'student_id' => $studentId,
  1099. 'kp_count' => count($kpCodes),
  1100. 'answered_count' => count($questionIds),
  1101. 'note' => '只按学生ID过滤,不按kp_code过滤'
  1102. ]);
  1103. return array_filter($questionIds); // 移除空值
  1104. } catch (\Exception $e) {
  1105. Log::error('ExamTypeStrategy: 查询学生已答题目失败', [
  1106. 'student_id' => $studentId,
  1107. 'error' => $e->getMessage()
  1108. ]);
  1109. return [];
  1110. }
  1111. }
  1112. /**
  1113. * 通过卷子ID列表查询错题
  1114. * 注意:paper_ids 使用的是 papers 表中的 paper_id 字段,不是 id 字段
  1115. * 错题数据从 mistake_records 表中获取,该表已包含 paper_id 字段
  1116. * 注意:不按学生ID过滤,因为卷子可能包含其他同学的错题,需要收集所有错题
  1117. */
  1118. private function getMistakeQuestionsFromPapers(array $paperIds, ?string $studentId = null): array
  1119. {
  1120. try {
  1121. // 使用 Eloquent 模型查询,从 mistake_records 表中获取错题记录
  1122. // 不按 student_id 过滤,因为要收集所有学生的错题
  1123. $mistakeRecords = MistakeRecord::query()
  1124. ->whereIn('paper_id', $paperIds)
  1125. ->get();
  1126. if ($mistakeRecords->isEmpty()) {
  1127. Log::warning('ExamTypeStrategy: 卷子中未找到错题记录', [
  1128. 'paper_ids' => $paperIds
  1129. ]);
  1130. return [];
  1131. }
  1132. // 收集所有错题的 question_id
  1133. $questionIds = $mistakeRecords->pluck('question_id')
  1134. ->filter()
  1135. ->unique()
  1136. ->values()
  1137. ->toArray();
  1138. Log::info('ExamTypeStrategy: 查询卷子错题完成', [
  1139. 'paper_count' => count($paperIds),
  1140. 'paper_ids_input' => $paperIds,
  1141. 'mistake_record_count' => $mistakeRecords->count(),
  1142. 'unique_question_count' => count($questionIds),
  1143. 'question_ids' => array_slice($questionIds, 0, 20), // 最多记录20个ID
  1144. 'per_paper_stats' => $mistakeRecords->groupBy('paper_id')->map->count()->toArray()
  1145. ]);
  1146. return array_filter($questionIds);
  1147. } catch (\Exception $e) {
  1148. Log::error('ExamTypeStrategy: 查询卷子错题失败', [
  1149. 'paper_ids' => $paperIds,
  1150. 'error' => $e->getMessage()
  1151. ]);
  1152. return [];
  1153. }
  1154. }
  1155. /**
  1156. * 通过题目ID列表获取知识点代码列表
  1157. */
  1158. private function getKnowledgePointsFromQuestions(array $questionIds): array
  1159. {
  1160. try {
  1161. // 使用 Eloquent 模型查询,获取题目的知识点
  1162. $questions = Question::whereIn('id', $questionIds)
  1163. ->whereNotNull('kp_code')
  1164. ->where('kp_code', '!=', '')
  1165. ->distinct()
  1166. ->pluck('kp_code')
  1167. ->toArray();
  1168. Log::debug('ExamTypeStrategy: 查询题目知识点', [
  1169. 'question_count' => count($questionIds),
  1170. 'kp_count' => count($questions)
  1171. ]);
  1172. return array_filter($questions);
  1173. } catch (\Exception $e) {
  1174. Log::error('ExamTypeStrategy: 查询题目知识点失败', [
  1175. 'question_ids' => array_slice($questionIds, 0, 10), // 只记录前10个
  1176. 'error' => $e->getMessage()
  1177. ]);
  1178. return [];
  1179. }
  1180. }
  1181. /**
  1182. * 【新增】获取每个章节对应的知识点数量统计
  1183. * 通过textbook_chapter_knowledge_relation表关联查询
  1184. *
  1185. * @param array $chapterIdList 章节ID列表
  1186. * @return array 章节知识点数量统计
  1187. */
  1188. private function getChapterKnowledgePointStats(array $chapterIdList): array
  1189. {
  1190. try {
  1191. // 查询每个章节对应的知识点数量
  1192. $stats = DB::table('textbook_chapter_knowledge_relation as tckr')
  1193. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  1194. ->whereIn('tckr.catalog_chapter_id', $chapterIdList)
  1195. ->select(
  1196. 'tckr.catalog_chapter_id as chapter_id',
  1197. 'tcn.title as chapter_title',
  1198. DB::raw('COUNT(DISTINCT tckr.kp_code) as knowledge_point_count')
  1199. )
  1200. ->groupBy('tckr.catalog_chapter_id', 'tcn.title')
  1201. ->orderBy('tckr.catalog_chapter_id')
  1202. ->get();
  1203. // 转换为数组格式
  1204. $result = [];
  1205. foreach ($stats as $stat) {
  1206. $result[] = [
  1207. 'chapter_id' => $stat->chapter_id,
  1208. 'chapter_title' => $stat->chapter_title,
  1209. 'knowledge_point_count' => (int) $stat->knowledge_point_count
  1210. ];
  1211. }
  1212. Log::debug('ExamTypeStrategy: 获取章节知识点统计', [
  1213. 'chapter_count' => count($chapterIdList),
  1214. 'stats_count' => count($result),
  1215. 'stats' => $result
  1216. ]);
  1217. return $result;
  1218. } catch (\Exception $e) {
  1219. Log::error('ExamTypeStrategy: 获取章节知识点统计失败', [
  1220. 'chapter_id_list' => $chapterIdList,
  1221. 'error' => $e->getMessage()
  1222. ]);
  1223. // 返回空数组,不影响组卷流程
  1224. return [];
  1225. }
  1226. }
  1227. /**
  1228. * 【新增】递归获取section节点ID列表
  1229. * 根据用户传入的chapter_id_list,自动识别节点类型:
  1230. * - 如果是chapter节点,查找其下的所有section子节点(不包含subsection)
  1231. * - 如果是section节点,直接使用
  1232. *
  1233. * @param array $chapterIdList 用户传入的章节ID列表
  1234. * @return array 最终用于查询知识点的section节点ID列表
  1235. */
  1236. private function resolveSectionNodesFromChapters(array $chapterIdList): array
  1237. {
  1238. try {
  1239. if (empty($chapterIdList)) {
  1240. return [];
  1241. }
  1242. Log::info('ExamTypeStrategy: 开始解析章节节点', [
  1243. 'input_chapter_ids' => $chapterIdList
  1244. ]);
  1245. $finalSectionIds = [];
  1246. foreach ($chapterIdList as $nodeId) {
  1247. // 查询节点信息
  1248. $node = DB::table('textbook_catalog_nodes')
  1249. ->where('id', $nodeId)
  1250. ->first();
  1251. if (!$node) {
  1252. Log::warning('ExamTypeStrategy: 未找到节点', ['node_id' => $nodeId]);
  1253. continue;
  1254. }
  1255. Log::debug('ExamTypeStrategy: 处理节点', [
  1256. 'node_id' => $nodeId,
  1257. 'node_type' => $node->node_type,
  1258. 'title' => $node->title
  1259. ]);
  1260. // 根据节点类型处理
  1261. switch ($node->node_type) {
  1262. case 'chapter':
  1263. // 如果是chapter节点,查找其下的所有section子节点
  1264. $childNodes = DB::table('textbook_catalog_nodes')
  1265. ->where('parent_id', $nodeId)
  1266. ->where('node_type', 'section')
  1267. ->orderBy('sort_order')
  1268. ->get();
  1269. Log::info('ExamTypeStrategy: 解析chapter节点', [
  1270. 'chapter_id' => $nodeId,
  1271. 'chapter_title' => $node->title,
  1272. 'section_count' => count($childNodes)
  1273. ]);
  1274. foreach ($childNodes as $child) {
  1275. if (!in_array($child->id, $finalSectionIds)) {
  1276. $finalSectionIds[] = $child->id;
  1277. Log::debug('ExamTypeStrategy: 添加section子节点', [
  1278. 'parent_chapter' => $nodeId,
  1279. 'child_node_id' => $child->id,
  1280. 'child_title' => $child->title,
  1281. 'child_type' => $child->node_type
  1282. ]);
  1283. }
  1284. }
  1285. break;
  1286. case 'section':
  1287. // 如果是section节点,直接使用
  1288. if (!in_array($nodeId, $finalSectionIds)) {
  1289. $finalSectionIds[] = $nodeId;
  1290. Log::debug('ExamTypeStrategy: 直接使用section节点', [
  1291. 'node_id' => $nodeId,
  1292. 'title' => $node->title,
  1293. 'node_type' => $node->node_type
  1294. ]);
  1295. }
  1296. break;
  1297. case 'subsection':
  1298. // 如果是subsection节点,需要找到其父级section节点
  1299. $parentSection = DB::table('textbook_catalog_nodes')
  1300. ->where('id', $node->parent_id)
  1301. ->where('node_type', 'section')
  1302. ->first();
  1303. if ($parentSection && !in_array($parentSection->id, $finalSectionIds)) {
  1304. $finalSectionIds[] = $parentSection->id;
  1305. Log::debug('ExamTypeStrategy: 通过subsection找到父级section', [
  1306. 'subsection_id' => $nodeId,
  1307. 'subsection_title' => $node->title,
  1308. 'parent_section_id' => $parentSection->id,
  1309. 'parent_section_title' => $parentSection->title
  1310. ]);
  1311. }
  1312. break;
  1313. default:
  1314. Log::warning('ExamTypeStrategy: 未知节点类型', [
  1315. 'node_id' => $nodeId,
  1316. 'node_type' => $node->node_type
  1317. ]);
  1318. break;
  1319. }
  1320. }
  1321. Log::info('ExamTypeStrategy: 章节节点解析完成', [
  1322. 'input_count' => count($chapterIdList),
  1323. 'output_section_count' => count($finalSectionIds),
  1324. 'section_ids' => $finalSectionIds
  1325. ]);
  1326. return $finalSectionIds;
  1327. } catch (\Exception $e) {
  1328. Log::error('ExamTypeStrategy: 解析章节节点失败', [
  1329. 'chapter_id_list' => $chapterIdList,
  1330. 'error' => $e->getMessage()
  1331. ]);
  1332. // 出错时返回空数组
  1333. return [];
  1334. }
  1335. }
  1336. }