ExamAnswerAnalysisService.php 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Support\Facades\Log;
  5. /**
  6. * 考试答题分析服务(步骤级分析)
  7. * 基于卷子分析思考文档的思路实现
  8. *
  9. * 核心流程:
  10. * 1. 接收卷子ID和每道题的对错、简答题的分步骤对错
  11. * 2. 将原子信息映射到知识点/技能
  12. * 3. 计算知识点掌握度向量
  13. * 4. 生成详细分析报告
  14. * 5. 提供智能出卷推荐依据
  15. */
  16. class ExamAnswerAnalysisService
  17. {
  18. /**
  19. * 缓存知识点信息,减少重复查询
  20. *
  21. * @var array<string, object|null>
  22. */
  23. private array $kpInfoCache = [];
  24. public function __construct(
  25. private readonly MasteryCalculator $masteryCalculator,
  26. private readonly KnowledgeMasteryService $knowledgeMasteryService,
  27. private readonly LocalAIAnalysisService $aiAnalysisService,
  28. private readonly MistakeBookService $mistakeBookService
  29. ) {}
  30. /**
  31. * 分析考试答题数据
  32. *
  33. * @param array $examData 考试数据
  34. * @return array 分析结果
  35. */
  36. public function analyzeExamAnswers(array $examData): array
  37. {
  38. Log::info('开始分析考试答题', [
  39. 'paper_id' => $examData['paper_id'] ?? 'unknown',
  40. 'student_id' => $examData['student_id'] ?? 'unknown',
  41. 'question_count' => count($examData['questions'] ?? []),
  42. ]);
  43. $studentId = $examData['student_id'];
  44. $paperId = $examData['paper_id'] ?? '';
  45. $questions = $examData['questions'] ?? [];
  46. // 0. 自动计算分数并补充未提交的题目
  47. $questions = $this->autoCalculateScores($questions, $paperId);
  48. // 更新 examData 中的 questions(包含补充的题目)
  49. $examData['questions'] = $questions;
  50. // 【公司要求】1. 获取学案基准难度(取自学案的difficulty_category)
  51. $examBaseDifficulty = $this->getExamBaseDifficulty($examData['paper_id'] ?? '');
  52. // 2. 获取题目知识点映射(批量查询,避免N+1)
  53. $questionMappings = $this->getQuestionKnowledgeMappings($questions);
  54. // 3. 保存答题记录到数据库(复用已查询的知识点映射)
  55. $recordChangeState = $this->saveExamAnswerRecords($examData, $questionMappings);
  56. // 同步回写 paper_questions 判分结果,保证 PDF 与分析链路一致
  57. $this->syncPaperQuestionGrading($examData);
  58. // 同卷同答案重复提交:直接复用最近一次分析结果,避免掌握度被重复累计
  59. $forceRecalculate = boolval($examData['force_recalculate'] ?? false);
  60. if (
  61. !$forceRecalculate
  62. &&
  63. !($recordChangeState['steps_changed'] ?? false)
  64. && !($recordChangeState['questions_changed'] ?? false)
  65. ) {
  66. $existing = DB::connection('mysql')
  67. ->table('exam_analysis_results')
  68. ->where('student_id', $studentId)
  69. ->where('paper_id', $examData['paper_id'])
  70. ->orderByDesc('created_at')
  71. ->first();
  72. if ($existing && !empty($existing->analysis_data)) {
  73. $existingData = json_decode($existing->analysis_data, true) ?: [];
  74. $existingData['reused_existing_analysis'] = true;
  75. $existingData['reused_analysis_id'] = $existing->id;
  76. Log::info('同卷同答案重复提交,复用已有分析结果', [
  77. 'student_id' => $studentId,
  78. 'paper_id' => $examData['paper_id'],
  79. 'analysis_id' => $existing->id,
  80. ]);
  81. return $existingData;
  82. }
  83. }
  84. // 【公司要求】4. 计算每个知识点的加权掌握度(传入学案基准难度)
  85. // 核心算法:难度映射 → 权重计算 → 数值更新(newMastery = oldMastery + change)
  86. $knowledgeMasteryVector = $this->calculateKnowledgeMasteryVector($questions, $questionMappings, $examBaseDifficulty, $studentId);
  87. // 【公司要求】5. 更新学生掌握度(包含多级父节点掌握度计算)
  88. $updatedMastery = $this->updateStudentMastery($studentId, $knowledgeMasteryVector);
  89. // 5. 生成题目维度分析
  90. $questionAnalysis = $this->analyzeQuestions($questions, $questionMappings);
  91. // 6. 生成知识点维度分析
  92. $knowledgePointAnalysis = $this->analyzeKnowledgePoints($knowledgeMasteryVector, $questionMappings);
  93. // 7. 生成整体掌握度总结
  94. $overallSummary = $this->generateOverallSummary($updatedMastery);
  95. // 8. 生成智能出卷推荐依据
  96. $smartQuizRecommendation = $this->generateSmartQuizRecommendation($updatedMastery);
  97. // 9. 保存分析结果
  98. $analysisResult = [
  99. 'paper_id' => $examData['paper_id'],
  100. 'student_id' => $studentId,
  101. 'timestamp' => now()->toISOString(),
  102. 'question_analysis' => $questionAnalysis,
  103. 'knowledge_point_analysis' => $knowledgePointAnalysis,
  104. 'overall_summary' => $overallSummary,
  105. 'smart_quiz_recommendation' => $smartQuizRecommendation,
  106. 'mastery_vector' => $updatedMastery,
  107. ];
  108. // 【新增】创建掌握度快照,并返回 current_mastery(仅kp->mastery)
  109. $snapshotInfo = $this->createMasterySnapshot($studentId, $paperId, $analysisResult);
  110. $analysisResult['current_mastery'] = $snapshotInfo['current_mastery'] ?? [];
  111. $this->saveAnalysisResult($studentId, $examData['paper_id'], $analysisResult);
  112. Log::info('考试答题分析完成', [
  113. 'student_id' => $studentId,
  114. 'paper_id' => $examData['paper_id'],
  115. 'analyzed_knowledge_points' => count($knowledgeMasteryVector),
  116. ]);
  117. return $analysisResult;
  118. }
  119. /**
  120. * 【公司要求】获取学案基准难度(取自学案的difficulty_category)
  121. *
  122. * 公司要求:
  123. * 入参需要增加 {学案基准难度}(取自学案的 difficulty_category)
  124. *
  125. * @param string $paperId 试卷ID
  126. * @return int|null 学案基准难度(1-4级),失败返回null
  127. */
  128. private function getExamBaseDifficulty(string $paperId): ?int
  129. {
  130. if (empty($paperId)) {
  131. return null;
  132. }
  133. try {
  134. // 【公司要求】入参需要增加 {学案基准难度}(取自学案的 difficulty_category)
  135. // 从试卷表获取difficulty_category
  136. $paper = DB::table('papers')
  137. ->where('paper_id', $paperId)
  138. ->first();
  139. if (! $paper) {
  140. Log::warning('未找到试卷,尝试从缓存获取', ['paper_id' => $paperId]);
  141. return 2;
  142. }
  143. return $paper->difficulty_category ?? 2;
  144. } catch (\Exception $e) {
  145. Log::warning('获取学案基准难度失败,使用默认2级', [
  146. 'paper_id' => $paperId,
  147. 'error' => $e->getMessage(),
  148. ]);
  149. return 2; // 默认中等难度
  150. }
  151. }
  152. /**
  153. * 获取题目知识点映射
  154. * 【优化】优先使用批量查询,失败时降级到单条查询
  155. */
  156. private function getQuestionKnowledgeMappings(array $questions): array
  157. {
  158. $mappings = [];
  159. $failedQuestions = [];
  160. // 收集所有题目ID
  161. $questionIds = [];
  162. foreach ($questions as $question) {
  163. $questionId = $question['question_id'] ?? null;
  164. if ($questionId) {
  165. $questionIds[] = $questionId;
  166. }
  167. }
  168. // 【优化】尝试批量查询
  169. $batchResult = [];
  170. if (! empty($questionIds)) {
  171. $batchResult = $this->batchGetQuestionKnowledgePoints($questionIds);
  172. }
  173. // 【优化】对批量未命中的题目再做一次批量补偿,减少单条查询
  174. $missingQuestionIds = [];
  175. if (! empty($questionIds)) {
  176. foreach ($questionIds as $qid) {
  177. if (! isset($batchResult[$qid])) {
  178. $missingQuestionIds[] = $qid;
  179. }
  180. }
  181. }
  182. $fallbackBatchResult = [];
  183. if (! empty($missingQuestionIds)) {
  184. $fallbackBatchResult = $this->batchGetQuestionKnowledgePoints($missingQuestionIds);
  185. }
  186. // 遍历题目,优先使用批量结果,否则降级到单条查询
  187. foreach ($questions as $question) {
  188. $questionId = $question['question_id'] ?? null;
  189. if (! $questionId) {
  190. continue;
  191. }
  192. $kpMapping = [];
  193. // 优先使用批量查询结果
  194. if (isset($batchResult[$questionId])) {
  195. $kpMapping = $batchResult[$questionId];
  196. Log::debug('使用批量查询结果', [
  197. 'question_id' => $questionId,
  198. 'kp_count' => count($kpMapping),
  199. ]);
  200. } elseif (isset($fallbackBatchResult[$questionId])) {
  201. $kpMapping = $fallbackBatchResult[$questionId];
  202. Log::debug('使用补偿批量查询结果', [
  203. 'question_id' => $questionId,
  204. 'kp_count' => count($kpMapping),
  205. ]);
  206. } else {
  207. // 降级:使用单条查询(批量查询可能遗漏的题目)
  208. $dbKpMappings = $this->getQuestionKnowledgePointsFromDb($questionId);
  209. if (! empty($dbKpMappings)) {
  210. $kpMapping = $dbKpMappings;
  211. Log::debug('降级到单条查询', [
  212. 'question_id' => $questionId,
  213. 'kp_count' => count($dbKpMappings),
  214. ]);
  215. }
  216. }
  217. // 如果仍然没有知识点信息,跳过该题目
  218. if (empty($kpMapping)) {
  219. $failedQuestions[] = $questionId;
  220. Log::warning('跳过无法获取知识点的题目', [
  221. 'question_id' => $questionId,
  222. ]);
  223. continue;
  224. }
  225. $mappings[$questionId] = [
  226. 'question_id' => $questionId,
  227. 'kp_mapping' => $kpMapping,
  228. ];
  229. }
  230. if (! empty($failedQuestions)) {
  231. Log::warning('部分题目无法获取知识点信息', [
  232. 'failed_questions' => $failedQuestions,
  233. 'total_questions' => count($questions),
  234. 'mapped_questions' => count($mappings),
  235. ]);
  236. }
  237. Log::info('题目知识点映射构建完成', [
  238. 'total_questions' => count($questions),
  239. 'mapped_questions' => count($mappings),
  240. 'failed_questions' => count($failedQuestions),
  241. 'batch_hit_count' => count($batchResult),
  242. ]);
  243. return $mappings;
  244. }
  245. /**
  246. * 从数据库获取题目的知识点信息(支持多知识点)
  247. * 如果题目没有直接的知识点,通过目录ID匹配知识点
  248. */
  249. private function getQuestionKnowledgePointsFromDb(string $questionId): array
  250. {
  251. $allKpMappings = [];
  252. try {
  253. // 【第一步】从 questions 表直接获取知识点字段(可能有多个)
  254. $question = DB::connection('mysql')
  255. ->table('questions')
  256. ->where('id', $questionId)
  257. ->orWhere('question_code', $questionId)
  258. ->first();
  259. if ($question) {
  260. // 检查题目的直接知识点字段
  261. $directKpCodes = [];
  262. $kpCode1 = $question->kp_code;
  263. if ($kpCode1) {
  264. $directKpCodes[] = $kpCode1;
  265. }
  266. // 获取每个知识点的详细信息
  267. foreach ($directKpCodes as $kpCode) {
  268. $kpInfo = $this->getKnowledgePointInfo($kpCode);
  269. if ($kpInfo) {
  270. $allKpMappings[] = [
  271. 'kp_id' => $kpCode,
  272. 'kp_name' => $kpInfo->name,
  273. 'weight' => 1.0,
  274. ];
  275. } else {
  276. // 如果knowledge_points表中没有记录,仍然添加
  277. $allKpMappings[] = [
  278. 'kp_id' => $kpCode,
  279. 'kp_name' => $kpCode,
  280. 'weight' => 1.0,
  281. ];
  282. }
  283. }
  284. if (! empty($directKpCodes)) {
  285. Log::debug('从题目直接字段获取知识点', [
  286. 'question_id' => $questionId,
  287. 'kp_codes' => $directKpCodes,
  288. 'mapped_count' => count($allKpMappings),
  289. ]);
  290. }
  291. }
  292. // 【第二步】如果题目没有直接的知识点,通过目录ID匹配知识点
  293. if (empty($allKpMappings) && $question) {
  294. $catalogKpMappings = $this->findKpCodesByCatalog($question);
  295. if (! empty($catalogKpMappings)) {
  296. $allKpMappings = $catalogKpMappings;
  297. Log::debug('通过目录ID匹配到知识点', [
  298. 'question_id' => $questionId,
  299. 'matched_kp_codes' => array_column($catalogKpMappings, 'kp_id'),
  300. 'matched_count' => count($catalogKpMappings),
  301. ]);
  302. }
  303. }
  304. if (empty($allKpMappings)) {
  305. Log::warning('未找到题目的知识点信息', [
  306. 'question_id' => $questionId,
  307. ]);
  308. }
  309. } catch (\Exception $e) {
  310. Log::error('获取题目知识点信息失败', [
  311. 'question_id' => $questionId,
  312. 'error' => $e->getMessage(),
  313. ]);
  314. }
  315. return $allKpMappings;
  316. }
  317. /**
  318. * 通过题目的目录信息匹配知识点
  319. * 使用 textbook_catalog_nodes_id -> textbook_chapter_knowledge_relation 表查询
  320. */
  321. private function findKpCodesByCatalog(object $question): array
  322. {
  323. $kpMappings = [];
  324. try {
  325. // 获取题目的教材目录节点ID
  326. $catalogNodesId = $question->textbook_catalog_nodes_id;
  327. if (! $catalogNodesId) {
  328. Log::debug('题目没有关联的教材目录节点', [
  329. 'question_id' => $question->id,
  330. ]);
  331. return $kpMappings;
  332. }
  333. // 通过 catalog_chapter_id 查询关联的知识点
  334. $relations = DB::connection('mysql')
  335. ->table('textbook_chapter_knowledge_relation')
  336. ->where('catalog_chapter_id', $catalogNodesId)
  337. ->where('is_deleted', 0) // 只查询未删除的关联
  338. ->get();
  339. if ($relations->isNotEmpty()) {
  340. foreach ($relations as $relation) {
  341. $kpCode = $relation->kp_code;
  342. $kpInfo = $this->getKnowledgePointInfo($kpCode);
  343. $kpMappings[] = [
  344. 'kp_id' => $kpCode,
  345. 'kp_name' => $kpInfo->name ?? $kpCode,
  346. 'weight' => 1.0,
  347. ];
  348. }
  349. Log::debug('通过教材目录节点匹配到知识点', [
  350. 'question_id' => $question->id,
  351. 'catalog_nodes_id' => $catalogNodesId,
  352. 'matched_kp_count' => count($kpMappings),
  353. 'matched_kp_codes' => array_column($kpMappings, 'kp_id'),
  354. ]);
  355. } else {
  356. Log::debug('教材目录节点没有关联的知识点', [
  357. 'question_id' => $question->id,
  358. 'catalog_nodes_id' => $catalogNodesId,
  359. ]);
  360. }
  361. } catch (\Exception $e) {
  362. Log::error('通过目录匹配知识点失败', [
  363. 'question_id' => $question->id,
  364. 'error' => $e->getMessage(),
  365. ]);
  366. }
  367. return $kpMappings;
  368. }
  369. /**
  370. * 保留原有方法用于向后兼容,但标记为废弃
  371. */
  372. private function getQuestionKnowledgePointFromDb(string $questionId): ?array
  373. {
  374. $kpMappings = $this->getQuestionKnowledgePointsFromDb($questionId);
  375. return ! empty($kpMappings) ? $kpMappings[0] : null;
  376. }
  377. /**
  378. * 获取知识点信息(带进程内缓存)
  379. */
  380. private function getKnowledgePointInfo(string $kpCode): ?object
  381. {
  382. if (isset($this->kpInfoCache[$kpCode])) {
  383. return $this->kpInfoCache[$kpCode];
  384. }
  385. $kpInfo = DB::connection('mysql')
  386. ->table('knowledge_points')
  387. ->where('kp_code', $kpCode)
  388. ->select(['kp_code', 'name'])
  389. ->first();
  390. $this->kpInfoCache[$kpCode] = $kpInfo ?: null;
  391. return $kpInfo;
  392. }
  393. /**
  394. * 【优化】批量获取题目的知识点信息
  395. * 将 N+1 查询优化为 2-3 次批量查询
  396. *
  397. * @param array $questionIds 题目ID数组
  398. * @return array [questionId => [kpMappings...]] 映射
  399. */
  400. private function batchGetQuestionKnowledgePoints(array $questionIds): array
  401. {
  402. if (empty($questionIds)) {
  403. return [];
  404. }
  405. $result = [];
  406. $questionsNeedCatalogLookup = []; // 需要通过目录查找知识点的题目
  407. try {
  408. // 【第1步】批量查询 questions 表(1次查询)
  409. $questionsData = DB::connection('mysql')
  410. ->table('questions')
  411. ->whereIn('id', $questionIds)
  412. ->orWhereIn('question_code', $questionIds)
  413. ->get();
  414. // 建立 ID 到题目数据的映射
  415. $questionMap = [];
  416. foreach ($questionsData as $q) {
  417. $questionMap[$q->id] = $q;
  418. if ($q->question_code) {
  419. $questionMap[$q->question_code] = $q;
  420. }
  421. }
  422. // 【第2步】收集所有直接关联的 kp_code
  423. $allKpCodes = [];
  424. foreach ($questionsData as $q) {
  425. if (! empty($q->kp_code)) {
  426. $allKpCodes[] = $q->kp_code;
  427. }
  428. }
  429. // 【第3步】批量查询 knowledge_points 表(1次查询)
  430. $kpInfoMap = [];
  431. if (! empty($allKpCodes)) {
  432. $kpInfos = DB::connection('mysql')
  433. ->table('knowledge_points')
  434. ->whereIn('kp_code', array_unique($allKpCodes))
  435. ->get();
  436. foreach ($kpInfos as $kp) {
  437. $kpInfoMap[$kp->kp_code] = $kp;
  438. }
  439. }
  440. // 【第4步】收集需要通过目录查找的题目
  441. $catalogNodeIds = [];
  442. foreach ($questionsData as $q) {
  443. if (empty($q->kp_code) && ! empty($q->textbook_catalog_nodes_id)) {
  444. $catalogNodeIds[] = $q->textbook_catalog_nodes_id;
  445. $questionsNeedCatalogLookup[$q->id] = $q;
  446. }
  447. }
  448. // 【第5步】批量查询目录-知识点关系(1次查询)
  449. $catalogKpMap = [];
  450. if (! empty($catalogNodeIds)) {
  451. $catalogRelations = DB::connection('mysql')
  452. ->table('textbook_chapter_knowledge_relation')
  453. ->whereIn('catalog_chapter_id', array_unique($catalogNodeIds))
  454. ->where('is_deleted', 0)
  455. ->get();
  456. // 收集目录关联的 kp_code
  457. $catalogKpCodes = [];
  458. foreach ($catalogRelations as $rel) {
  459. $catalogKpCodes[] = $rel->kp_code;
  460. if (! isset($catalogKpMap[$rel->catalog_chapter_id])) {
  461. $catalogKpMap[$rel->catalog_chapter_id] = [];
  462. }
  463. $catalogKpMap[$rel->catalog_chapter_id][] = $rel->kp_code;
  464. }
  465. // 批量查询这些知识点的信息
  466. if (! empty($catalogKpCodes)) {
  467. $catalogKpInfos = DB::connection('mysql')
  468. ->table('knowledge_points')
  469. ->whereIn('kp_code', array_unique($catalogKpCodes))
  470. ->get();
  471. foreach ($catalogKpInfos as $kp) {
  472. $kpInfoMap[$kp->kp_code] = $kp;
  473. }
  474. }
  475. }
  476. // 【第6步】组装结果
  477. foreach ($questionIds as $questionId) {
  478. $qData = $questionMap[$questionId] ?? null;
  479. if (! $qData) {
  480. Log::debug('批量查询未找到题目', ['question_id' => $questionId]);
  481. continue;
  482. }
  483. $kpMappings = [];
  484. // 方式1:直接从 kp_code 字段获取
  485. if (! empty($qData->kp_code)) {
  486. $kpCode = $qData->kp_code;
  487. $kpInfo = $kpInfoMap[$kpCode] ?? null;
  488. $kpMappings[] = [
  489. 'kp_id' => $kpCode,
  490. 'kp_name' => $kpInfo->name ?? $kpCode,
  491. 'weight' => 1.0,
  492. ];
  493. }
  494. // 方式2:通过目录关系获取
  495. elseif (! empty($qData->textbook_catalog_nodes_id)) {
  496. $catalogId = $qData->textbook_catalog_nodes_id;
  497. $catalogKpCodes = $catalogKpMap[$catalogId] ?? [];
  498. foreach ($catalogKpCodes as $kpCode) {
  499. $kpInfo = $kpInfoMap[$kpCode] ?? null;
  500. $kpMappings[] = [
  501. 'kp_id' => $kpCode,
  502. 'kp_name' => $kpInfo->name ?? $kpCode,
  503. 'weight' => 1.0,
  504. ];
  505. }
  506. }
  507. if (! empty($kpMappings)) {
  508. $result[$questionId] = $kpMappings;
  509. }
  510. }
  511. Log::info('批量获取题目知识点完成', [
  512. 'input_count' => count($questionIds),
  513. 'output_count' => count($result),
  514. 'query_count' => '2-4次(优化后)',
  515. ]);
  516. } catch (\Exception $e) {
  517. Log::error('批量获取题目知识点失败,将降级到单条查询', [
  518. 'question_ids' => $questionIds,
  519. 'error' => $e->getMessage(),
  520. ]);
  521. // 降级:返回空,让调用方使用单条查询
  522. return [];
  523. }
  524. return $result;
  525. }
  526. /**
  527. * 从 QuestionBank API 获取题目信息
  528. */
  529. private function getQuestionFromQuestionBank(string $questionId): ?array
  530. {
  531. try {
  532. $baseUrl = config('services.question_bank_api.base_url', 'http://question-bank-api:5015');
  533. $response = Http::timeout(10)->get($baseUrl.'/questions/'.$questionId);
  534. if ($response->successful()) {
  535. $data = $response->json();
  536. return $data['data'] ?? null;
  537. }
  538. return null;
  539. } catch (\Exception $e) {
  540. Log::warning('从QuestionBank获取题目信息失败', [
  541. 'question_id' => $questionId,
  542. 'error' => $e->getMessage(),
  543. ]);
  544. return null;
  545. }
  546. }
  547. /**
  548. * 批量获取题目难度
  549. *
  550. * @param array $questionIds 题目ID数组
  551. * @return array [questionId => difficulty] 映射
  552. */
  553. private function batchGetQuestionDifficulties(array $questionIds): array
  554. {
  555. if (empty($questionIds)) {
  556. return [];
  557. }
  558. $difficulties = [];
  559. try {
  560. $questions = DB::connection('mysql')
  561. ->table('questions')
  562. ->whereIn('id', $questionIds)
  563. ->orWhereIn('question_code', $questionIds)
  564. ->select(['id', 'question_code', 'difficulty'])
  565. ->get();
  566. foreach ($questions as $question) {
  567. $difficulty = $question->difficulty !== null ? floatval($question->difficulty) : 0.6;
  568. // 同时用 id 和 question_code 作为键,确保能匹配到
  569. $difficulties[$question->id] = $difficulty;
  570. if ($question->question_code) {
  571. $difficulties[$question->question_code] = $difficulty;
  572. }
  573. }
  574. } catch (\Exception $e) {
  575. Log::warning('批量获取题目难度失败', [
  576. 'question_ids' => $questionIds,
  577. 'error' => $e->getMessage(),
  578. ]);
  579. }
  580. return $difficulties;
  581. }
  582. /**
  583. * 【公司要求】计算知识点掌握度向量
  584. *
  585. * 公司要求的核心算法:
  586. * 1. 难度映射:将题目中0.0-1.0的浮点数难度映射为 1-4 等级
  587. * 2. 权重计算:
  588. * - 越级(Question > {学案基准难度}):对 +0.15 / 错 -0.05
  589. * - 适应(Question = {学案基准难度}):对 +0.10 / 错 -0.10
  590. * - 降级(Question < {学案基准难度}):对 +0.05 / 错 -0.15
  591. * 3. 数值更新:newMastery = oldMastery + change,并做 0.0 ~ 1.0 的边界限制
  592. *
  593. * 核心算法说明:
  594. * 1. 从考试答题中提取每个知识点的答题记录
  595. * 2. 调用MasteryCalculator计算掌握度(包含:难度映射、权重计算、数值更新)
  596. * 3. 返回包含掌握度、置信度、趋势等完整信息的向量
  597. *
  598. * @param array $questions 题目列表
  599. * @param array $questionMappings 题目知识点映射
  600. * @param int|null $examBaseDifficulty 学案基准难度(1-4级)
  601. * @param string|null $studentId 学生ID
  602. * @return array 知识点掌握度向量
  603. */
  604. private function calculateKnowledgeMasteryVector(array $questions, array $questionMappings, ?int $examBaseDifficulty = null, ?string $studentId = null): array
  605. {
  606. // 按知识点聚合答题记录
  607. $knowledgeAttempts = [];
  608. // 批量获取所有题目的难度(减少数据库查询次数)
  609. $questionIds = array_filter(array_map(fn ($q) => $q['question_id'] ?? $q['question_bank_id'] ?? null, $questions));
  610. $questionDifficulties = $this->batchGetQuestionDifficulties($questionIds);
  611. foreach ($questions as $question) {
  612. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  613. if (empty($questionId)) {
  614. Log::warning('calculateKnowledgeMasteryVector: 题目缺少ID', ['question' => $question]);
  615. continue;
  616. }
  617. $score = floatval($question['score_obtained'] ?? 0);
  618. $maxScore = floatval($question['score'] ?? $score);
  619. // is_correct 是数组,如 [0,1,1],表示每个步骤的正误
  620. $isCorrectArray = $question['is_correct'] ?? [];
  621. if (! is_array($isCorrectArray)) {
  622. $isCorrectArray = [$isCorrectArray ? 1 : 0];
  623. }
  624. $mapping = $questionMappings[$questionId] ?? null;
  625. if (! $mapping || ! isset($mapping['kp_mapping'])) {
  626. Log::debug('calculateKnowledgeMasteryVector: 题目无知识点映射', ['question_id' => $questionId]);
  627. continue;
  628. }
  629. // 从批量查询结果获取题目难度
  630. $questionDifficulty = $questionDifficulties[$questionId] ?? 0.6;
  631. $stepCount = count($isCorrectArray);
  632. $scorePerStep = $maxScore / max($stepCount, 1);
  633. // 根据 is_correct 数组生成步骤级答题记录
  634. foreach ($isCorrectArray as $stepIndex => $isCorrect) {
  635. $isCorrectBool = (int) $isCorrect === 1;
  636. // 为该题目关联的每个知识点创建答题记录
  637. foreach ($mapping['kp_mapping'] as $kpMapping) {
  638. $kpId = $kpMapping['kp_id'];
  639. if (! isset($knowledgeAttempts[$kpId])) {
  640. $knowledgeAttempts[$kpId] = [
  641. 'attempts' => [],
  642. 'step_details' => [],
  643. ];
  644. }
  645. // 构建答题记录(用于MasteryCalculator)
  646. $attemptRecord = [
  647. 'question_id' => $questionId,
  648. 'is_correct' => $isCorrectBool,
  649. 'step_index' => $stepIndex,
  650. 'question_difficulty' => $questionDifficulty,
  651. 'created_at' => now()->toISOString(),
  652. ];
  653. $knowledgeAttempts[$kpId]['attempts'][] = $attemptRecord;
  654. $knowledgeAttempts[$kpId]['step_details'][] = [
  655. 'question_id' => $questionId,
  656. 'step_index' => $stepIndex,
  657. 'score' => $isCorrectBool ? $scorePerStep : 0,
  658. 'max_score' => $scorePerStep,
  659. 'is_correct' => $isCorrectBool,
  660. ];
  661. }
  662. }
  663. }
  664. // 【公司要求】【核心】使用MasteryCalculator计算每个知识点的掌握度
  665. $masteryVector = [];
  666. foreach ($knowledgeAttempts as $kpId => $data) {
  667. $attempts = $data['attempts'];
  668. // 如果没有学案基准难度,使用默认值2(提分)
  669. $baseDifficulty = $examBaseDifficulty ?? 2;
  670. // 【公司要求】调用MasteryCalculator的核心算法(传入学案基准难度)
  671. // 该算法包含:难度映射、权重计算、数值更新(newMastery = oldMastery + change)
  672. $masteryResult = $this->masteryCalculator->calculateMasteryLevel(
  673. $studentId ?? '', // 传递学生ID,用于保存掌握度到数据库
  674. $kpId,
  675. $attempts,
  676. $baseDifficulty
  677. );
  678. // 【公司要求】只保留核心掌握度数据
  679. $masteryVector[$kpId] = [
  680. 'kp_id' => $kpId,
  681. 'mastery' => $masteryResult['mastery'],
  682. 'previous_mastery' => $masteryResult['old_mastery'] ?? null,
  683. 'change' => $masteryResult['change'] ?? null,
  684. 'total_attempts' => $masteryResult['total_attempts'],
  685. 'correct_attempts' => $masteryResult['correct_attempts'],
  686. 'accuracy_rate' => $masteryResult['accuracy_rate'],
  687. 'step_details' => $data['step_details'],
  688. // 计算细节(用于调试和分析)
  689. 'calculation_details' => $masteryResult['details'] ?? [],
  690. ];
  691. }
  692. Log::info('知识点掌握度向量计算完成', [
  693. 'knowledge_points_count' => count($masteryVector),
  694. 'sample' => array_slice($masteryVector, 0, 3, true),
  695. ]);
  696. return $masteryVector;
  697. }
  698. /**
  699. * 更新学生掌握度(优化版:批量查询+批量upsert)
  700. */
  701. private function updateStudentMastery(string $studentId, array $knowledgeMasteryVector): array
  702. {
  703. if (empty($knowledgeMasteryVector)) {
  704. return [];
  705. }
  706. $updatedMastery = [];
  707. $kpIds = array_keys($knowledgeMasteryVector);
  708. // 子节点掌握度已在 MasteryCalculator 内部写库,这里只生成返回数据,避免二次写入与重复统计
  709. foreach ($knowledgeMasteryVector as $kpId => $data) {
  710. $previousMastery = $data['previous_mastery'] ?? 0.0;
  711. $updatedMastery[$kpId] = [
  712. 'kp_id' => $kpId,
  713. 'current_mastery' => $data['mastery'],
  714. 'previous_mastery' => $previousMastery,
  715. 'change' => $data['mastery'] - $previousMastery,
  716. 'weight' => 1,
  717. 'is_parent' => false,
  718. ];
  719. }
  720. // 【修复】计算并更新父节点掌握度,同时添加到返回数组中
  721. $parentMasteryData = $this->updateParentMasteryLevels($studentId, $kpIds);
  722. // 合并父节点数据到返回数组
  723. $updatedMastery = array_merge($updatedMastery, $parentMasteryData);
  724. return $updatedMastery;
  725. }
  726. /**
  727. * 更新父节点掌握度(优化版:批量查询+批量upsert)
  728. * 父节点掌握度 = 所有子节点掌握度的算术平均数,支持多级递归
  729. */
  730. private function updateParentMasteryLevels(string $studentId, array $childKpCodes, int $maxDepth = 2): array
  731. {
  732. $allParentMasteryData = [];
  733. $currentLevelChildCodes = $childKpCodes;
  734. $processedNodes = new \ArrayObject;
  735. $now = now();
  736. try {
  737. for ($level = 0; $level < $maxDepth; $level++) {
  738. if (empty($currentLevelChildCodes)) {
  739. break;
  740. }
  741. // 获取当前层子节点的直接父节点
  742. $parentKpCodes = DB::connection('mysql')
  743. ->table('knowledge_points')
  744. ->whereIn('kp_code', $currentLevelChildCodes)
  745. ->whereNotNull('parent_kp_code')
  746. ->distinct()
  747. ->pluck('parent_kp_code')
  748. ->toArray();
  749. if (empty($parentKpCodes)) {
  750. break;
  751. }
  752. // 过滤已处理的节点
  753. $parentKpCodesToProcess = [];
  754. foreach ($parentKpCodes as $code) {
  755. if (! isset($processedNodes[$code])) {
  756. $processedNodes[$code] = true;
  757. $parentKpCodesToProcess[] = $code;
  758. }
  759. }
  760. if (empty($parentKpCodesToProcess)) {
  761. $currentLevelChildCodes = $parentKpCodes;
  762. continue;
  763. }
  764. // 批量获取父节点的直接子节点
  765. $childRelations = DB::connection('mysql')
  766. ->table('knowledge_points')
  767. ->whereIn('parent_kp_code', $parentKpCodesToProcess)
  768. ->get(['kp_code', 'parent_kp_code']);
  769. $childrenByParent = [];
  770. $allChildCodes = [];
  771. foreach ($childRelations as $relation) {
  772. $childrenByParent[$relation->parent_kp_code][] = $relation->kp_code;
  773. $allChildCodes[$relation->kp_code] = true;
  774. }
  775. // 批量获取子节点掌握度
  776. $childMasteryMap = [];
  777. if (! empty($allChildCodes)) {
  778. $childMasteryMap = DB::connection('mysql')
  779. ->table('student_knowledge_mastery')
  780. ->where('student_id', $studentId)
  781. ->whereIn('kp_code', array_keys($allChildCodes))
  782. ->pluck('mastery_level', 'kp_code')
  783. ->toArray();
  784. }
  785. // 批量查询父节点历史掌握度
  786. $historyRecords = DB::connection('mysql')
  787. ->table('student_knowledge_mastery')
  788. ->where('student_id', $studentId)
  789. ->whereIn('kp_code', $parentKpCodesToProcess)
  790. ->get()
  791. ->keyBy('kp_code');
  792. // 计算每个父节点的掌握度并收集upsert数据
  793. $upsertData = [];
  794. $currentLevelParentData = [];
  795. foreach ($parentKpCodesToProcess as $parentKpCode) {
  796. $children = $childrenByParent[$parentKpCode] ?? [];
  797. $sum = 0.0;
  798. $count = 0;
  799. foreach ($children as $childCode) {
  800. if (isset($childMasteryMap[$childCode])) {
  801. $sum += (float) $childMasteryMap[$childCode];
  802. $count++;
  803. }
  804. }
  805. $parentMastery = $count > 0 ? round($sum / $count, 4) : 0.0;
  806. $historyMastery = $historyRecords->get($parentKpCode);
  807. $previousMastery = $historyMastery->mastery_level ?? 0.0;
  808. $upsertData[] = [
  809. 'student_id' => $studentId,
  810. 'kp_code' => $parentKpCode,
  811. 'mastery_level' => $parentMastery,
  812. 'confidence_level' => 0.0,
  813. 'total_attempts' => 1,
  814. 'correct_attempts' => 0,
  815. 'mastery_trend' => 'stable',
  816. 'last_mastery_update' => $now,
  817. 'updated_at' => $now,
  818. ];
  819. $currentLevelParentData[$parentKpCode] = [
  820. 'kp_id' => $parentKpCode,
  821. 'current_mastery' => $parentMastery,
  822. 'previous_mastery' => $previousMastery,
  823. 'change' => $parentMastery - $previousMastery,
  824. 'weight' => 1,
  825. 'is_parent' => true,
  826. 'level' => $level + 1,
  827. ];
  828. }
  829. // 【优化】批量upsert(1次查询代替N次updateOrInsert)
  830. if (! empty($upsertData)) {
  831. DB::connection('mysql')
  832. ->table('student_knowledge_mastery')
  833. ->upsert(
  834. $upsertData,
  835. ['student_id', 'kp_code'],
  836. ['mastery_level', 'confidence_level', 'total_attempts', 'correct_attempts', 'mastery_trend', 'last_mastery_update', 'updated_at']
  837. );
  838. }
  839. $allParentMasteryData = array_merge($allParentMasteryData, $currentLevelParentData);
  840. $currentLevelChildCodes = $parentKpCodes;
  841. }
  842. if (! empty($allParentMasteryData)) {
  843. Log::info('多级父节点掌握度计算完成', [
  844. 'student_id' => $studentId,
  845. 'child_count' => count($childKpCodes),
  846. 'total_parent_count' => count($allParentMasteryData),
  847. ]);
  848. }
  849. } catch (\Exception $e) {
  850. Log::error('计算多级父节点掌握度失败', [
  851. 'student_id' => $studentId,
  852. 'error' => $e->getMessage(),
  853. ]);
  854. }
  855. return $allParentMasteryData;
  856. }
  857. /**
  858. * 生成题目维度分析(包含AI分析和解题思路)
  859. */
  860. private function analyzeQuestions(array $questions, array $questionMappings): array
  861. {
  862. $analysis = [];
  863. foreach ($questions as $question) {
  864. $questionId = $question['question_id'];
  865. $score = floatval($question['score_obtained'] ?? 0);
  866. $maxScore = floatval($question['score'] ?? $score);
  867. $steps = $question['steps'] ?? [];
  868. $isCorrect = $question['is_correct'] ?? ($score >= $maxScore);
  869. $mapping = $questionMappings[$questionId] ?? ['kp_mapping' => []];
  870. if (empty($mapping['kp_mapping'])) {
  871. Log::warning('ExamAnswerAnalysisService: 题目无知识点映射', ['question_id' => $questionId]);
  872. continue;
  873. }
  874. $kpCode = $mapping['kp_mapping'][0]['kp_id'];
  875. // 步骤分析
  876. $stepAnalysis = [];
  877. if (! empty($steps)) {
  878. foreach ($steps as $step) {
  879. $kpId = $step['kp_id'];
  880. if (empty($kpId)) {
  881. Log::warning('ExamAnswerAnalysisService: 步骤缺少知识点ID', [
  882. 'question_id' => $questionId,
  883. 'step_index' => $step['step_index'] ?? 'unknown',
  884. ]);
  885. continue;
  886. }
  887. $stepAnalysis[] = [
  888. 'step_index' => $step['step_index'],
  889. 'is_correct' => $step['is_correct'],
  890. 'kp_id' => $kpId,
  891. 'description' => $step['description'] ?? '',
  892. ];
  893. }
  894. }
  895. // 知识点关联
  896. $knowledgePoints = array_map(function ($kp) {
  897. return [
  898. 'kp_id' => $kp['kp_id'],
  899. 'kp_name' => $kp['kp_name'] ?? $kp['kp_id'],
  900. 'weight' => $kp['weight'] ?? 1.0,
  901. ];
  902. }, $mapping['kp_mapping']);
  903. // 【集成】调用AI分析服务,获取解题思路和错误分析
  904. $aiAnalysis = $this->getQuestionAIAnalysis($question, $mapping);
  905. $analysis[] = [
  906. 'question_id' => $questionId,
  907. 'score_obtained' => $score,
  908. 'max_score' => $maxScore,
  909. 'accuracy_rate' => $maxScore > 0 ? $score / $maxScore : 0,
  910. 'is_correct' => $isCorrect,
  911. 'step_analysis' => $stepAnalysis,
  912. 'knowledge_points' => $knowledgePoints,
  913. 'performance_summary' => $this->generateQuestionPerformanceSummary($question, $stepAnalysis),
  914. // 【新增】解题思路和错误分析
  915. 'solution_process' => $aiAnalysis['solution_process'] ?? '',
  916. 'error_analysis' => $aiAnalysis['error_analysis'] ?? '',
  917. 'mistake_type' => $aiAnalysis['mistake_type'] ?? '',
  918. 'suggestions' => $aiAnalysis['suggestions'] ?? '',
  919. 'next_steps' => $aiAnalysis['next_steps'] ?? [],
  920. ];
  921. }
  922. return $analysis;
  923. }
  924. /**
  925. * 获取题目的AI分析(解题思路、错误分析)
  926. */
  927. private function getQuestionAIAnalysis(array $question, array $mapping): array
  928. {
  929. $isCorrect = $question['is_correct'] ?? false;
  930. $score = floatval($question['score_obtained'] ?? 0);
  931. $maxScore = floatval($question['score'] ?? 10);
  932. $kpCode = $mapping['kp_mapping'][0]['kp_id'] ?? null;
  933. if (empty($kpCode)) {
  934. Log::warning('ExamAnswerAnalysisService: getQuestionAIAnalysis缺少知识点ID', [
  935. 'question_id' => $question['question_id'] ?? 'unknown',
  936. 'mapping' => $mapping,
  937. ]);
  938. $kpCode = 'UNKNOWN_KP';
  939. }
  940. // 调用LocalAIAnalysisService进行分析
  941. try {
  942. $analysisResult = $this->aiAnalysisService->analyzeAnswer([
  943. 'question_id' => $question['question_id'],
  944. 'question_text' => $question['question_text'] ?? '',
  945. 'student_answer' => $question['student_answer'] ?? '',
  946. 'correct_answer' => $question['correct_answer'] ?? '',
  947. 'score' => $score,
  948. 'max_score' => $maxScore,
  949. 'kp_code' => $kpCode,
  950. ]);
  951. $data = $analysisResult['data'] ?? [];
  952. // 根据正确性生成不同的解题思路
  953. if ($isCorrect) {
  954. return [
  955. 'solution_process' => $data['correct_solution'] ?? '该题作答正确,解题思路清晰',
  956. 'error_analysis' => '',
  957. 'mistake_type' => '',
  958. 'suggestions' => $data['suggestions'] ?? '继续保持良好的解题习惯',
  959. 'next_steps' => $data['next_steps'] ?? ['尝试更高难度的同类题目'],
  960. ];
  961. }
  962. // 错误题目:返回详细分析
  963. return [
  964. 'solution_process' => $data['correct_solution'] ?? '请参考标准解题步骤',
  965. 'error_analysis' => $data['reason'] ?? '解题过程中存在错误',
  966. 'mistake_type' => $data['mistake_type'] ?? '计算或理解错误',
  967. 'suggestions' => $data['suggestions'] ?? '建议针对薄弱知识点进行专项练习',
  968. 'next_steps' => $data['next_steps'] ?? ['复习相关知识点', '做同类型练习题'],
  969. ];
  970. } catch (\Exception $e) {
  971. Log::warning('AI分析失败,使用默认分析', [
  972. 'question_id' => $question['question_id'],
  973. 'error' => $e->getMessage(),
  974. ]);
  975. // 回退到基础分析
  976. return $this->getFallbackAnalysis($question, $isCorrect);
  977. }
  978. }
  979. /**
  980. * 回退分析(当AI分析失败时)
  981. */
  982. private function getFallbackAnalysis(array $question, bool $isCorrect): array
  983. {
  984. if ($isCorrect) {
  985. return [
  986. 'solution_process' => '该题作答正确',
  987. 'error_analysis' => '',
  988. 'mistake_type' => '',
  989. 'suggestions' => '继续保持',
  990. 'next_steps' => ['尝试更高难度的题目'],
  991. ];
  992. }
  993. $scoreRatio = floatval($question['score_obtained'] ?? 0) / max(floatval($question['score'] ?? 1), 1);
  994. return [
  995. 'solution_process' => '请参考标准答案和解题步骤',
  996. 'error_analysis' => $scoreRatio < 0.3 ? '知识点理解存在偏差' : '解题过程中出现错误',
  997. 'mistake_type' => $scoreRatio < 0.3 ? '概念错误' : '计算/步骤错误',
  998. 'suggestions' => '建议复习相关知识点,加强练习',
  999. 'next_steps' => ['复习基础概念', '做同类型练习题', '请教老师或同学'],
  1000. ];
  1001. }
  1002. /**
  1003. * 生成知识点维度分析
  1004. */
  1005. private function analyzeKnowledgePoints(array $knowledgeMasteryVector, array $questionMappings): array
  1006. {
  1007. $analysis = [];
  1008. foreach ($knowledgeMasteryVector as $kpId => $data) {
  1009. // 【公司要求】移除置信度,只保留核心掌握度分析
  1010. $analysis[] = [
  1011. 'kp_id' => $kpId,
  1012. 'mastery_level' => $data['mastery'],
  1013. 'performance_in_exam' => $this->evaluatePerformanceLevel($data['mastery']),
  1014. 'evidence_count' => count($data['step_details']),
  1015. 'step_evidence' => $data['step_details'],
  1016. 'recommendation' => $this->generateKnowledgePointRecommendation($data),
  1017. ];
  1018. }
  1019. return $analysis;
  1020. }
  1021. /**
  1022. * 生成整体掌握度总结
  1023. */
  1024. private function generateOverallSummary(array $updatedMastery): array
  1025. {
  1026. $knowledgePoints = array_values($updatedMastery);
  1027. if (empty($knowledgePoints)) {
  1028. return [
  1029. 'total_knowledge_points' => 0,
  1030. 'average_mastery' => 0,
  1031. 'mastery_distribution' => [
  1032. 'mastered' => 0,
  1033. 'good' => 0,
  1034. 'weak' => 0,
  1035. ],
  1036. 'top_strengths' => [],
  1037. 'top_weaknesses' => [],
  1038. ];
  1039. }
  1040. // 计算平均掌握度(只计算子节点,不包括父节点)
  1041. $childNodes = array_filter($knowledgePoints, fn ($kp) => ! ($kp['is_parent'] ?? false));
  1042. $totalChildNodes = count($childNodes);
  1043. if ($totalChildNodes === 0) {
  1044. // 如果没有子节点,只计算所有节点
  1045. $averageMastery = array_sum(array_column($knowledgePoints, 'current_mastery')) / count($knowledgePoints);
  1046. } else {
  1047. // 计算所有节点的平均掌握度(包括父节点)
  1048. $allMastery = array_column($knowledgePoints, 'current_mastery');
  1049. $averageMastery = array_sum($allMastery) / count($allMastery);
  1050. }
  1051. // 掌握度分布(只统计子节点)
  1052. $mastered = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] >= 0.85);
  1053. $good = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] >= 0.70 && $kp['current_mastery'] < 0.85);
  1054. $weak = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] < 0.70);
  1055. // 排序找出优势和薄弱点(只包括子节点)
  1056. usort($childNodes, fn ($a, $b) => $b['current_mastery'] <=> $a['current_mastery']);
  1057. $topStrengths = array_slice($childNodes, 0, 3);
  1058. $topWeaknesses = array_slice(array_reverse($childNodes), 0, 3);
  1059. // 统计父子节点数量
  1060. $childCount = count(array_filter($knowledgePoints, fn ($kp) => ! ($kp['is_parent'] ?? false)));
  1061. $parentCount = count(array_filter($knowledgePoints, fn ($kp) => $kp['is_parent'] ?? false));
  1062. return [
  1063. 'total_knowledge_points' => $totalChildNodes, // 只统计子节点数量
  1064. 'child_nodes_count' => $childCount,
  1065. 'parent_nodes_count' => $parentCount,
  1066. 'average_mastery' => round($averageMastery, 4),
  1067. 'mastery_distribution' => [
  1068. 'mastered' => count($mastered),
  1069. 'good' => count($good),
  1070. 'weak' => count($weak),
  1071. ],
  1072. 'top_strengths' => $topStrengths,
  1073. 'top_weaknesses' => $topWeaknesses,
  1074. 'overall_performance' => $this->evaluateOverallPerformance($averageMastery),
  1075. ];
  1076. }
  1077. /**
  1078. * 生成智能出卷推荐依据
  1079. * 基于文档中的推荐优先级算法
  1080. */
  1081. private function generateSmartQuizRecommendation(array $updatedMastery): array
  1082. {
  1083. $recommendations = [];
  1084. // 只对子节点生成推荐,忽略父节点
  1085. foreach ($updatedMastery as $kpId => $data) {
  1086. // 跳过父节点
  1087. if ($data['is_parent'] ?? false) {
  1088. continue;
  1089. }
  1090. $mastery = $data['current_mastery'];
  1091. // 【公司要求】移除置信度,只使用掌握度计算推荐
  1092. $weight = $data['weight'];
  1093. // 推荐优先级 = (1 - 掌握度) * 重要性 * 覆盖需求
  1094. // 重要性可以根据知识点在中考/阶段考试中的权重,这里简化为1.0
  1095. $importance = 1.0;
  1096. // 覆盖需求:最近没考过或考得少,值大
  1097. $coverageNeed = max(1.0, 1.5 - ($weight / 10));
  1098. $priority = (1 - $mastery) * $importance * $coverageNeed;
  1099. $recommendations[] = [
  1100. 'kp_id' => $kpId,
  1101. 'current_mastery' => $mastery,
  1102. 'priority' => $priority,
  1103. 'recommended_questions' => $this->calculateRecommendedQuestions($mastery),
  1104. 'focus_type' => $this->determineFocusType($mastery),
  1105. ];
  1106. }
  1107. // 按优先级排序
  1108. usort($recommendations, fn ($a, $b) => $b['priority'] <=> $a['priority']);
  1109. // 控制难度节奏:40%巩固型 + 40%修补型 + 20%挑战型
  1110. $totalRecommendations = count($recommendations);
  1111. $consolidation = array_slice($recommendations, 0, intval($totalRecommendations * 0.4));
  1112. $remediation = array_slice($recommendations, intval($totalRecommendations * 0.4), intval($totalRecommendations * 0.4));
  1113. $challenge = array_slice($recommendations, intval($totalRecommendations * 0.8));
  1114. return [
  1115. 'priority_list' => $recommendations,
  1116. 'quiz_structure' => [
  1117. 'consolidation_type' => $consolidation,
  1118. 'remediation_type' => $remediation,
  1119. 'challenge_type' => $challenge,
  1120. ],
  1121. 'total_recommended_questions' => array_sum(array_column($recommendations, 'recommended_questions')),
  1122. ];
  1123. }
  1124. /**
  1125. * 保存考试答题记录
  1126. *
  1127. * 入参格式示例:
  1128. * {
  1129. * "question_bank_id": "12979",
  1130. * "student_answer": "C",
  1131. * "is_correct": [0], // 数组长度决定步骤数,0=错误,1=正确
  1132. * "teacher_comment": null
  1133. * }
  1134. *
  1135. * is_correct 数组说明:
  1136. * - 单选题:[1] 或 [0],长度为1
  1137. * - 填空题:[1, 0, 1],每个空一个元素
  1138. * - 简答题:[1, 1, 0, 1],每个得分步骤一个元素
  1139. */
  1140. /**
  1141. * 保存错题记录
  1142. *
  1143. * @param string $studentId 学生ID
  1144. * @param string $questionId 题目ID
  1145. * @param string $examId 考试ID
  1146. * @param array $question 题目数据
  1147. * @param array|null $kpMapping 知识点映射(数组格式:[kp_id1, kp_id2] 或 null)
  1148. */
  1149. private function saveMistakeRecord(string $studentId, string $questionId, string $examId, array $question, ?array $kpMapping): void
  1150. {
  1151. try {
  1152. // 如果 $kpMapping 是数组,说明是多个 kp_id
  1153. // 如果是关联数组,说明是单个 kpMapping(兼容旧调用)
  1154. $kpIds = null;
  1155. if (is_array($kpMapping)) {
  1156. // 检查是数组的数组(多个kp_id)还是关联数组(单个kpMapping)
  1157. if (isset($kpMapping[0])) {
  1158. // 数组的数组:[[kp_id: '...'], [kp_id: '...']]
  1159. $kpIds = array_column($kpMapping, 'kp_id');
  1160. } else {
  1161. // 关联数组:[kp_id: '...']
  1162. $kpIds = [$kpMapping['kp_id']];
  1163. }
  1164. }
  1165. $payload = [
  1166. 'student_id' => $studentId,
  1167. 'question_id' => $questionId,
  1168. 'paper_id' => $examId,
  1169. 'my_answer' => $question['student_answer'] ?? null,
  1170. 'correct_answer' => null, // 可以从题目表获取
  1171. 'question_text' => null, // 可以从题目表获取
  1172. 'knowledge_point' => null, // 不保存name,只保存kp_ids
  1173. 'kp_ids' => $kpIds, // 保存为数组格式
  1174. 'source' => $examId, // 来源标记使用卷子ID
  1175. 'happened_at' => now(),
  1176. ];
  1177. $result = $this->mistakeBookService->createMistake($payload);
  1178. if (($result['duplicate'] ?? false) === false) {
  1179. Log::debug('错题记录保存成功', [
  1180. 'student_id' => $studentId,
  1181. 'question_id' => $questionId,
  1182. 'mistake_id' => $result['mistake_id'] ?? null,
  1183. ]);
  1184. }
  1185. } catch (\Exception $e) {
  1186. Log::warning('错题记录保存失败(不中断主流程)', [
  1187. 'student_id' => $studentId,
  1188. 'question_id' => $questionId,
  1189. 'exam_id' => $examId,
  1190. 'error' => $e->getMessage(),
  1191. ]);
  1192. }
  1193. }
  1194. /**
  1195. * 保存答题记录(优化版:批量INSERT)
  1196. *
  1197. * @param array $examData 考试数据
  1198. * @param array $questionMappings 已批量查询的知识点映射,避免N+1
  1199. */
  1200. private function saveExamAnswerRecords(array $examData, array $questionMappings = []): array
  1201. {
  1202. // 【修复】确保类型正确,避免 SQL 类型转换问题
  1203. $studentId = (string) $examData['student_id'];
  1204. $examId = (string) $examData['paper_id'];
  1205. $now = now();
  1206. // 【优化】收集所有要插入的记录,最后批量INSERT
  1207. $stepsToInsert = [];
  1208. $questionsToInsert = [];
  1209. $mistakesToSave = []; // 收集错题记录
  1210. foreach ($examData['questions'] as $question) {
  1211. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1212. if (empty($questionId)) {
  1213. continue;
  1214. }
  1215. // 【优化】使用传入的映射,不再查询数据库
  1216. $kpMappings = $questionMappings[$questionId]['kp_mapping'] ?? [];
  1217. $isCorrectArray = $question['is_correct'] ?? [];
  1218. if (! is_array($isCorrectArray)) {
  1219. $isCorrectArray = [$isCorrectArray ? 1 : 0];
  1220. }
  1221. $stepCount = count($isCorrectArray);
  1222. if ($stepCount > 1 || ! empty($kpMappings)) {
  1223. // 多步骤题目:收集步骤记录
  1224. $scorePerStep = ($question['score'] ?? 0) / max($stepCount, 1);
  1225. $hasMistake = false;
  1226. $allErrorKpCodes = [];
  1227. foreach ($isCorrectArray as $stepIndex => $isCorrect) {
  1228. $isCorrectBool = (int) $isCorrect === 1;
  1229. if (! empty($kpMappings)) {
  1230. foreach ($kpMappings as $kpMapping) {
  1231. $stepsToInsert[] = [
  1232. 'student_id' => $studentId,
  1233. 'exam_id' => $examId,
  1234. 'question_id' => $questionId,
  1235. 'step_index' => $stepIndex,
  1236. 'kp_id' => $kpMapping['kp_id'],
  1237. 'is_correct' => $isCorrectBool ? 1 : 0,
  1238. 'step_score' => $isCorrectBool ? $scorePerStep : 0,
  1239. 'created_at' => $now,
  1240. 'updated_at' => $now,
  1241. ];
  1242. if (! $isCorrectBool) {
  1243. $hasMistake = true;
  1244. $allErrorKpCodes[] = $kpMapping['kp_id'];
  1245. }
  1246. }
  1247. } else {
  1248. $stepsToInsert[] = [
  1249. 'student_id' => $studentId,
  1250. 'exam_id' => $examId,
  1251. 'question_id' => $questionId,
  1252. 'step_index' => $stepIndex,
  1253. 'kp_id' => null,
  1254. 'is_correct' => $isCorrectBool ? 1 : 0,
  1255. 'step_score' => $isCorrectBool ? $scorePerStep : 0,
  1256. 'created_at' => $now,
  1257. 'updated_at' => $now,
  1258. ];
  1259. if (! $isCorrectBool) {
  1260. $hasMistake = true;
  1261. }
  1262. }
  1263. }
  1264. // 收集错题记录
  1265. if ($hasMistake) {
  1266. $uniqueKpCodes = array_values(array_unique($allErrorKpCodes));
  1267. $mistakesToSave[] = [
  1268. 'questionId' => $questionId,
  1269. 'question' => $question,
  1270. 'kpMappings' => array_map(fn ($code) => ['kp_id' => $code], $uniqueKpCodes),
  1271. ];
  1272. }
  1273. } else {
  1274. // 单步骤题目:收集题目级记录
  1275. $questionsToInsert[] = [
  1276. 'student_id' => $studentId,
  1277. 'exam_id' => $examId,
  1278. 'question_id' => $questionId,
  1279. 'score_obtained' => $question['score_obtained'] ?? 0,
  1280. 'max_score' => $question['score'] ?? 0,
  1281. 'created_at' => $now,
  1282. 'updated_at' => $now,
  1283. ];
  1284. // 收集错题记录
  1285. if (($question['score_obtained'] ?? 0) <= 0) {
  1286. $mistakesToSave[] = [
  1287. 'questionId' => $questionId,
  1288. 'question' => $question,
  1289. 'kpMappings' => ! empty($kpMappings)
  1290. ? array_map(fn ($m) => ['kp_id' => $m['kp_id']], $kpMappings)
  1291. : null,
  1292. ];
  1293. }
  1294. }
  1295. }
  1296. // 判断是否有变更,避免重复删除/插入
  1297. $stepsChanged = $this->hasAnswerStepsChanged($studentId, $examId, $stepsToInsert);
  1298. $questionsChanged = $this->hasAnswerQuestionsChanged($studentId, $examId, $questionsToInsert);
  1299. if ($stepsChanged || $questionsChanged) {
  1300. // 先清理该考试的所有答题记录(支持重复提交)
  1301. try {
  1302. if ($questionsChanged) {
  1303. DB::connection('mysql')->table('student_answer_questions')
  1304. ->where('student_id', '=', $studentId)
  1305. ->where('exam_id', '=', $examId)
  1306. ->delete();
  1307. }
  1308. if ($stepsChanged) {
  1309. DB::connection('mysql')->table('student_answer_steps')
  1310. ->where('student_id', '=', $studentId)
  1311. ->where('exam_id', '=', $examId)
  1312. ->delete();
  1313. }
  1314. Log::info('清理旧答题记录成功', [
  1315. 'student_id' => $studentId,
  1316. 'exam_id' => $examId,
  1317. 'steps_changed' => $stepsChanged,
  1318. 'questions_changed' => $questionsChanged,
  1319. ]);
  1320. } catch (\Exception $e) {
  1321. // 清理失败时抛出异常,避免后续插入重复数据
  1322. Log::error('清理旧答题记录失败', [
  1323. 'student_id' => $studentId,
  1324. 'exam_id' => $examId,
  1325. 'error' => $e->getMessage(),
  1326. ]);
  1327. throw $e;
  1328. }
  1329. // 【优化】批量 INSERT(每500条一批,避免超过MySQL限制)
  1330. try {
  1331. if ($stepsChanged && ! empty($stepsToInsert)) {
  1332. foreach (array_chunk($stepsToInsert, 500) as $chunk) {
  1333. DB::connection('mysql')->table('student_answer_steps')->insert($chunk);
  1334. }
  1335. }
  1336. if ($questionsChanged && ! empty($questionsToInsert)) {
  1337. foreach (array_chunk($questionsToInsert, 500) as $chunk) {
  1338. DB::connection('mysql')->table('student_answer_questions')->insert($chunk);
  1339. }
  1340. }
  1341. } catch (\Exception $e) {
  1342. Log::error('批量保存答题记录失败', [
  1343. 'student_id' => $studentId,
  1344. 'exam_id' => $examId,
  1345. 'error' => $e->getMessage(),
  1346. ]);
  1347. }
  1348. }
  1349. // 保存错题记录(批量处理,避免逐条写入)
  1350. if (! empty($mistakesToSave)) {
  1351. $payloads = [];
  1352. foreach ($mistakesToSave as $mistake) {
  1353. $kpIds = null;
  1354. if (is_array($mistake['kpMappings'])) {
  1355. $kpIds = isset($mistake['kpMappings'][0])
  1356. ? array_column($mistake['kpMappings'], 'kp_id')
  1357. : [$mistake['kpMappings']['kp_id'] ?? null];
  1358. }
  1359. $payloads[] = [
  1360. 'student_id' => $studentId,
  1361. 'question_id' => $mistake['questionId'],
  1362. 'paper_id' => $examId,
  1363. 'my_answer' => $mistake['question']['student_answer'] ?? null,
  1364. 'correct_answer' => null,
  1365. 'question_text' => null,
  1366. 'knowledge_point' => null,
  1367. 'kp_ids' => $kpIds,
  1368. 'source' => $examId,
  1369. 'happened_at' => now(),
  1370. ];
  1371. }
  1372. $this->mistakeBookService->createMistakesBatch($payloads);
  1373. }
  1374. Log::info('答题记录保存完成', [
  1375. 'student_id' => $studentId,
  1376. 'exam_id' => $examId,
  1377. 'total_questions' => count($examData['questions']),
  1378. 'steps_saved' => count($stepsToInsert),
  1379. 'questions_saved' => count($questionsToInsert),
  1380. 'steps_changed' => $stepsChanged,
  1381. 'questions_changed' => $questionsChanged,
  1382. ]);
  1383. return [
  1384. 'steps_changed' => $stepsChanged,
  1385. 'questions_changed' => $questionsChanged,
  1386. ];
  1387. }
  1388. /**
  1389. * 同步更新 paper_questions 的判分字段
  1390. * 适配 /api/exam-answer-analysis:保持题目判分与分析数据一致
  1391. */
  1392. private function syncPaperQuestionGrading(array $examData): void
  1393. {
  1394. $paperId = (string) ($examData['paper_id'] ?? '');
  1395. if ($paperId === '' || empty($examData['questions']) || !is_array($examData['questions'])) {
  1396. return;
  1397. }
  1398. $now = now();
  1399. $updated = 0;
  1400. foreach ($examData['questions'] as $question) {
  1401. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1402. if (empty($questionId)) {
  1403. continue;
  1404. }
  1405. $isCorrectArray = $question['is_correct'] ?? [];
  1406. if (!is_array($isCorrectArray)) {
  1407. $isCorrectArray = [$isCorrectArray ? 1 : 0];
  1408. }
  1409. $totalSteps = count($isCorrectArray);
  1410. $correctSteps = array_sum(array_map(fn ($v) => (int) $v === 1 ? 1 : 0, $isCorrectArray));
  1411. $scoreRatio = $totalSteps > 0 ? ($correctSteps / $totalSteps) : null;
  1412. $isFullyCorrect = $totalSteps > 0 ? ($correctSteps === $totalSteps) : null;
  1413. $scoreObtained = $question['score_obtained'] ?? null;
  1414. $query = DB::connection('mysql')->table('paper_questions')
  1415. ->where('paper_id', $paperId)
  1416. ->where(function ($q) use ($questionId) {
  1417. $q->where('question_bank_id', $questionId)
  1418. ->orWhere('question_id', $questionId);
  1419. });
  1420. $payload = [
  1421. 'graded_at' => $now,
  1422. ];
  1423. if ($isFullyCorrect !== null) {
  1424. $payload['is_correct'] = $isFullyCorrect ? 1 : 0;
  1425. }
  1426. if ($scoreRatio !== null) {
  1427. $payload['score_ratio'] = round($scoreRatio, 4);
  1428. }
  1429. if ($scoreObtained !== null) {
  1430. $payload['score_obtained'] = $scoreObtained;
  1431. }
  1432. if (array_key_exists('student_answer', $question)) {
  1433. $payload['student_answer'] = $question['student_answer'];
  1434. }
  1435. if (array_key_exists('teacher_comment', $question)) {
  1436. $payload['teacher_comment'] = $question['teacher_comment'];
  1437. }
  1438. $updated += $query->update($payload);
  1439. }
  1440. if ($updated > 0) {
  1441. DB::connection('mysql')->table('papers')
  1442. ->where('paper_id', $paperId)
  1443. ->update([
  1444. 'status' => 'completed',
  1445. 'completed_at' => $now,
  1446. 'updated_at' => $now,
  1447. ]);
  1448. }
  1449. Log::info('paper_questions 判分同步完成', [
  1450. 'paper_id' => $paperId,
  1451. 'input_question_count' => count($examData['questions']),
  1452. 'updated_rows' => $updated,
  1453. ]);
  1454. }
  1455. /**
  1456. * 判断答题步骤记录是否发生变化
  1457. */
  1458. private function hasAnswerStepsChanged(string $studentId, string $examId, array $newSteps): bool
  1459. {
  1460. $existing = DB::connection('mysql')
  1461. ->table('student_answer_steps')
  1462. ->where('student_id', $studentId)
  1463. ->where('exam_id', $examId)
  1464. ->get(['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'])
  1465. ->map(fn ($row) => (array) $row)
  1466. ->toArray();
  1467. return $this->buildRecordsHash($existing, ['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'], ['step_score'])
  1468. !== $this->buildRecordsHash($newSteps, ['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'], ['step_score']);
  1469. }
  1470. /**
  1471. * 判断题目级答题记录是否发生变化
  1472. */
  1473. private function hasAnswerQuestionsChanged(string $studentId, string $examId, array $newQuestions): bool
  1474. {
  1475. $existing = DB::connection('mysql')
  1476. ->table('student_answer_questions')
  1477. ->where('student_id', $studentId)
  1478. ->where('exam_id', $examId)
  1479. ->get(['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'])
  1480. ->map(fn ($row) => (array) $row)
  1481. ->toArray();
  1482. return $this->buildRecordsHash($existing, ['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'], ['score_obtained', 'max_score'])
  1483. !== $this->buildRecordsHash($newQuestions, ['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'], ['score_obtained', 'max_score']);
  1484. }
  1485. /**
  1486. * 构建记录哈希,用于判断是否变化
  1487. */
  1488. private function buildRecordsHash(array $rows, array $fields, array $numericFields = []): string
  1489. {
  1490. if (empty($rows)) {
  1491. return '[]';
  1492. }
  1493. $normalized = [];
  1494. $numericFieldMap = array_fill_keys($numericFields, true);
  1495. foreach ($rows as $row) {
  1496. $item = [];
  1497. foreach ($fields as $field) {
  1498. $value = $row[$field] ?? null;
  1499. if ($value !== null && isset($numericFieldMap[$field]) && is_numeric($value)) {
  1500. $value = sprintf('%.4F', (float) $value);
  1501. }
  1502. $item[$field] = $value;
  1503. }
  1504. $normalized[] = $item;
  1505. }
  1506. usort($normalized, fn ($a, $b) => json_encode($a) <=> json_encode($b));
  1507. return md5(json_encode($normalized));
  1508. }
  1509. /**
  1510. * 保存分析结果并创建掌握度快照
  1511. */
  1512. private function saveAnalysisResult(string $studentId, string $paperId, array $result): void
  1513. {
  1514. // 【修复】支持重复分析:先删除旧的分析结果
  1515. DB::connection('mysql')->table('exam_analysis_results')
  1516. ->where('student_id', $studentId)
  1517. ->where('paper_id', $paperId)
  1518. ->delete();
  1519. // 插入新的分析结果
  1520. DB::connection('mysql')->table('exam_analysis_results')->insert([
  1521. 'student_id' => $studentId,
  1522. 'paper_id' => $paperId,
  1523. 'analysis_data' => json_encode($result),
  1524. 'created_at' => now(),
  1525. 'updated_at' => now(),
  1526. ]);
  1527. Log::info('分析结果保存完成', [
  1528. 'student_id' => $studentId,
  1529. 'paper_id' => $paperId,
  1530. 'data_size' => strlen(json_encode($result)),
  1531. ]);
  1532. // 【新增】异步生成学情分析PDF
  1533. try {
  1534. Log::info('开始异步生成学情分析PDF', [
  1535. 'student_id' => $studentId,
  1536. 'paper_id' => $paperId,
  1537. ]);
  1538. // 使用队列异步生成PDF,避免阻塞主流程
  1539. dispatch(new \App\Jobs\GenerateAnalysisPdfJob($paperId, $studentId, null));
  1540. Log::info('PDF生成任务已加入队列', [
  1541. 'student_id' => $studentId,
  1542. 'paper_id' => $paperId,
  1543. ]);
  1544. } catch (\Exception $e) {
  1545. Log::error('PDF生成任务加入队列失败', [
  1546. 'student_id' => $studentId,
  1547. 'paper_id' => $paperId,
  1548. 'error' => $e->getMessage(),
  1549. ]);
  1550. }
  1551. }
  1552. /**
  1553. * 创建知识点掌握度快照
  1554. * 【集成】使用LocalAIAnalysisService的快照功能
  1555. *
  1556. * 快照用途:
  1557. * 1. 追踪学生掌握度变化趋势
  1558. * 2. 生成学情报告时对比历史数据
  1559. * 3. 为智能出卷提供决策依据
  1560. */
  1561. private function createMasterySnapshot(string $studentId, string $paperId, array $analysisResult): ?array
  1562. {
  1563. try {
  1564. // 计算快照数据
  1565. $masteryVector = $analysisResult['mastery_vector'] ?? [];
  1566. $overallMastery = 0;
  1567. $weakCount = 0;
  1568. $strongCount = 0;
  1569. foreach ($masteryVector as $kpData) {
  1570. $mastery = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0;
  1571. $overallMastery += $mastery;
  1572. if ($mastery < 0.6) {
  1573. $weakCount++;
  1574. } elseif ($mastery >= 0.85) {
  1575. $strongCount++;
  1576. }
  1577. }
  1578. $kpCount = count($masteryVector);
  1579. $overallMastery = $kpCount > 0 ? round($overallMastery / $kpCount, 4) : 0;
  1580. // Get all existing mastery records from database (as baseline)
  1581. // Use DB::table to avoid Eloquent accessor converting numbers to strings
  1582. $studentMasteries = DB::table('student_knowledge_mastery')
  1583. ->where('student_id', $studentId)
  1584. ->get(['kp_code', 'mastery_level']);
  1585. $currentMastery = [];
  1586. foreach ($studentMasteries as $record) {
  1587. $currentMastery[$record->kp_code] = (float) ($record->mastery_level ?? 0);
  1588. }
  1589. // Update with newly calculated mastery values from analysis result
  1590. foreach ($masteryVector as $kpData) {
  1591. $kpCode = $kpData['kp_id'] ?? null;
  1592. if (! $kpCode) {
  1593. continue;
  1594. }
  1595. $analysisLevel = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0;
  1596. // Use new analysis value if it's higher, or if there was no previous value
  1597. if (! isset($currentMastery[$kpCode]) || $analysisLevel > $currentMastery[$kpCode]) {
  1598. $currentMastery[$kpCode] = $analysisLevel;
  1599. }
  1600. }
  1601. // 生成快照ID
  1602. $snapshotId = 'snap_'.$paperId.'_'.now()->format('YmdHis').'_'.substr(uniqid(), -4);
  1603. // 保存到快照表
  1604. DB::connection('mysql')->table('knowledge_point_mastery_snapshots')->insert([
  1605. 'snapshot_id' => $snapshotId,
  1606. 'student_id' => $studentId,
  1607. 'paper_id' => $paperId,
  1608. 'answer_record_id' => null,
  1609. 'mastery_data' => json_encode($masteryVector),
  1610. 'current_mastery' => json_encode($currentMastery),
  1611. 'overall_mastery' => $overallMastery,
  1612. 'weak_knowledge_points_count' => $weakCount,
  1613. 'strong_knowledge_points_count' => $strongCount,
  1614. 'snapshot_time' => now(),
  1615. 'analysis_id' => null,
  1616. 'created_at' => now(),
  1617. 'updated_at' => now(),
  1618. ]);
  1619. Log::info('掌握度快照创建成功', [
  1620. 'snapshot_id' => $snapshotId,
  1621. 'student_id' => $studentId,
  1622. 'paper_id' => $paperId,
  1623. 'overall_mastery' => $overallMastery,
  1624. 'weak_count' => $weakCount,
  1625. 'strong_count' => $strongCount,
  1626. ]);
  1627. // 计算变化
  1628. $lastSnapshot = DB::connection('mysql')->table('knowledge_point_mastery_snapshots')
  1629. ->where('student_id', $studentId)
  1630. ->where('snapshot_id', '<>', $snapshotId)
  1631. ->orderBy('snapshot_time', 'desc')
  1632. ->first();
  1633. $gainCount = $lossCount = 0;
  1634. $overallChange = 0;
  1635. $compareCount = 0;
  1636. $changeAverage = 0;
  1637. if ($lastSnapshot && ! empty($lastSnapshot->current_mastery)) {
  1638. $lastCurrentMastery = json_decode($lastSnapshot->current_mastery, true);
  1639. if (is_array($lastCurrentMastery)) {
  1640. foreach ($currentMastery as $kp => $value) {
  1641. $prev = $lastCurrentMastery[$kp] ?? null;
  1642. if ($prev === null) {
  1643. $gainCount++;
  1644. } elseif ($value > $prev) {
  1645. $gainCount++;
  1646. } elseif ($value < $prev) {
  1647. $lossCount++;
  1648. }
  1649. if ($prev !== null) {
  1650. $overallChange += $value - $prev;
  1651. $compareCount++;
  1652. }
  1653. }
  1654. $changeAverage = $compareCount > 0 ? round($overallChange / $compareCount, 4) : 0;
  1655. Log::info('掌握度变化', [
  1656. 'student_id' => $studentId,
  1657. 'paper_id' => $paperId,
  1658. 'snapshot_id' => $snapshotId,
  1659. 'gain_count' => $gainCount,
  1660. 'loss_count' => $lossCount,
  1661. 'overall_change' => $changeAverage,
  1662. ]);
  1663. }
  1664. }
  1665. return [
  1666. 'snapshot_id' => $snapshotId,
  1667. 'current_mastery' => $currentMastery,
  1668. 'overall_mastery' => $overallMastery,
  1669. 'gain_count' => $gainCount,
  1670. 'loss_count' => $lossCount,
  1671. 'overall_change' => $changeAverage,
  1672. ];
  1673. } catch (\Exception $e) {
  1674. // 快照创建失败不影响主流程
  1675. Log::warning('掌握度快照创建失败', [
  1676. 'student_id' => $studentId,
  1677. 'paper_id' => $paperId,
  1678. 'error' => $e->getMessage(),
  1679. ]);
  1680. return null;
  1681. }
  1682. }
  1683. /**
  1684. * 判断掌握度趋势
  1685. */
  1686. /**
  1687. * 评估表现水平
  1688. */
  1689. private function evaluatePerformanceLevel(float $mastery): string
  1690. {
  1691. if ($mastery >= 0.85) {
  1692. return 'excellent';
  1693. } elseif ($mastery >= 0.70) {
  1694. return 'good';
  1695. } elseif ($mastery >= 0.50) {
  1696. return 'fair';
  1697. } else {
  1698. return 'poor';
  1699. }
  1700. }
  1701. /**
  1702. * 生成题目表现总结
  1703. */
  1704. private function generateQuestionPerformanceSummary(array $question, array $stepAnalysis): string
  1705. {
  1706. if (empty($stepAnalysis)) {
  1707. return '整题作答';
  1708. }
  1709. $correctSteps = count(array_filter($stepAnalysis, fn ($s) => $s['is_correct']));
  1710. $totalSteps = count($stepAnalysis);
  1711. if ($correctSteps === $totalSteps) {
  1712. return '所有步骤正确';
  1713. } elseif ($correctSteps > 0) {
  1714. return "部分正确 ({$correctSteps}/{$totalSteps} 步骤正确)";
  1715. } else {
  1716. return '所有步骤错误';
  1717. }
  1718. }
  1719. /**
  1720. * 生成知识点建议
  1721. */
  1722. private function generateKnowledgePointRecommendation(array $data): string
  1723. {
  1724. $mastery = $data['mastery'];
  1725. if ($mastery >= 0.85) {
  1726. return '掌握良好,可安排综合练习';
  1727. } elseif ($mastery >= 0.70) {
  1728. return '基本掌握,建议加强练习';
  1729. } elseif ($mastery >= 0.50) {
  1730. return '需要重点练习,建议安排专项训练';
  1731. } else {
  1732. return '薄弱知识点,建议系统学习和大量练习';
  1733. }
  1734. }
  1735. /**
  1736. * 评估整体表现
  1737. */
  1738. private function evaluateOverallPerformance(float $averageMastery): string
  1739. {
  1740. if ($averageMastery >= 0.85) {
  1741. return '优秀';
  1742. } elseif ($averageMastery >= 0.70) {
  1743. return '良好';
  1744. } elseif ($averageMastery >= 0.50) {
  1745. return '一般';
  1746. } else {
  1747. return '需加强';
  1748. }
  1749. }
  1750. /**
  1751. * 计算推荐题目数量
  1752. */
  1753. private function calculateRecommendedQuestions(float $mastery): int
  1754. {
  1755. if ($mastery >= 0.85) {
  1756. return 1; // 巩固型:1题
  1757. } elseif ($mastery >= 0.50) {
  1758. return 2; // 修补型:2题
  1759. } else {
  1760. return 3; // 挑战型:3题
  1761. }
  1762. }
  1763. /**
  1764. * 确定重点类型
  1765. */
  1766. private function determineFocusType(float $mastery): string
  1767. {
  1768. if ($mastery >= 0.70 && $mastery < 0.85) {
  1769. return 'consolidation'; // 巩固型
  1770. } elseif ($mastery < 0.70) {
  1771. return 'remediation'; // 修补型
  1772. } else {
  1773. return 'challenge'; // 挑战型
  1774. }
  1775. }
  1776. /**
  1777. * 自动计算题目分数并补充未提交的题目
  1778. *
  1779. * 功能:
  1780. * 1. 从 paper_questions 表获取卷子的所有题目
  1781. * 2. 补充未提交的题目(is_correct 默认为 [0],表示错误)
  1782. * 3. 自动计算 score 和 score_obtained
  1783. *
  1784. * @param array $questions 用户提交的题目列表
  1785. * @param string $paperId 卷子ID
  1786. * @return array 完整的题目列表(包含未提交的题目)
  1787. */
  1788. private function autoCalculateScores(array $questions, string $paperId = ''): array
  1789. {
  1790. // 获取已提交题目的ID集合
  1791. $submittedQuestionIds = [];
  1792. foreach ($questions as $question) {
  1793. $qid = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1794. if ($qid) {
  1795. $submittedQuestionIds[$qid] = true;
  1796. }
  1797. }
  1798. // 从 paper_questions 表获取卷子的所有题目
  1799. if (! empty($paperId)) {
  1800. try {
  1801. $paperQuestions = DB::connection('mysql')
  1802. ->table('paper_questions')
  1803. ->where('paper_id', $paperId)
  1804. ->get(['question_bank_id', 'question_id', 'score']);
  1805. foreach ($paperQuestions as $pq) {
  1806. // 优先用 question_bank_id,其次用 question_id
  1807. $questionId = $pq->question_bank_id ?? $pq->question_id ?? null;
  1808. if (empty($questionId)) {
  1809. continue;
  1810. }
  1811. if (isset($pq->score)) {
  1812. $scoreMap[$questionId] = (float) $pq->score;
  1813. }
  1814. // 如果该题目未提交,补充进去
  1815. if (! isset($submittedQuestionIds[$questionId])) {
  1816. $defaultScore = $pq->score ? floatval($pq->score) : 2.0;
  1817. $questions[] = [
  1818. 'question_id' => $questionId,
  1819. 'student_answer' => null,
  1820. 'is_correct' => [1], // 未提交默认为正确
  1821. 'teacher_comment' => null,
  1822. 'score' => $defaultScore,
  1823. 'score_obtained' => $defaultScore, // 正确则得满分
  1824. ];
  1825. Log::debug('补充未提交的题目', [
  1826. 'paper_id' => $paperId,
  1827. 'question_id' => $questionId,
  1828. 'default_score' => $pq->score ?? 2.0,
  1829. ]);
  1830. }
  1831. }
  1832. } catch (\Exception $e) {
  1833. Log::warning('获取卷子题目列表失败', [
  1834. 'paper_id' => $paperId,
  1835. 'error' => $e->getMessage(),
  1836. ]);
  1837. }
  1838. }
  1839. // 为已提交的题目计算分数
  1840. foreach ($questions as &$question) {
  1841. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? '';
  1842. // 如果用户没有提供 score,尝试从数据库获取或使用默认值
  1843. if (! isset($question['score'])) {
  1844. $question['score'] = $scoreMap[$questionId] ?? 2.0;
  1845. }
  1846. // 如果用户没有提供 score_obtained,根据 is_correct 计算
  1847. if (! isset($question['score_obtained'])) {
  1848. $question['score_obtained'] = $this->calculateScoreObtained(
  1849. $question['score'] ?? 0,
  1850. $question['is_correct'] ?? []
  1851. );
  1852. }
  1853. Log::debug('自动计算分数', [
  1854. 'question_id' => $questionId,
  1855. 'default_score' => $question['score'],
  1856. 'score_obtained' => $question['score_obtained'],
  1857. 'is_correct' => $question['is_correct'] ?? [],
  1858. ]);
  1859. }
  1860. return $questions;
  1861. }
  1862. /**
  1863. * 获取题目默认分数
  1864. */
  1865. private function getQuestionDefaultScore(string $questionId): float
  1866. {
  1867. if (empty($questionId)) {
  1868. return 2.0; // 默认分数
  1869. }
  1870. try {
  1871. // 尝试从题库获取题目分数
  1872. $question = DB::connection('mysql')
  1873. ->table('questions')
  1874. ->where('id', $questionId)
  1875. ->orWhere('question_code', $questionId)
  1876. ->first();
  1877. if ($question && isset($question->score)) {
  1878. return (float) $question->score;
  1879. }
  1880. // 如果没有找到,根据题目ID生成一个合理的默认分数
  1881. // 这里可以根据需要调整默认分数逻辑
  1882. return 2.0;
  1883. } catch (\Exception $e) {
  1884. Log::warning('获取题目默认分数失败,使用默认值', [
  1885. 'question_id' => $questionId,
  1886. 'error' => $e->getMessage(),
  1887. ]);
  1888. return 2.0;
  1889. }
  1890. }
  1891. /**
  1892. * 根据 is_correct 数组计算得分
  1893. *
  1894. * @param float $totalScore 总分
  1895. * @param array $isCorrect 正确性数组 [0, 1, 1] 表示第1题错误,第2、3题正确
  1896. * @return float 得分
  1897. */
  1898. private function calculateScoreObtained(float $totalScore, array $isCorrect): float
  1899. {
  1900. if (empty($isCorrect)) {
  1901. return 0.0;
  1902. }
  1903. $correctCount = array_sum($isCorrect);
  1904. $totalCount = count($isCorrect);
  1905. if ($totalCount === 0) {
  1906. return 0.0;
  1907. }
  1908. // 按正确率计算得分
  1909. $scoreRatio = $correctCount / $totalCount;
  1910. return round($totalScore * $scoreRatio, 2);
  1911. }
  1912. }