ExamTypeStrategy.php 61 KB

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