ExamAnswerAnalysisService.php 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859
  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. * 【公司要求】计算并更新父节点掌握度(支持多级递归)
  687. *
  688. * 公司要求:
  689. * 1. 查询结构:通过 knowledge_points 表获取知识点的层级关系(parent_kp_code)
  690. * 2. 平均值计算:如果一个知识点是父节点,它的掌握度不再从数据库直接读,
  691. * 而是实时计算其下所有子节点掌握度的算术平均数
  692. * 3. 多级递归:支持多级结构,能够从最底层逐级向上求平均
  693. *
  694. * 递归计算流程:
  695. * - 从最底层节点开始,逐级向上递归计算父节点掌握度
  696. * - 父节点掌握度 = 所有子节点掌握度的算术平均数
  697. * - 支持任意层级结构,递归深度限制为10级
  698. *
  699. * @param string $studentId 学生ID
  700. * @param array $childKpCodes 当前层的子节点编码列表
  701. * @param int $maxDepth 最大递归深度(防止无限递归,默认10级)
  702. * @return array 返回所有层级的父节点掌握度数据
  703. */
  704. private function updateParentMasteryLevels(string $studentId, array $childKpCodes, int $maxDepth = 2): array
  705. {
  706. $allParentMasteryData = [];
  707. $currentLevelChildCodes = $childKpCodes;
  708. $processedNodes = new \ArrayObject(); // 防止重复处理
  709. try {
  710. // 【公司要求】多级递归:逐级向上递归计算,支持多级结构
  711. for ($level = 0; $level < $maxDepth; $level++) {
  712. if (empty($currentLevelChildCodes)) {
  713. break; // 没有更多父节点,退出循环
  714. }
  715. // 【公司要求】查询结构:通过 knowledge_points 表获取知识点的层级关系(parent_kp_code)
  716. // 获取当前层子节点的直接父节点
  717. $parentKpCodes = DB::connection('mysql')
  718. ->table('knowledge_points')
  719. ->whereIn('kp_code', $currentLevelChildCodes)
  720. ->whereNotNull('parent_kp_code')
  721. ->distinct()
  722. ->pluck('parent_kp_code')
  723. ->toArray();
  724. if (empty($parentKpCodes)) {
  725. Log::debug("第{$level}层没有更多父节点,递归结束");
  726. break;
  727. }
  728. $currentLevelParentData = [];
  729. foreach ($parentKpCodes as $parentKpCode) {
  730. // 防止重复处理同一节点
  731. if (isset($processedNodes[$parentKpCode])) {
  732. continue;
  733. }
  734. $processedNodes[$parentKpCode] = true;
  735. // 【公司要求】平均值计算:使用MasteryCalculator计算父节点掌握度(实时计算)
  736. // 父节点掌握度 = 所有子节点掌握度的算术平均数
  737. $parentMastery = $this->masteryCalculator->calculateParentMastery($studentId, $parentKpCode);
  738. // 获取父节点历史数据
  739. $historyParentMastery = DB::connection('mysql')
  740. ->table('student_knowledge_mastery')
  741. ->where('student_id', $studentId)
  742. ->where('kp_code', $parentKpCode)
  743. ->first();
  744. $previousMastery = $historyParentMastery->mastery_level ?? 0.0;
  745. // 【自己要求】保存父节点掌握度到数据库(只保存核心数据)
  746. DB::connection('mysql')
  747. ->table('student_knowledge_mastery')
  748. ->updateOrInsert(
  749. ['student_id' => $studentId, 'kp_code' => $parentKpCode],
  750. [
  751. 'mastery_level' => $parentMastery,
  752. 'confidence_level' => 0.0, // 不再保存置信度
  753. 'total_attempts' => 1, // 父节点不记录答题次数
  754. 'correct_attempts' => 0, // 父节点不记录正确次数
  755. 'mastery_trend' => 'stable', // 统一设为stable
  756. 'last_mastery_update' => now(),
  757. 'updated_at' => now(),
  758. ]
  759. );
  760. // 【公司要求】记录当前层级数据(移除置信度)
  761. $currentLevelParentData[$parentKpCode] = [
  762. 'kp_id' => $parentKpCode,
  763. 'current_mastery' => $parentMastery,
  764. 'previous_mastery' => $previousMastery,
  765. 'change' => $parentMastery - $previousMastery,
  766. 'weight' => 1,
  767. 'is_parent' => true,
  768. 'level' => $level + 1 // 记录层级深度
  769. ];
  770. Log::debug("第" . ($level + 1) . "层父节点掌握度已更新", [
  771. 'student_id' => $studentId,
  772. 'parent_kp_code' => $parentKpCode,
  773. 'parent_mastery' => $parentMastery,
  774. 'child_nodes_count' => count($currentLevelChildCodes)
  775. ]);
  776. }
  777. // 合并到总结果中
  778. $allParentMasteryData = array_merge($allParentMasteryData, $currentLevelParentData);
  779. // 【公司要求】多级递归:准备下一轮递归,从最底层逐级向上求平均
  780. // 当前层的父节点作为下一层的子节点
  781. $currentLevelChildCodes = $parentKpCodes;
  782. }
  783. if (!empty($allParentMasteryData)) {
  784. $totalParentCount = count($allParentMasteryData);
  785. $maxLevel = 0;
  786. foreach ($allParentMasteryData as $data) {
  787. $maxLevel = max($maxLevel, $data['level']);
  788. }
  789. Log::info('多级父节点掌握度计算完成', [
  790. 'student_id' => $studentId,
  791. 'child_count' => count($childKpCodes),
  792. 'total_parent_count' => $totalParentCount,
  793. 'max_level' => $maxLevel,
  794. 'all_parent_kp_codes' => array_keys($allParentMasteryData)
  795. ]);
  796. }
  797. } catch (\Exception $e) {
  798. Log::error('计算多级父节点掌握度失败', [
  799. 'student_id' => $studentId,
  800. 'child_kp_codes' => $childKpCodes,
  801. 'current_level' => $currentLevelChildCodes,
  802. 'error' => $e->getMessage(),
  803. 'trace' => $e->getTraceAsString()
  804. ]);
  805. }
  806. return $allParentMasteryData;
  807. }
  808. /**
  809. * 生成题目维度分析(包含AI分析和解题思路)
  810. */
  811. private function analyzeQuestions(array $questions, array $questionMappings): array
  812. {
  813. $analysis = [];
  814. foreach ($questions as $question) {
  815. $questionId = $question['question_id'];
  816. $score = floatval($question['score_obtained'] ?? 0);
  817. $maxScore = floatval($question['score'] ?? $score);
  818. $steps = $question['steps'] ?? [];
  819. $isCorrect = $question['is_correct'] ?? ($score >= $maxScore);
  820. $mapping = $questionMappings[$questionId] ?? ['kp_mapping' => []];
  821. if (empty($mapping['kp_mapping'])) {
  822. Log::warning('ExamAnswerAnalysisService: 题目无知识点映射', ['question_id' => $questionId]);
  823. continue;
  824. }
  825. $kpCode = $mapping['kp_mapping'][0]['kp_id'];
  826. // 步骤分析
  827. $stepAnalysis = [];
  828. if (!empty($steps)) {
  829. foreach ($steps as $step) {
  830. $kpId = $step['kp_id'];
  831. if (empty($kpId)) {
  832. Log::warning('ExamAnswerAnalysisService: 步骤缺少知识点ID', [
  833. 'question_id' => $questionId,
  834. 'step_index' => $step['step_index'] ?? 'unknown'
  835. ]);
  836. continue;
  837. }
  838. $stepAnalysis[] = [
  839. 'step_index' => $step['step_index'],
  840. 'is_correct' => $step['is_correct'],
  841. 'kp_id' => $kpId,
  842. 'description' => $step['description'] ?? ''
  843. ];
  844. }
  845. }
  846. // 知识点关联
  847. $knowledgePoints = array_map(function($kp) {
  848. return [
  849. 'kp_id' => $kp['kp_id'],
  850. 'kp_name' => $kp['kp_name'] ?? $kp['kp_id'],
  851. 'weight' => $kp['weight'] ?? 1.0
  852. ];
  853. }, $mapping['kp_mapping']);
  854. // 【集成】调用AI分析服务,获取解题思路和错误分析
  855. $aiAnalysis = $this->getQuestionAIAnalysis($question, $mapping);
  856. $analysis[] = [
  857. 'question_id' => $questionId,
  858. 'score_obtained' => $score,
  859. 'max_score' => $maxScore,
  860. 'accuracy_rate' => $maxScore > 0 ? $score / $maxScore : 0,
  861. 'is_correct' => $isCorrect,
  862. 'step_analysis' => $stepAnalysis,
  863. 'knowledge_points' => $knowledgePoints,
  864. 'performance_summary' => $this->generateQuestionPerformanceSummary($question, $stepAnalysis),
  865. // 【新增】解题思路和错误分析
  866. 'solution_process' => $aiAnalysis['solution_process'] ?? '',
  867. 'error_analysis' => $aiAnalysis['error_analysis'] ?? '',
  868. 'mistake_type' => $aiAnalysis['mistake_type'] ?? '',
  869. 'suggestions' => $aiAnalysis['suggestions'] ?? '',
  870. 'next_steps' => $aiAnalysis['next_steps'] ?? [],
  871. ];
  872. }
  873. return $analysis;
  874. }
  875. /**
  876. * 获取题目的AI分析(解题思路、错误分析)
  877. */
  878. private function getQuestionAIAnalysis(array $question, array $mapping): array
  879. {
  880. $isCorrect = $question['is_correct'] ?? false;
  881. $score = floatval($question['score_obtained'] ?? 0);
  882. $maxScore = floatval($question['score'] ?? 10);
  883. $kpCode = $mapping['kp_mapping'][0]['kp_id'] ?? null;
  884. if (empty($kpCode)) {
  885. Log::warning('ExamAnswerAnalysisService: getQuestionAIAnalysis缺少知识点ID', [
  886. 'question_id' => $question['question_id'] ?? 'unknown',
  887. 'mapping' => $mapping
  888. ]);
  889. $kpCode = 'UNKNOWN_KP';
  890. }
  891. // 调用LocalAIAnalysisService进行分析
  892. try {
  893. $analysisResult = $this->aiAnalysisService->analyzeAnswer([
  894. 'question_id' => $question['question_id'],
  895. 'question_text' => $question['question_text'] ?? '',
  896. 'student_answer' => $question['student_answer'] ?? '',
  897. 'correct_answer' => $question['correct_answer'] ?? '',
  898. 'score' => $score,
  899. 'max_score' => $maxScore,
  900. 'kp_code' => $kpCode,
  901. ]);
  902. $data = $analysisResult['data'] ?? [];
  903. // 根据正确性生成不同的解题思路
  904. if ($isCorrect) {
  905. return [
  906. 'solution_process' => $data['correct_solution'] ?? '该题作答正确,解题思路清晰',
  907. 'error_analysis' => '',
  908. 'mistake_type' => '',
  909. 'suggestions' => $data['suggestions'] ?? '继续保持良好的解题习惯',
  910. 'next_steps' => $data['next_steps'] ?? ['尝试更高难度的同类题目'],
  911. ];
  912. }
  913. // 错误题目:返回详细分析
  914. return [
  915. 'solution_process' => $data['correct_solution'] ?? '请参考标准解题步骤',
  916. 'error_analysis' => $data['reason'] ?? '解题过程中存在错误',
  917. 'mistake_type' => $data['mistake_type'] ?? '计算或理解错误',
  918. 'suggestions' => $data['suggestions'] ?? '建议针对薄弱知识点进行专项练习',
  919. 'next_steps' => $data['next_steps'] ?? ['复习相关知识点', '做同类型练习题'],
  920. ];
  921. } catch (\Exception $e) {
  922. Log::warning('AI分析失败,使用默认分析', [
  923. 'question_id' => $question['question_id'],
  924. 'error' => $e->getMessage(),
  925. ]);
  926. // 回退到基础分析
  927. return $this->getFallbackAnalysis($question, $isCorrect);
  928. }
  929. }
  930. /**
  931. * 回退分析(当AI分析失败时)
  932. */
  933. private function getFallbackAnalysis(array $question, bool $isCorrect): array
  934. {
  935. if ($isCorrect) {
  936. return [
  937. 'solution_process' => '该题作答正确',
  938. 'error_analysis' => '',
  939. 'mistake_type' => '',
  940. 'suggestions' => '继续保持',
  941. 'next_steps' => ['尝试更高难度的题目'],
  942. ];
  943. }
  944. $scoreRatio = floatval($question['score_obtained'] ?? 0) / max(floatval($question['score'] ?? 1), 1);
  945. return [
  946. 'solution_process' => '请参考标准答案和解题步骤',
  947. 'error_analysis' => $scoreRatio < 0.3 ? '知识点理解存在偏差' : '解题过程中出现错误',
  948. 'mistake_type' => $scoreRatio < 0.3 ? '概念错误' : '计算/步骤错误',
  949. 'suggestions' => '建议复习相关知识点,加强练习',
  950. 'next_steps' => ['复习基础概念', '做同类型练习题', '请教老师或同学'],
  951. ];
  952. }
  953. /**
  954. * 生成知识点维度分析
  955. */
  956. private function analyzeKnowledgePoints(array $knowledgeMasteryVector, array $questionMappings): array
  957. {
  958. $analysis = [];
  959. foreach ($knowledgeMasteryVector as $kpId => $data) {
  960. // 【公司要求】移除置信度,只保留核心掌握度分析
  961. $analysis[] = [
  962. 'kp_id' => $kpId,
  963. 'mastery_level' => $data['mastery'],
  964. 'performance_in_exam' => $this->evaluatePerformanceLevel($data['mastery']),
  965. 'evidence_count' => count($data['step_details']),
  966. 'step_evidence' => $data['step_details'],
  967. 'recommendation' => $this->generateKnowledgePointRecommendation($data)
  968. ];
  969. }
  970. return $analysis;
  971. }
  972. /**
  973. * 生成整体掌握度总结
  974. */
  975. private function generateOverallSummary(array $updatedMastery): array
  976. {
  977. $knowledgePoints = array_values($updatedMastery);
  978. if (empty($knowledgePoints)) {
  979. return [
  980. 'total_knowledge_points' => 0,
  981. 'average_mastery' => 0,
  982. 'mastery_distribution' => [
  983. 'mastered' => 0,
  984. 'good' => 0,
  985. 'weak' => 0
  986. ],
  987. 'top_strengths' => [],
  988. 'top_weaknesses' => []
  989. ];
  990. }
  991. // 计算平均掌握度(只计算子节点,不包括父节点)
  992. $childNodes = array_filter($knowledgePoints, fn($kp) => !($kp['is_parent'] ?? false));
  993. $totalChildNodes = count($childNodes);
  994. if ($totalChildNodes === 0) {
  995. // 如果没有子节点,只计算所有节点
  996. $averageMastery = array_sum(array_column($knowledgePoints, 'current_mastery')) / count($knowledgePoints);
  997. } else {
  998. // 计算所有节点的平均掌握度(包括父节点)
  999. $allMastery = array_column($knowledgePoints, 'current_mastery');
  1000. $averageMastery = array_sum($allMastery) / count($allMastery);
  1001. }
  1002. // 掌握度分布(只统计子节点)
  1003. $mastered = array_filter($childNodes, fn($kp) => $kp['current_mastery'] >= 0.85);
  1004. $good = array_filter($childNodes, fn($kp) => $kp['current_mastery'] >= 0.70 && $kp['current_mastery'] < 0.85);
  1005. $weak = array_filter($childNodes, fn($kp) => $kp['current_mastery'] < 0.70);
  1006. // 排序找出优势和薄弱点(只包括子节点)
  1007. usort($childNodes, fn($a, $b) => $b['current_mastery'] <=> $a['current_mastery']);
  1008. $topStrengths = array_slice($childNodes, 0, 3);
  1009. $topWeaknesses = array_slice(array_reverse($childNodes), 0, 3);
  1010. // 统计父子节点数量
  1011. $childCount = count(array_filter($knowledgePoints, fn($kp) => !($kp['is_parent'] ?? false)));
  1012. $parentCount = count(array_filter($knowledgePoints, fn($kp) => $kp['is_parent'] ?? false));
  1013. return [
  1014. 'total_knowledge_points' => $totalChildNodes, // 只统计子节点数量
  1015. 'child_nodes_count' => $childCount,
  1016. 'parent_nodes_count' => $parentCount,
  1017. 'average_mastery' => round($averageMastery, 4),
  1018. 'mastery_distribution' => [
  1019. 'mastered' => count($mastered),
  1020. 'good' => count($good),
  1021. 'weak' => count($weak)
  1022. ],
  1023. 'top_strengths' => $topStrengths,
  1024. 'top_weaknesses' => $topWeaknesses,
  1025. 'overall_performance' => $this->evaluateOverallPerformance($averageMastery)
  1026. ];
  1027. }
  1028. /**
  1029. * 生成智能出卷推荐依据
  1030. * 基于文档中的推荐优先级算法
  1031. */
  1032. private function generateSmartQuizRecommendation(array $updatedMastery): array
  1033. {
  1034. $recommendations = [];
  1035. // 只对子节点生成推荐,忽略父节点
  1036. foreach ($updatedMastery as $kpId => $data) {
  1037. // 跳过父节点
  1038. if ($data['is_parent'] ?? false) {
  1039. continue;
  1040. }
  1041. $mastery = $data['current_mastery'];
  1042. // 【公司要求】移除置信度,只使用掌握度计算推荐
  1043. $weight = $data['weight'];
  1044. // 推荐优先级 = (1 - 掌握度) * 重要性 * 覆盖需求
  1045. // 重要性可以根据知识点在中考/阶段考试中的权重,这里简化为1.0
  1046. $importance = 1.0;
  1047. // 覆盖需求:最近没考过或考得少,值大
  1048. $coverageNeed = max(1.0, 1.5 - ($weight / 10));
  1049. $priority = (1 - $mastery) * $importance * $coverageNeed;
  1050. $recommendations[] = [
  1051. 'kp_id' => $kpId,
  1052. 'current_mastery' => $mastery,
  1053. 'priority' => $priority,
  1054. 'recommended_questions' => $this->calculateRecommendedQuestions($mastery),
  1055. 'focus_type' => $this->determineFocusType($mastery)
  1056. ];
  1057. }
  1058. // 按优先级排序
  1059. usort($recommendations, fn($a, $b) => $b['priority'] <=> $a['priority']);
  1060. // 控制难度节奏:40%巩固型 + 40%修补型 + 20%挑战型
  1061. $totalRecommendations = count($recommendations);
  1062. $consolidation = array_slice($recommendations, 0, intval($totalRecommendations * 0.4));
  1063. $remediation = array_slice($recommendations, intval($totalRecommendations * 0.4), intval($totalRecommendations * 0.4));
  1064. $challenge = array_slice($recommendations, intval($totalRecommendations * 0.8));
  1065. return [
  1066. 'priority_list' => $recommendations,
  1067. 'quiz_structure' => [
  1068. 'consolidation_type' => $consolidation,
  1069. 'remediation_type' => $remediation,
  1070. 'challenge_type' => $challenge
  1071. ],
  1072. 'total_recommended_questions' => array_sum(array_column($recommendations, 'recommended_questions'))
  1073. ];
  1074. }
  1075. /**
  1076. * 保存考试答题记录
  1077. *
  1078. * 入参格式示例:
  1079. * {
  1080. * "question_bank_id": "12979",
  1081. * "student_answer": "C",
  1082. * "is_correct": [0], // 数组长度决定步骤数,0=错误,1=正确
  1083. * "teacher_comment": null
  1084. * }
  1085. *
  1086. * is_correct 数组说明:
  1087. * - 单选题:[1] 或 [0],长度为1
  1088. * - 填空题:[1, 0, 1],每个空一个元素
  1089. * - 简答题:[1, 1, 0, 1],每个得分步骤一个元素
  1090. */
  1091. /**
  1092. * 保存错题记录
  1093. *
  1094. * @param string $studentId 学生ID
  1095. * @param string $questionId 题目ID
  1096. * @param string $examId 考试ID
  1097. * @param array $question 题目数据
  1098. * @param array|null $kpMapping 知识点映射(数组格式:[kp_id1, kp_id2] 或 null)
  1099. */
  1100. private function saveMistakeRecord(string $studentId, string $questionId, string $examId, array $question, ?array $kpMapping): void
  1101. {
  1102. try {
  1103. // 如果 $kpMapping 是数组,说明是多个 kp_id
  1104. // 如果是关联数组,说明是单个 kpMapping(兼容旧调用)
  1105. $kpIds = null;
  1106. if (is_array($kpMapping)) {
  1107. // 检查是数组的数组(多个kp_id)还是关联数组(单个kpMapping)
  1108. if (isset($kpMapping[0])) {
  1109. // 数组的数组:[[kp_id: '...'], [kp_id: '...']]
  1110. $kpIds = array_column($kpMapping, 'kp_id');
  1111. } else {
  1112. // 关联数组:[kp_id: '...']
  1113. $kpIds = [$kpMapping['kp_id']];
  1114. }
  1115. }
  1116. $payload = [
  1117. 'student_id' => $studentId,
  1118. 'question_id' => $questionId,
  1119. 'paper_id' => $examId,
  1120. 'my_answer' => $question['student_answer'] ?? null,
  1121. 'correct_answer' => null, // 可以从题目表获取
  1122. 'question_text' => null, // 可以从题目表获取
  1123. 'knowledge_point' => null, // 不保存name,只保存kp_ids
  1124. 'kp_ids' => $kpIds, // 保存为数组格式
  1125. 'source' => $examId, // 来源标记使用卷子ID
  1126. 'happened_at' => now(),
  1127. ];
  1128. $result = $this->mistakeBookService->createMistake($payload);
  1129. if (($result['duplicate'] ?? false) === false) {
  1130. Log::debug('错题记录保存成功', [
  1131. 'student_id' => $studentId,
  1132. 'question_id' => $questionId,
  1133. 'mistake_id' => $result['mistake_id'] ?? null
  1134. ]);
  1135. }
  1136. } catch (\Exception $e) {
  1137. Log::warning('错题记录保存失败(不中断主流程)', [
  1138. 'student_id' => $studentId,
  1139. 'question_id' => $questionId,
  1140. 'exam_id' => $examId,
  1141. 'error' => $e->getMessage()
  1142. ]);
  1143. }
  1144. }
  1145. /**
  1146. * 保存答题记录(优化版:批量INSERT)
  1147. * @param array $examData 考试数据
  1148. * @param array $questionMappings 已批量查询的知识点映射,避免N+1
  1149. */
  1150. private function saveExamAnswerRecords(array $examData, array $questionMappings = []): void
  1151. {
  1152. $studentId = $examData['student_id'];
  1153. $examId = $examData['paper_id'];
  1154. $now = now();
  1155. // 先清理该考试的所有答题记录(支持重复提交)
  1156. try {
  1157. DB::connection('mysql')->table('student_answer_questions')
  1158. ->where('student_id', $studentId)
  1159. ->where('exam_id', $examId)
  1160. ->delete();
  1161. DB::connection('mysql')->table('student_answer_steps')
  1162. ->where('student_id', $studentId)
  1163. ->where('exam_id', $examId)
  1164. ->delete();
  1165. } catch (\Exception $e) {
  1166. Log::warning('清理旧答题记录时出错(可忽略)', [
  1167. 'student_id' => $studentId,
  1168. 'exam_id' => $examId,
  1169. 'error' => $e->getMessage(),
  1170. ]);
  1171. }
  1172. // 【优化】收集所有要插入的记录,最后批量INSERT
  1173. $stepsToInsert = [];
  1174. $questionsToInsert = [];
  1175. $mistakesToSave = []; // 收集错题记录
  1176. foreach ($examData['questions'] as $question) {
  1177. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1178. if (empty($questionId)) {
  1179. continue;
  1180. }
  1181. // 【优化】使用传入的映射,不再查询数据库
  1182. $kpMappings = $questionMappings[$questionId]['kp_mapping'] ?? [];
  1183. $isCorrectArray = $question['is_correct'] ?? [];
  1184. if (!is_array($isCorrectArray)) {
  1185. $isCorrectArray = [$isCorrectArray ? 1 : 0];
  1186. }
  1187. $stepCount = count($isCorrectArray);
  1188. if ($stepCount > 1 || !empty($kpMappings)) {
  1189. // 多步骤题目:收集步骤记录
  1190. $scorePerStep = ($question['score'] ?? 0) / max($stepCount, 1);
  1191. $hasMistake = false;
  1192. $allErrorKpCodes = [];
  1193. foreach ($isCorrectArray as $stepIndex => $isCorrect) {
  1194. $isCorrectBool = (int) $isCorrect === 1;
  1195. if (!empty($kpMappings)) {
  1196. foreach ($kpMappings as $kpMapping) {
  1197. $stepsToInsert[] = [
  1198. 'student_id' => $studentId,
  1199. 'exam_id' => $examId,
  1200. 'question_id' => $questionId,
  1201. 'step_index' => $stepIndex,
  1202. 'kp_id' => $kpMapping['kp_id'],
  1203. 'is_correct' => $isCorrectBool ? 1 : 0,
  1204. 'step_score' => $isCorrectBool ? $scorePerStep : 0,
  1205. 'created_at' => $now,
  1206. 'updated_at' => $now,
  1207. ];
  1208. if (!$isCorrectBool) {
  1209. $hasMistake = true;
  1210. $allErrorKpCodes[] = $kpMapping['kp_id'];
  1211. }
  1212. }
  1213. } else {
  1214. $stepsToInsert[] = [
  1215. 'student_id' => $studentId,
  1216. 'exam_id' => $examId,
  1217. 'question_id' => $questionId,
  1218. 'step_index' => $stepIndex,
  1219. 'kp_id' => null,
  1220. 'is_correct' => $isCorrectBool ? 1 : 0,
  1221. 'step_score' => $isCorrectBool ? $scorePerStep : 0,
  1222. 'created_at' => $now,
  1223. 'updated_at' => $now,
  1224. ];
  1225. if (!$isCorrectBool) {
  1226. $hasMistake = true;
  1227. }
  1228. }
  1229. }
  1230. // 收集错题记录
  1231. if ($hasMistake) {
  1232. $uniqueKpCodes = array_values(array_unique($allErrorKpCodes));
  1233. $mistakesToSave[] = [
  1234. 'questionId' => $questionId,
  1235. 'question' => $question,
  1236. 'kpMappings' => array_map(fn($code) => ['kp_id' => $code], $uniqueKpCodes),
  1237. ];
  1238. }
  1239. } else {
  1240. // 单步骤题目:收集题目级记录
  1241. $questionsToInsert[] = [
  1242. 'student_id' => $studentId,
  1243. 'exam_id' => $examId,
  1244. 'question_id' => $questionId,
  1245. 'score_obtained' => $question['score_obtained'] ?? 0,
  1246. 'max_score' => $question['score'] ?? 0,
  1247. 'created_at' => $now,
  1248. 'updated_at' => $now,
  1249. ];
  1250. // 收集错题记录
  1251. if (($question['score_obtained'] ?? 0) <= 0) {
  1252. $mistakesToSave[] = [
  1253. 'questionId' => $questionId,
  1254. 'question' => $question,
  1255. 'kpMappings' => !empty($kpMappings)
  1256. ? array_map(fn($m) => ['kp_id' => $m['kp_id']], $kpMappings)
  1257. : null,
  1258. ];
  1259. }
  1260. }
  1261. }
  1262. // 【优化】批量INSERT(每500条一批,避免超过MySQL限制)
  1263. try {
  1264. if (!empty($stepsToInsert)) {
  1265. foreach (array_chunk($stepsToInsert, 500) as $chunk) {
  1266. DB::connection('mysql')->table('student_answer_steps')->insert($chunk);
  1267. }
  1268. }
  1269. if (!empty($questionsToInsert)) {
  1270. foreach (array_chunk($questionsToInsert, 500) as $chunk) {
  1271. DB::connection('mysql')->table('student_answer_questions')->insert($chunk);
  1272. }
  1273. }
  1274. } catch (\Exception $e) {
  1275. Log::error('批量保存答题记录失败', [
  1276. 'student_id' => $studentId,
  1277. 'exam_id' => $examId,
  1278. 'error' => $e->getMessage(),
  1279. ]);
  1280. }
  1281. // 保存错题记录(错题本逻辑相对复杂,保持单条处理)
  1282. foreach ($mistakesToSave as $mistake) {
  1283. $this->saveMistakeRecord($studentId, $mistake['questionId'], $examId, $mistake['question'], $mistake['kpMappings']);
  1284. }
  1285. Log::info('答题记录保存完成', [
  1286. 'student_id' => $studentId,
  1287. 'exam_id' => $examId,
  1288. 'total_questions' => count($examData['questions']),
  1289. 'steps_saved' => count($stepsToInsert),
  1290. 'questions_saved' => count($questionsToInsert),
  1291. ]);
  1292. }
  1293. /**
  1294. * 保存分析结果并创建掌握度快照
  1295. */
  1296. private function saveAnalysisResult(string $studentId, string $paperId, array $result): void
  1297. {
  1298. // 【修复】支持重复分析:先删除旧的分析结果
  1299. DB::connection('mysql')->table('exam_analysis_results')
  1300. ->where('student_id', $studentId)
  1301. ->where('paper_id', $paperId)
  1302. ->delete();
  1303. // 插入新的分析结果
  1304. DB::connection('mysql')->table('exam_analysis_results')->insert([
  1305. 'student_id' => $studentId,
  1306. 'paper_id' => $paperId,
  1307. 'analysis_data' => json_encode($result),
  1308. 'created_at' => now(),
  1309. 'updated_at' => now(),
  1310. ]);
  1311. Log::info('分析结果保存完成', [
  1312. 'student_id' => $studentId,
  1313. 'paper_id' => $paperId,
  1314. 'data_size' => strlen(json_encode($result)),
  1315. ]);
  1316. // 【集成】创建知识点掌握度快照
  1317. $this->createMasterySnapshot($studentId, $paperId, $result);
  1318. // 【新增】异步生成学情分析PDF
  1319. try {
  1320. Log::info('开始异步生成学情分析PDF', [
  1321. 'student_id' => $studentId,
  1322. 'paper_id' => $paperId,
  1323. ]);
  1324. // 使用队列异步生成PDF,避免阻塞主流程
  1325. dispatch(new \App\Jobs\GenerateAnalysisPdfJob($paperId, $studentId, null));
  1326. Log::info('PDF生成任务已加入队列', [
  1327. 'student_id' => $studentId,
  1328. 'paper_id' => $paperId,
  1329. ]);
  1330. } catch (\Exception $e) {
  1331. Log::error('PDF生成任务加入队列失败', [
  1332. 'student_id' => $studentId,
  1333. 'paper_id' => $paperId,
  1334. 'error' => $e->getMessage(),
  1335. ]);
  1336. }
  1337. }
  1338. /**
  1339. * 创建知识点掌握度快照
  1340. * 【集成】使用LocalAIAnalysisService的快照功能
  1341. *
  1342. * 快照用途:
  1343. * 1. 追踪学生掌握度变化趋势
  1344. * 2. 生成学情报告时对比历史数据
  1345. * 3. 为智能出卷提供决策依据
  1346. */
  1347. private function createMasterySnapshot(string $studentId, string $paperId, array $analysisResult): void
  1348. {
  1349. try {
  1350. // 计算快照数据
  1351. $masteryVector = $analysisResult['mastery_vector'] ?? [];
  1352. $overallMastery = 0;
  1353. $weakCount = 0;
  1354. $strongCount = 0;
  1355. foreach ($masteryVector as $kpData) {
  1356. $mastery = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0;
  1357. $overallMastery += $mastery;
  1358. if ($mastery < 0.6) {
  1359. $weakCount++;
  1360. } elseif ($mastery >= 0.85) {
  1361. $strongCount++;
  1362. }
  1363. }
  1364. $kpCount = count($masteryVector);
  1365. $overallMastery = $kpCount > 0 ? round($overallMastery / $kpCount, 4) : 0;
  1366. // 生成快照ID
  1367. $snapshotId = 'snap_' . $paperId . '_' . now()->format('YmdHis');
  1368. // 保存到快照表
  1369. DB::connection('mysql')->table('knowledge_point_mastery_snapshots')->insert([
  1370. 'snapshot_id' => $snapshotId,
  1371. 'student_id' => $studentId,
  1372. 'paper_id' => $paperId,
  1373. 'answer_record_id' => null,
  1374. 'mastery_data' => json_encode($masteryVector),
  1375. 'overall_mastery' => $overallMastery,
  1376. 'weak_knowledge_points_count' => $weakCount,
  1377. 'strong_knowledge_points_count' => $strongCount,
  1378. 'snapshot_time' => now(),
  1379. 'analysis_id' => null,
  1380. 'created_at' => now(),
  1381. 'updated_at' => now(),
  1382. ]);
  1383. Log::info('掌握度快照创建成功', [
  1384. 'snapshot_id' => $snapshotId,
  1385. 'student_id' => $studentId,
  1386. 'paper_id' => $paperId,
  1387. 'overall_mastery' => $overallMastery,
  1388. 'weak_count' => $weakCount,
  1389. 'strong_count' => $strongCount,
  1390. ]);
  1391. } catch (\Exception $e) {
  1392. // 快照创建失败不影响主流程
  1393. Log::warning('掌握度快照创建失败', [
  1394. 'student_id' => $studentId,
  1395. 'paper_id' => $paperId,
  1396. 'error' => $e->getMessage(),
  1397. ]);
  1398. }
  1399. }
  1400. /**
  1401. * 判断掌握度趋势
  1402. */
  1403. /**
  1404. * 评估表现水平
  1405. */
  1406. private function evaluatePerformanceLevel(float $mastery): string
  1407. {
  1408. if ($mastery >= 0.85) {
  1409. return 'excellent';
  1410. } elseif ($mastery >= 0.70) {
  1411. return 'good';
  1412. } elseif ($mastery >= 0.50) {
  1413. return 'fair';
  1414. } else {
  1415. return 'poor';
  1416. }
  1417. }
  1418. /**
  1419. * 生成题目表现总结
  1420. */
  1421. private function generateQuestionPerformanceSummary(array $question, array $stepAnalysis): string
  1422. {
  1423. if (empty($stepAnalysis)) {
  1424. return '整题作答';
  1425. }
  1426. $correctSteps = count(array_filter($stepAnalysis, fn($s) => $s['is_correct']));
  1427. $totalSteps = count($stepAnalysis);
  1428. if ($correctSteps === $totalSteps) {
  1429. return '所有步骤正确';
  1430. } elseif ($correctSteps > 0) {
  1431. return "部分正确 ({$correctSteps}/{$totalSteps} 步骤正确)";
  1432. } else {
  1433. return '所有步骤错误';
  1434. }
  1435. }
  1436. /**
  1437. * 生成知识点建议
  1438. */
  1439. private function generateKnowledgePointRecommendation(array $data): string
  1440. {
  1441. $mastery = $data['mastery'];
  1442. if ($mastery >= 0.85) {
  1443. return '掌握良好,可安排综合练习';
  1444. } elseif ($mastery >= 0.70) {
  1445. return '基本掌握,建议加强练习';
  1446. } elseif ($mastery >= 0.50) {
  1447. return '需要重点练习,建议安排专项训练';
  1448. } else {
  1449. return '薄弱知识点,建议系统学习和大量练习';
  1450. }
  1451. }
  1452. /**
  1453. * 评估整体表现
  1454. */
  1455. private function evaluateOverallPerformance(float $averageMastery): string
  1456. {
  1457. if ($averageMastery >= 0.85) {
  1458. return '优秀';
  1459. } elseif ($averageMastery >= 0.70) {
  1460. return '良好';
  1461. } elseif ($averageMastery >= 0.50) {
  1462. return '一般';
  1463. } else {
  1464. return '需加强';
  1465. }
  1466. }
  1467. /**
  1468. * 计算推荐题目数量
  1469. */
  1470. private function calculateRecommendedQuestions(float $mastery): int
  1471. {
  1472. if ($mastery >= 0.85) {
  1473. return 1; // 巩固型:1题
  1474. } elseif ($mastery >= 0.50) {
  1475. return 2; // 修补型:2题
  1476. } else {
  1477. return 3; // 挑战型:3题
  1478. }
  1479. }
  1480. /**
  1481. * 确定重点类型
  1482. */
  1483. private function determineFocusType(float $mastery): string
  1484. {
  1485. if ($mastery >= 0.70 && $mastery < 0.85) {
  1486. return 'consolidation'; // 巩固型
  1487. } elseif ($mastery < 0.70) {
  1488. return 'remediation'; // 修补型
  1489. } else {
  1490. return 'challenge'; // 挑战型
  1491. }
  1492. }
  1493. /**
  1494. * 自动计算题目分数并补充未提交的题目
  1495. *
  1496. * 功能:
  1497. * 1. 从 paper_questions 表获取卷子的所有题目
  1498. * 2. 补充未提交的题目(is_correct 默认为 [0],表示错误)
  1499. * 3. 自动计算 score 和 score_obtained
  1500. *
  1501. * @param array $questions 用户提交的题目列表
  1502. * @param string $paperId 卷子ID
  1503. * @return array 完整的题目列表(包含未提交的题目)
  1504. */
  1505. private function autoCalculateScores(array $questions, string $paperId = ''): array
  1506. {
  1507. // 获取已提交题目的ID集合
  1508. $submittedQuestionIds = [];
  1509. foreach ($questions as $question) {
  1510. $qid = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1511. if ($qid) {
  1512. $submittedQuestionIds[$qid] = true;
  1513. }
  1514. }
  1515. // 从 paper_questions 表获取卷子的所有题目
  1516. if (!empty($paperId)) {
  1517. try {
  1518. $paperQuestions = DB::connection('mysql')
  1519. ->table('paper_questions')
  1520. ->where('paper_id', $paperId)
  1521. ->get();
  1522. foreach ($paperQuestions as $pq) {
  1523. // 优先用 question_bank_id,其次用 question_id
  1524. $questionId = $pq->question_bank_id ?? $pq->question_id ?? null;
  1525. if (empty($questionId)) {
  1526. continue;
  1527. }
  1528. // 如果该题目未提交,补充进去
  1529. if (!isset($submittedQuestionIds[$questionId])) {
  1530. $defaultScore = $pq->score ? floatval($pq->score) : 2.0;
  1531. $questions[] = [
  1532. 'question_id' => $questionId,
  1533. 'student_answer' => null,
  1534. 'is_correct' => [1], // 未提交默认为正确
  1535. 'teacher_comment' => null,
  1536. 'score' => $defaultScore,
  1537. 'score_obtained' => $defaultScore, // 正确则得满分
  1538. ];
  1539. Log::debug('补充未提交的题目', [
  1540. 'paper_id' => $paperId,
  1541. 'question_id' => $questionId,
  1542. 'default_score' => $pq->score ?? 2.0
  1543. ]);
  1544. }
  1545. }
  1546. } catch (\Exception $e) {
  1547. Log::warning('获取卷子题目列表失败', [
  1548. 'paper_id' => $paperId,
  1549. 'error' => $e->getMessage()
  1550. ]);
  1551. }
  1552. }
  1553. // 为已提交的题目计算分数
  1554. foreach ($questions as &$question) {
  1555. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? '';
  1556. // 如果用户没有提供 score,尝试从数据库获取或使用默认值
  1557. if (!isset($question['score'])) {
  1558. $question['score'] = $this->getQuestionDefaultScore($questionId);
  1559. }
  1560. // 如果用户没有提供 score_obtained,根据 is_correct 计算
  1561. if (!isset($question['score_obtained'])) {
  1562. $question['score_obtained'] = $this->calculateScoreObtained(
  1563. $question['score'] ?? 0,
  1564. $question['is_correct'] ?? []
  1565. );
  1566. }
  1567. Log::debug('自动计算分数', [
  1568. 'question_id' => $questionId,
  1569. 'default_score' => $question['score'],
  1570. 'score_obtained' => $question['score_obtained'],
  1571. 'is_correct' => $question['is_correct'] ?? []
  1572. ]);
  1573. }
  1574. return $questions;
  1575. }
  1576. /**
  1577. * 获取题目默认分数
  1578. */
  1579. private function getQuestionDefaultScore(string $questionId): float
  1580. {
  1581. if (empty($questionId)) {
  1582. return 2.0; // 默认分数
  1583. }
  1584. try {
  1585. // 尝试从题库获取题目分数
  1586. $question = DB::connection('mysql')
  1587. ->table('questions')
  1588. ->where('id', $questionId)
  1589. ->orWhere('question_code', $questionId)
  1590. ->first();
  1591. if ($question && isset($question->score)) {
  1592. return (float) $question->score;
  1593. }
  1594. // 如果没有找到,根据题目ID生成一个合理的默认分数
  1595. // 这里可以根据需要调整默认分数逻辑
  1596. return 2.0;
  1597. } catch (\Exception $e) {
  1598. Log::warning('获取题目默认分数失败,使用默认值', [
  1599. 'question_id' => $questionId,
  1600. 'error' => $e->getMessage()
  1601. ]);
  1602. return 2.0;
  1603. }
  1604. }
  1605. /**
  1606. * 根据 is_correct 数组计算得分
  1607. *
  1608. * @param float $totalScore 总分
  1609. * @param array $isCorrect 正确性数组 [0, 1, 1] 表示第1题错误,第2、3题正确
  1610. * @return float 得分
  1611. */
  1612. private function calculateScoreObtained(float $totalScore, array $isCorrect): float
  1613. {
  1614. if (empty($isCorrect)) {
  1615. return 0.0;
  1616. }
  1617. $correctCount = array_sum($isCorrect);
  1618. $totalCount = count($isCorrect);
  1619. if ($totalCount === 0) {
  1620. return 0.0;
  1621. }
  1622. // 按正确率计算得分
  1623. $scoreRatio = $correctCount / $totalCount;
  1624. return round($totalScore * $scoreRatio, 2);
  1625. }
  1626. }