ExamTypeStrategy.php 67 KB

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