ExamTypeStrategy.php 64 KB

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