ExamAnswerAnalysisService.php 92 KB

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