ExamAnswerAnalysisService.php 70 KB

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