ExamTypeStrategy.php 82 KB

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