ExamTypeStrategy.php 84 KB

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