ExamAnswerAnalysisService.php 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845
  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. // 【修复】确保类型正确,避免 SQL 类型转换问题
  1132. $studentId = (string) $examData['student_id'];
  1133. $examId = (string) $examData['paper_id'];
  1134. $now = now();
  1135. // 先清理该考试的所有答题记录(支持重复提交)
  1136. try {
  1137. DB::connection('mysql')->table('student_answer_questions')
  1138. ->where('student_id', '=', $studentId)
  1139. ->where('exam_id', '=', $examId)
  1140. ->delete();
  1141. DB::connection('mysql')->table('student_answer_steps')
  1142. ->where('student_id', '=', $studentId)
  1143. ->where('exam_id', '=', $examId)
  1144. ->delete();
  1145. Log::info('清理旧答题记录成功', [
  1146. 'student_id' => $studentId,
  1147. 'exam_id' => $examId,
  1148. ]);
  1149. } catch (\Exception $e) {
  1150. // 清理失败时抛出异常,避免后续插入重复数据
  1151. Log::error('清理旧答题记录失败', [
  1152. 'student_id' => $studentId,
  1153. 'exam_id' => $examId,
  1154. 'error' => $e->getMessage(),
  1155. ]);
  1156. throw $e;
  1157. }
  1158. // 【优化】收集所有要插入的记录,最后批量INSERT
  1159. $stepsToInsert = [];
  1160. $questionsToInsert = [];
  1161. $mistakesToSave = []; // 收集错题记录
  1162. foreach ($examData['questions'] as $question) {
  1163. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1164. if (empty($questionId)) {
  1165. continue;
  1166. }
  1167. // 【优化】使用传入的映射,不再查询数据库
  1168. $kpMappings = $questionMappings[$questionId]['kp_mapping'] ?? [];
  1169. $isCorrectArray = $question['is_correct'] ?? [];
  1170. if (!is_array($isCorrectArray)) {
  1171. $isCorrectArray = [$isCorrectArray ? 1 : 0];
  1172. }
  1173. $stepCount = count($isCorrectArray);
  1174. if ($stepCount > 1 || !empty($kpMappings)) {
  1175. // 多步骤题目:收集步骤记录
  1176. $scorePerStep = ($question['score'] ?? 0) / max($stepCount, 1);
  1177. $hasMistake = false;
  1178. $allErrorKpCodes = [];
  1179. foreach ($isCorrectArray as $stepIndex => $isCorrect) {
  1180. $isCorrectBool = (int) $isCorrect === 1;
  1181. if (!empty($kpMappings)) {
  1182. foreach ($kpMappings as $kpMapping) {
  1183. $stepsToInsert[] = [
  1184. 'student_id' => $studentId,
  1185. 'exam_id' => $examId,
  1186. 'question_id' => $questionId,
  1187. 'step_index' => $stepIndex,
  1188. 'kp_id' => $kpMapping['kp_id'],
  1189. 'is_correct' => $isCorrectBool ? 1 : 0,
  1190. 'step_score' => $isCorrectBool ? $scorePerStep : 0,
  1191. 'created_at' => $now,
  1192. 'updated_at' => $now,
  1193. ];
  1194. if (!$isCorrectBool) {
  1195. $hasMistake = true;
  1196. $allErrorKpCodes[] = $kpMapping['kp_id'];
  1197. }
  1198. }
  1199. } else {
  1200. $stepsToInsert[] = [
  1201. 'student_id' => $studentId,
  1202. 'exam_id' => $examId,
  1203. 'question_id' => $questionId,
  1204. 'step_index' => $stepIndex,
  1205. 'kp_id' => null,
  1206. 'is_correct' => $isCorrectBool ? 1 : 0,
  1207. 'step_score' => $isCorrectBool ? $scorePerStep : 0,
  1208. 'created_at' => $now,
  1209. 'updated_at' => $now,
  1210. ];
  1211. if (!$isCorrectBool) {
  1212. $hasMistake = true;
  1213. }
  1214. }
  1215. }
  1216. // 收集错题记录
  1217. if ($hasMistake) {
  1218. $uniqueKpCodes = array_values(array_unique($allErrorKpCodes));
  1219. $mistakesToSave[] = [
  1220. 'questionId' => $questionId,
  1221. 'question' => $question,
  1222. 'kpMappings' => array_map(fn($code) => ['kp_id' => $code], $uniqueKpCodes),
  1223. ];
  1224. }
  1225. } else {
  1226. // 单步骤题目:收集题目级记录
  1227. $questionsToInsert[] = [
  1228. 'student_id' => $studentId,
  1229. 'exam_id' => $examId,
  1230. 'question_id' => $questionId,
  1231. 'score_obtained' => $question['score_obtained'] ?? 0,
  1232. 'max_score' => $question['score'] ?? 0,
  1233. 'created_at' => $now,
  1234. 'updated_at' => $now,
  1235. ];
  1236. // 收集错题记录
  1237. if (($question['score_obtained'] ?? 0) <= 0) {
  1238. $mistakesToSave[] = [
  1239. 'questionId' => $questionId,
  1240. 'question' => $question,
  1241. 'kpMappings' => !empty($kpMappings)
  1242. ? array_map(fn($m) => ['kp_id' => $m['kp_id']], $kpMappings)
  1243. : null,
  1244. ];
  1245. }
  1246. }
  1247. }
  1248. // 【优化】批量 INSERT(每500条一批,避免超过MySQL限制)
  1249. try {
  1250. if (!empty($stepsToInsert)) {
  1251. foreach (array_chunk($stepsToInsert, 500) as $chunk) {
  1252. DB::connection('mysql')->table('student_answer_steps')->insert($chunk);
  1253. }
  1254. }
  1255. if (!empty($questionsToInsert)) {
  1256. foreach (array_chunk($questionsToInsert, 500) as $chunk) {
  1257. DB::connection('mysql')->table('student_answer_questions')->insert($chunk);
  1258. }
  1259. }
  1260. } catch (\Exception $e) {
  1261. Log::error('批量保存答题记录失败', [
  1262. 'student_id' => $studentId,
  1263. 'exam_id' => $examId,
  1264. 'error' => $e->getMessage(),
  1265. ]);
  1266. }
  1267. // 保存错题记录(错题本逻辑相对复杂,保持单条处理)
  1268. foreach ($mistakesToSave as $mistake) {
  1269. $this->saveMistakeRecord($studentId, $mistake['questionId'], $examId, $mistake['question'], $mistake['kpMappings']);
  1270. }
  1271. Log::info('答题记录保存完成', [
  1272. 'student_id' => $studentId,
  1273. 'exam_id' => $examId,
  1274. 'total_questions' => count($examData['questions']),
  1275. 'steps_saved' => count($stepsToInsert),
  1276. 'questions_saved' => count($questionsToInsert),
  1277. ]);
  1278. }
  1279. /**
  1280. * 保存分析结果并创建掌握度快照
  1281. */
  1282. private function saveAnalysisResult(string $studentId, string $paperId, array $result): void
  1283. {
  1284. // 【修复】支持重复分析:先删除旧的分析结果
  1285. DB::connection('mysql')->table('exam_analysis_results')
  1286. ->where('student_id', $studentId)
  1287. ->where('paper_id', $paperId)
  1288. ->delete();
  1289. // 插入新的分析结果
  1290. DB::connection('mysql')->table('exam_analysis_results')->insert([
  1291. 'student_id' => $studentId,
  1292. 'paper_id' => $paperId,
  1293. 'analysis_data' => json_encode($result),
  1294. 'created_at' => now(),
  1295. 'updated_at' => now(),
  1296. ]);
  1297. Log::info('分析结果保存完成', [
  1298. 'student_id' => $studentId,
  1299. 'paper_id' => $paperId,
  1300. 'data_size' => strlen(json_encode($result)),
  1301. ]);
  1302. // 【集成】创建知识点掌握度快照
  1303. $this->createMasterySnapshot($studentId, $paperId, $result);
  1304. // 【新增】异步生成学情分析PDF
  1305. try {
  1306. Log::info('开始异步生成学情分析PDF', [
  1307. 'student_id' => $studentId,
  1308. 'paper_id' => $paperId,
  1309. ]);
  1310. // 使用队列异步生成PDF,避免阻塞主流程
  1311. dispatch(new \App\Jobs\GenerateAnalysisPdfJob($paperId, $studentId, null));
  1312. Log::info('PDF生成任务已加入队列', [
  1313. 'student_id' => $studentId,
  1314. 'paper_id' => $paperId,
  1315. ]);
  1316. } catch (\Exception $e) {
  1317. Log::error('PDF生成任务加入队列失败', [
  1318. 'student_id' => $studentId,
  1319. 'paper_id' => $paperId,
  1320. 'error' => $e->getMessage(),
  1321. ]);
  1322. }
  1323. }
  1324. /**
  1325. * 创建知识点掌握度快照
  1326. * 【集成】使用LocalAIAnalysisService的快照功能
  1327. *
  1328. * 快照用途:
  1329. * 1. 追踪学生掌握度变化趋势
  1330. * 2. 生成学情报告时对比历史数据
  1331. * 3. 为智能出卷提供决策依据
  1332. */
  1333. private function createMasterySnapshot(string $studentId, string $paperId, array $analysisResult): void
  1334. {
  1335. try {
  1336. // 计算快照数据
  1337. $masteryVector = $analysisResult['mastery_vector'] ?? [];
  1338. $overallMastery = 0;
  1339. $weakCount = 0;
  1340. $strongCount = 0;
  1341. foreach ($masteryVector as $kpData) {
  1342. $mastery = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0;
  1343. $overallMastery += $mastery;
  1344. if ($mastery < 0.6) {
  1345. $weakCount++;
  1346. } elseif ($mastery >= 0.85) {
  1347. $strongCount++;
  1348. }
  1349. }
  1350. $kpCount = count($masteryVector);
  1351. $overallMastery = $kpCount > 0 ? round($overallMastery / $kpCount, 4) : 0;
  1352. // 生成快照ID
  1353. $snapshotId = 'snap_' . $paperId . '_' . now()->format('YmdHis');
  1354. // 保存到快照表
  1355. DB::connection('mysql')->table('knowledge_point_mastery_snapshots')->insert([
  1356. 'snapshot_id' => $snapshotId,
  1357. 'student_id' => $studentId,
  1358. 'paper_id' => $paperId,
  1359. 'answer_record_id' => null,
  1360. 'mastery_data' => json_encode($masteryVector),
  1361. 'overall_mastery' => $overallMastery,
  1362. 'weak_knowledge_points_count' => $weakCount,
  1363. 'strong_knowledge_points_count' => $strongCount,
  1364. 'snapshot_time' => now(),
  1365. 'analysis_id' => null,
  1366. 'created_at' => now(),
  1367. 'updated_at' => now(),
  1368. ]);
  1369. Log::info('掌握度快照创建成功', [
  1370. 'snapshot_id' => $snapshotId,
  1371. 'student_id' => $studentId,
  1372. 'paper_id' => $paperId,
  1373. 'overall_mastery' => $overallMastery,
  1374. 'weak_count' => $weakCount,
  1375. 'strong_count' => $strongCount,
  1376. ]);
  1377. } catch (\Exception $e) {
  1378. // 快照创建失败不影响主流程
  1379. Log::warning('掌握度快照创建失败', [
  1380. 'student_id' => $studentId,
  1381. 'paper_id' => $paperId,
  1382. 'error' => $e->getMessage(),
  1383. ]);
  1384. }
  1385. }
  1386. /**
  1387. * 判断掌握度趋势
  1388. */
  1389. /**
  1390. * 评估表现水平
  1391. */
  1392. private function evaluatePerformanceLevel(float $mastery): string
  1393. {
  1394. if ($mastery >= 0.85) {
  1395. return 'excellent';
  1396. } elseif ($mastery >= 0.70) {
  1397. return 'good';
  1398. } elseif ($mastery >= 0.50) {
  1399. return 'fair';
  1400. } else {
  1401. return 'poor';
  1402. }
  1403. }
  1404. /**
  1405. * 生成题目表现总结
  1406. */
  1407. private function generateQuestionPerformanceSummary(array $question, array $stepAnalysis): string
  1408. {
  1409. if (empty($stepAnalysis)) {
  1410. return '整题作答';
  1411. }
  1412. $correctSteps = count(array_filter($stepAnalysis, fn($s) => $s['is_correct']));
  1413. $totalSteps = count($stepAnalysis);
  1414. if ($correctSteps === $totalSteps) {
  1415. return '所有步骤正确';
  1416. } elseif ($correctSteps > 0) {
  1417. return "部分正确 ({$correctSteps}/{$totalSteps} 步骤正确)";
  1418. } else {
  1419. return '所有步骤错误';
  1420. }
  1421. }
  1422. /**
  1423. * 生成知识点建议
  1424. */
  1425. private function generateKnowledgePointRecommendation(array $data): string
  1426. {
  1427. $mastery = $data['mastery'];
  1428. if ($mastery >= 0.85) {
  1429. return '掌握良好,可安排综合练习';
  1430. } elseif ($mastery >= 0.70) {
  1431. return '基本掌握,建议加强练习';
  1432. } elseif ($mastery >= 0.50) {
  1433. return '需要重点练习,建议安排专项训练';
  1434. } else {
  1435. return '薄弱知识点,建议系统学习和大量练习';
  1436. }
  1437. }
  1438. /**
  1439. * 评估整体表现
  1440. */
  1441. private function evaluateOverallPerformance(float $averageMastery): string
  1442. {
  1443. if ($averageMastery >= 0.85) {
  1444. return '优秀';
  1445. } elseif ($averageMastery >= 0.70) {
  1446. return '良好';
  1447. } elseif ($averageMastery >= 0.50) {
  1448. return '一般';
  1449. } else {
  1450. return '需加强';
  1451. }
  1452. }
  1453. /**
  1454. * 计算推荐题目数量
  1455. */
  1456. private function calculateRecommendedQuestions(float $mastery): int
  1457. {
  1458. if ($mastery >= 0.85) {
  1459. return 1; // 巩固型:1题
  1460. } elseif ($mastery >= 0.50) {
  1461. return 2; // 修补型:2题
  1462. } else {
  1463. return 3; // 挑战型:3题
  1464. }
  1465. }
  1466. /**
  1467. * 确定重点类型
  1468. */
  1469. private function determineFocusType(float $mastery): string
  1470. {
  1471. if ($mastery >= 0.70 && $mastery < 0.85) {
  1472. return 'consolidation'; // 巩固型
  1473. } elseif ($mastery < 0.70) {
  1474. return 'remediation'; // 修补型
  1475. } else {
  1476. return 'challenge'; // 挑战型
  1477. }
  1478. }
  1479. /**
  1480. * 自动计算题目分数并补充未提交的题目
  1481. *
  1482. * 功能:
  1483. * 1. 从 paper_questions 表获取卷子的所有题目
  1484. * 2. 补充未提交的题目(is_correct 默认为 [0],表示错误)
  1485. * 3. 自动计算 score 和 score_obtained
  1486. *
  1487. * @param array $questions 用户提交的题目列表
  1488. * @param string $paperId 卷子ID
  1489. * @return array 完整的题目列表(包含未提交的题目)
  1490. */
  1491. private function autoCalculateScores(array $questions, string $paperId = ''): array
  1492. {
  1493. // 获取已提交题目的ID集合
  1494. $submittedQuestionIds = [];
  1495. foreach ($questions as $question) {
  1496. $qid = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1497. if ($qid) {
  1498. $submittedQuestionIds[$qid] = true;
  1499. }
  1500. }
  1501. // 从 paper_questions 表获取卷子的所有题目
  1502. if (!empty($paperId)) {
  1503. try {
  1504. $paperQuestions = DB::connection('mysql')
  1505. ->table('paper_questions')
  1506. ->where('paper_id', $paperId)
  1507. ->get();
  1508. foreach ($paperQuestions as $pq) {
  1509. // 优先用 question_bank_id,其次用 question_id
  1510. $questionId = $pq->question_bank_id ?? $pq->question_id ?? null;
  1511. if (empty($questionId)) {
  1512. continue;
  1513. }
  1514. // 如果该题目未提交,补充进去
  1515. if (!isset($submittedQuestionIds[$questionId])) {
  1516. $defaultScore = $pq->score ? floatval($pq->score) : 2.0;
  1517. $questions[] = [
  1518. 'question_id' => $questionId,
  1519. 'student_answer' => null,
  1520. 'is_correct' => [1], // 未提交默认为正确
  1521. 'teacher_comment' => null,
  1522. 'score' => $defaultScore,
  1523. 'score_obtained' => $defaultScore, // 正确则得满分
  1524. ];
  1525. Log::debug('补充未提交的题目', [
  1526. 'paper_id' => $paperId,
  1527. 'question_id' => $questionId,
  1528. 'default_score' => $pq->score ?? 2.0
  1529. ]);
  1530. }
  1531. }
  1532. } catch (\Exception $e) {
  1533. Log::warning('获取卷子题目列表失败', [
  1534. 'paper_id' => $paperId,
  1535. 'error' => $e->getMessage()
  1536. ]);
  1537. }
  1538. }
  1539. // 为已提交的题目计算分数
  1540. foreach ($questions as &$question) {
  1541. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? '';
  1542. // 如果用户没有提供 score,尝试从数据库获取或使用默认值
  1543. if (!isset($question['score'])) {
  1544. $question['score'] = $this->getQuestionDefaultScore($questionId);
  1545. }
  1546. // 如果用户没有提供 score_obtained,根据 is_correct 计算
  1547. if (!isset($question['score_obtained'])) {
  1548. $question['score_obtained'] = $this->calculateScoreObtained(
  1549. $question['score'] ?? 0,
  1550. $question['is_correct'] ?? []
  1551. );
  1552. }
  1553. Log::debug('自动计算分数', [
  1554. 'question_id' => $questionId,
  1555. 'default_score' => $question['score'],
  1556. 'score_obtained' => $question['score_obtained'],
  1557. 'is_correct' => $question['is_correct'] ?? []
  1558. ]);
  1559. }
  1560. return $questions;
  1561. }
  1562. /**
  1563. * 获取题目默认分数
  1564. */
  1565. private function getQuestionDefaultScore(string $questionId): float
  1566. {
  1567. if (empty($questionId)) {
  1568. return 2.0; // 默认分数
  1569. }
  1570. try {
  1571. // 尝试从题库获取题目分数
  1572. $question = DB::connection('mysql')
  1573. ->table('questions')
  1574. ->where('id', $questionId)
  1575. ->orWhere('question_code', $questionId)
  1576. ->first();
  1577. if ($question && isset($question->score)) {
  1578. return (float) $question->score;
  1579. }
  1580. // 如果没有找到,根据题目ID生成一个合理的默认分数
  1581. // 这里可以根据需要调整默认分数逻辑
  1582. return 2.0;
  1583. } catch (\Exception $e) {
  1584. Log::warning('获取题目默认分数失败,使用默认值', [
  1585. 'question_id' => $questionId,
  1586. 'error' => $e->getMessage()
  1587. ]);
  1588. return 2.0;
  1589. }
  1590. }
  1591. /**
  1592. * 根据 is_correct 数组计算得分
  1593. *
  1594. * @param float $totalScore 总分
  1595. * @param array $isCorrect 正确性数组 [0, 1, 1] 表示第1题错误,第2、3题正确
  1596. * @return float 得分
  1597. */
  1598. private function calculateScoreObtained(float $totalScore, array $isCorrect): float
  1599. {
  1600. if (empty($isCorrect)) {
  1601. return 0.0;
  1602. }
  1603. $correctCount = array_sum($isCorrect);
  1604. $totalCount = count($isCorrect);
  1605. if ($totalCount === 0) {
  1606. return 0.0;
  1607. }
  1608. // 按正确率计算得分
  1609. $scoreRatio = $correctCount / $totalCount;
  1610. return round($totalScore * $scoreRatio, 2);
  1611. }
  1612. }