ExamTypeStrategy.php 66 KB

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