ExamPdfExportService.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. <?php
  2. namespace App\Services;
  3. use App\DTO\ExamAnalysisDataDto;
  4. use App\DTO\ReportPayloadDto;
  5. use App\Models\Paper;
  6. use App\Models\PaperQuestion;
  7. use App\Models\Student;
  8. use Illuminate\Http\Request;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\File;
  11. use Illuminate\Support\Facades\Http;
  12. use Illuminate\Support\Facades\Log;
  13. use Illuminate\Support\Facades\Storage;
  14. use Illuminate\Support\Facades\URL;
  15. use Symfony\Component\Process\Exception\ProcessSignaledException;
  16. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  17. use Symfony\Component\Process\Process;
  18. /**
  19. * PDF导出服务(重构版)
  20. * 负责生成试卷PDF、判卷PDF和学情报告PDF
  21. */
  22. class ExamPdfExportService
  23. {
  24. public function __construct(
  25. private readonly LearningAnalyticsService $learningAnalyticsService,
  26. private readonly QuestionBankService $questionBankService,
  27. private readonly QuestionServiceApi $questionServiceApi,
  28. private readonly PdfStorageService $pdfStorageService,
  29. private readonly MasteryCalculator $masteryCalculator
  30. ) {}
  31. /**
  32. * 生成试卷 PDF(不含答案)
  33. */
  34. public function generateExamPdf(string $paperId): ?string
  35. {
  36. Log::info('generateExamPdf 开始:', ['paper_id' => $paperId]);
  37. $url = $this->renderAndStoreExamPdf($paperId, includeAnswer: false, suffix: 'exam');
  38. Log::info('generateExamPdf url 生成结果:', ['paper_id' => $paperId, 'url' => $url]);
  39. // 如果生成成功,将 URL 写入数据库
  40. if ($url) {
  41. $this->savePdfUrlToDatabase($paperId, 'exam_pdf_url', $url);
  42. }
  43. return $url;
  44. }
  45. /**
  46. * 生成判卷 PDF(含答案与解析)
  47. */
  48. public function generateGradingPdf(string $paperId): ?string
  49. {
  50. Log::info('generateGradingPdf 开始:', ['paper_id' => $paperId]);
  51. $url = $this->renderAndStoreExamPdf($paperId, includeAnswer: true, suffix: 'grading', useGradingView: true);
  52. Log::info('generateGradingPdf url 生成结果:', ['paper_id' => $paperId, 'url' => $url]);
  53. // 如果生成成功,将 URL 写入数据库
  54. if ($url) {
  55. $this->savePdfUrlToDatabase($paperId, 'grading_pdf_url', $url);
  56. }
  57. return $url;
  58. }
  59. /**
  60. * 生成学情分析 PDF
  61. */
  62. public function generateAnalysisReportPdf(string $paperId, string $studentId, ?string $recordId = null): ?string
  63. {
  64. if (function_exists('set_time_limit')) {
  65. @set_time_limit(240);
  66. }
  67. try {
  68. // 【调试】打印输入参数
  69. Log::info('ExamPdfExportService: 开始生成学情分析PDF', [
  70. 'paper_id' => $paperId,
  71. 'student_id' => $studentId,
  72. 'record_id' => $recordId,
  73. ]);
  74. // 构建分析数据
  75. $analysisData = $this->buildAnalysisData($paperId, $studentId);
  76. if (!$analysisData) {
  77. Log::warning('ExamPdfExportService: buildAnalysisData返回空数据', [
  78. 'paper_id' => $paperId,
  79. 'student_id' => $studentId,
  80. ]);
  81. return null;
  82. }
  83. Log::info('ExamPdfExportService: buildAnalysisData返回数据', [
  84. 'paper_id' => $paperId,
  85. 'student_id' => $studentId,
  86. 'analysisData_keys' => array_keys($analysisData),
  87. 'mastery_count' => count($analysisData['mastery']['items'] ?? []),
  88. 'questions_count' => count($analysisData['questions'] ?? []),
  89. ]);
  90. // 创建DTO
  91. $dto = ExamAnalysisDataDto::fromArray($analysisData);
  92. $payloadDto = ReportPayloadDto::fromExamAnalysisDataDto($dto);
  93. // 【调试】打印传给模板的数据
  94. $templateData = $payloadDto->toArray();
  95. Log::info('ExamPdfExportService: 传给模板的数据', [
  96. 'paper' => $templateData['paper'] ?? null,
  97. 'student' => $templateData['student'] ?? null,
  98. 'mastery' => $templateData['mastery'] ?? null,
  99. 'parent_mastery_levels' => $templateData['parent_mastery_levels'] ?? null, // 新增:检查父节点掌握度
  100. 'questions_count' => count($templateData['questions'] ?? []),
  101. 'insights_count' => count($templateData['question_insights'] ?? []),
  102. 'recommendations_count' => count($templateData['recommendations'] ?? []),
  103. ]);
  104. // 渲染HTML
  105. $html = view('exam-analysis.pdf-report', $templateData)->render();
  106. if (!$html) {
  107. Log::error('ExamPdfExportService: 渲染HTML为空', ['paper_id' => $paperId]);
  108. return null;
  109. }
  110. // 生成PDF
  111. $pdfBinary = $this->buildPdf($html);
  112. if (!$pdfBinary) {
  113. return null;
  114. }
  115. // 保存PDF
  116. $version = time();
  117. $path = "analysis_reports/{$paperId}_{$studentId}_{$version}.pdf";
  118. $url = $this->pdfStorageService->put($path, $pdfBinary);
  119. if (!$url) {
  120. Log::error('ExamPdfExportService: 保存学情PDF失败', ['path' => $path]);
  121. return null;
  122. }
  123. // 保存URL到数据库
  124. $this->saveAnalysisPdfUrl($paperId, $studentId, $recordId, $url);
  125. return $url;
  126. } catch (\Throwable $e) {
  127. Log::error('ExamPdfExportService: 生成学情分析PDF失败', [
  128. 'paper_id' => $paperId,
  129. 'student_id' => $studentId,
  130. 'record_id' => $recordId,
  131. 'error' => $e->getMessage(),
  132. 'exception' => get_class($e),
  133. 'trace' => $e->getTraceAsString(),
  134. ]);
  135. return null;
  136. }
  137. }
  138. /**
  139. * 渲染并存储试卷PDF
  140. */
  141. private function renderAndStoreExamPdf(
  142. string $paperId,
  143. bool $includeAnswer,
  144. string $suffix,
  145. bool $useGradingView = false
  146. ): ?string {
  147. // 放宽脚本执行时间
  148. if (function_exists('set_time_limit')) {
  149. @set_time_limit(240);
  150. }
  151. try {
  152. $html = $this->renderExamHtml($paperId, $includeAnswer, $useGradingView);
  153. if (!$html) {
  154. Log::error('ExamPdfExportService: 渲染HTML为空', [
  155. 'paper_id' => $paperId,
  156. 'include_answer' => $includeAnswer,
  157. 'use_grading_view' => $useGradingView,
  158. ]);
  159. return null;
  160. }
  161. $pdfBinary = $this->buildPdf($html);
  162. if (!$pdfBinary) {
  163. Log::error('ExamPdfExportService: buildPdf为空', [
  164. 'paper_id' => $paperId,
  165. 'include_answer' => $includeAnswer,
  166. 'use_grading_view' => $useGradingView,
  167. ]);
  168. return null;
  169. }
  170. $path = "exams/{$paperId}_{$suffix}.pdf";
  171. $url = $this->pdfStorageService->put($path, $pdfBinary);
  172. if (!$url) {
  173. Log::error('ExamPdfExportService: 保存PDF失败', ['path' => $path]);
  174. return null;
  175. }
  176. return $url;
  177. } catch (\Throwable $e) {
  178. Log::error('ExamPdfExportService: 生成PDF失败', [
  179. 'paper_id' => $paperId,
  180. 'suffix' => $suffix,
  181. 'error' => $e->getMessage(),
  182. 'exception' => get_class($e),
  183. 'trace' => $e->getTraceAsString(),
  184. ]);
  185. return null;
  186. }
  187. }
  188. /**
  189. * 渲染试卷HTML(重构版)
  190. */
  191. private function renderExamHtml(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
  192. {
  193. // 直接构造请求URL,使用路由生成HTML
  194. $routeName = $useGradingView
  195. ? 'filament.admin.auth.intelligent-exam.grading'
  196. : 'filament.admin.auth.intelligent-exam.pdf';
  197. $url = route($routeName, ['paper_id' => $paperId, 'answer' => $includeAnswer ? 'true' : 'false']);
  198. // 使用HTTP客户端获取渲染后的HTML
  199. try {
  200. $response = Http::get($url);
  201. if ($response->successful()) {
  202. $html = $response->body();
  203. if (!empty(trim($html))) {
  204. return $this->ensureUtf8Html($html);
  205. } else {
  206. Log::warning('ExamPdfExportService: HTTP返回的HTML为空,使用备用方案', [
  207. 'paper_id' => $paperId,
  208. 'url' => $url,
  209. ]);
  210. }
  211. }
  212. } catch (\Exception $e) {
  213. Log::warning('ExamPdfExportService: 通过HTTP获取HTML失败,使用备用方案', [
  214. 'paper_id' => $paperId,
  215. 'error' => $e->getMessage(),
  216. ]);
  217. }
  218. // 备用方案:直接渲染视图(如果路由不可用)
  219. try {
  220. $paper = Paper::with('questions')->find($paperId);
  221. if (!$paper) {
  222. Log::error('ExamPdfExportService: 试卷不存在,备用方案无法渲染', [
  223. 'paper_id' => $paperId,
  224. 'include_answer' => $includeAnswer,
  225. 'use_grading_view' => $useGradingView,
  226. ]);
  227. return null;
  228. }
  229. // 检查试卷是否有题目
  230. if ($paper->questions->isEmpty()) {
  231. Log::error('ExamPdfExportService: 试卷没有题目数据', [
  232. 'paper_id' => $paperId,
  233. 'question_count' => 0,
  234. ]);
  235. return null;
  236. }
  237. $viewName = $useGradingView ? 'exam-pdf.grading' : 'exam-pdf.student';
  238. $html = view($viewName, compact('paper'))->render();
  239. if (empty(trim($html))) {
  240. Log::error('ExamPdfExportService: 视图渲染结果为空', [
  241. 'paper_id' => $paperId,
  242. 'view_name' => $viewName,
  243. 'question_count' => $paper->questions->count(),
  244. ]);
  245. return null;
  246. }
  247. return $this->ensureUtf8Html($html);
  248. } catch (\Exception $e) {
  249. Log::error('ExamPdfExportService: 备用方案渲染失败', [
  250. 'paper_id' => $paperId,
  251. 'error' => $e->getMessage(),
  252. 'trace' => $e->getTraceAsString(),
  253. ]);
  254. return null;
  255. }
  256. }
  257. /**
  258. * 构建分析数据(重构版)
  259. * 优先使用本地MySQL数据,减少API依赖
  260. */
  261. private function buildAnalysisData(string $paperId, string $studentId): ?array
  262. {
  263. // 【关键调试】确认方法被调用
  264. Log::warning('ExamPdfExportService: buildAnalysisData方法被调用了!', [
  265. 'paper_id' => $paperId,
  266. 'student_id' => $studentId,
  267. 'timestamp' => now()->toISOString()
  268. ]);
  269. $paper = Paper::with(['questions' => function ($query) {
  270. $query->orderBy('question_number')->orderBy('id');
  271. }])->find($paperId);
  272. if (!$paper) {
  273. Log::warning('ExamPdfExportService: 未找到试卷,将尝试仅基于分析数据生成PDF', [
  274. 'paper_id' => $paperId,
  275. 'student_id' => $studentId,
  276. ]);
  277. // 【修复】即使试卷不存在,也尝试基于分析数据生成PDF
  278. $paper = new \stdClass();
  279. $paper->paper_id = $paperId;
  280. $paper->paper_name = "学情分析报告_{$studentId}_{$paperId}";
  281. $paper->question_count = 0;
  282. $paper->total_score = 0;
  283. $paper->created_at = now();
  284. $paper->questions = collect();
  285. }
  286. $student = Student::find($studentId);
  287. $studentInfo = [
  288. 'id' => $student?->student_id ?? $studentId,
  289. 'name' => $student?->name ?? $studentId,
  290. 'grade' => $student?->grade ?? '未知年级',
  291. 'class' => $student?->class_name ?? '未知班级',
  292. ];
  293. // 【修改】直接从本地数据库获取分析数据(不再调用API)
  294. $analysisData = [];
  295. // 首先尝试从paper->analysis_id获取
  296. if (!empty($paper->analysis_id)) {
  297. Log::info('ExamPdfExportService: 从本地数据库获取试卷分析数据', [
  298. 'paper_id' => $paperId,
  299. 'student_id' => $studentId,
  300. 'analysis_id' => $paper->analysis_id
  301. ]);
  302. $analysisRecord = \DB::table('exam_analysis_results')
  303. ->where('id', $paper->analysis_id)
  304. ->where('student_id', $studentId)
  305. ->first();
  306. if ($analysisRecord && !empty($analysisRecord->analysis_data)) {
  307. $analysisData = json_decode($analysisRecord->analysis_data, true);
  308. Log::info('ExamPdfExportService: 成功获取本地分析数据(通过analysis_id)', [
  309. 'data_size' => strlen($analysisRecord->analysis_data)
  310. ]);
  311. } else {
  312. Log::warning('ExamPdfExportService: 未找到本地分析数据,将尝试其他方式', [
  313. 'paper_id' => $paperId,
  314. 'student_id' => $studentId,
  315. 'analysis_id' => $paper->analysis_id
  316. ]);
  317. }
  318. }
  319. // 如果没有analysis_id或未找到数据,直接从exam_analysis_results表查询
  320. if (empty($analysisData)) {
  321. Log::info('ExamPdfExportService: 直接从exam_analysis_results表查询分析数据', [
  322. 'paper_id' => $paperId,
  323. 'student_id' => $studentId
  324. ]);
  325. $analysisRecord = \DB::table('exam_analysis_results')
  326. ->where('paper_id', $paperId)
  327. ->where('student_id', $studentId)
  328. ->first();
  329. if ($analysisRecord && !empty($analysisRecord->analysis_data)) {
  330. $analysisData = json_decode($analysisRecord->analysis_data, true);
  331. Log::info('ExamPdfExportService: 成功获取本地分析数据(直接查询)', [
  332. 'data_size' => strlen($analysisRecord->analysis_data),
  333. 'question_count' => count($analysisData['question_analysis'] ?? [])
  334. ]);
  335. } else {
  336. Log::warning('ExamPdfExportService: 未找到任何分析数据,将使用空数据', [
  337. 'paper_id' => $paperId,
  338. 'student_id' => $studentId
  339. ]);
  340. }
  341. }
  342. // 【修复】优先使用analysisData中的knowledge_point_analysis数据
  343. $masteryData = [];
  344. $parentMasteryLevels = []; // 新增:父节点掌握度数据
  345. Log::info('ExamPdfExportService: 开始处理掌握度数据', [
  346. 'student_id' => $studentId,
  347. 'analysisData_keys' => array_keys($analysisData),
  348. 'has_knowledge_point_analysis' => !empty($analysisData['knowledge_point_analysis']),
  349. ]);
  350. if (!empty($analysisData['knowledge_point_analysis'])) {
  351. // 将knowledge_point_analysis转换为buildMasterySummary期望的格式
  352. foreach ($analysisData['knowledge_point_analysis'] as $kp) {
  353. $masteryData[] = [
  354. 'kp_code' => $kp['kp_id'] ?? null,
  355. 'kp_name' => $kp['kp_id'] ?? '未知知识点',
  356. 'mastery_level' => $kp['mastery_level'] ?? 0,
  357. 'mastery_change' => $kp['change'] ?? null,
  358. ];
  359. }
  360. // 【修复】基于所有兄弟节点历史数据计算父节点掌握度,并获取掌握度变化
  361. try {
  362. // 获取本次考试涉及的知识点代码列表
  363. $examKpCodes = array_column($masteryData, 'kp_code');
  364. Log::info('ExamPdfExportService: 本次考试涉及的知识点', [
  365. 'count' => count($examKpCodes),
  366. 'kp_codes' => $examKpCodes
  367. ]);
  368. // 获取上一个快照的数据(用于计算变化)
  369. // 如果没有其他试卷的记录,使用同一试卷的上一次快照
  370. $lastSnapshot = DB::connection('mysql')
  371. ->table('knowledge_point_mastery_snapshots')
  372. ->where('student_id', $studentId)
  373. ->where('paper_id', $paper->paper_id)
  374. ->where('snapshot_id', '!=', "snap_{$paper->paper_id}_" . date('YmdHis'))
  375. ->latest('snapshot_time')
  376. ->first();
  377. $previousMasteryData = [];
  378. if ($lastSnapshot) {
  379. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  380. foreach ($previousMasteryJson as $kpCode => $data) {
  381. $previousMasteryData[$kpCode] = [
  382. 'current_mastery' => $data['current_mastery'] ?? 0,
  383. 'previous_mastery' => $data['previous_mastery'] ?? null,
  384. ];
  385. }
  386. Log::info('ExamPdfExportService: 获取到上一次快照数据', [
  387. 'snapshot_time' => $lastSnapshot->snapshot_time,
  388. 'kp_count' => count($previousMasteryData)
  389. ]);
  390. }
  391. // 为当前知识点添加变化数据
  392. foreach ($masteryData as &$item) {
  393. $kpCode = $item['kp_code'];
  394. if (isset($previousMasteryData[$kpCode])) {
  395. $previous = floatval($previousMasteryData[$kpCode]['previous_mastery'] ?? 0);
  396. $current = floatval($item['mastery_level']);
  397. $item['mastery_change'] = $current - $previous;
  398. }
  399. }
  400. unset($item); // 解除引用
  401. // 获取所有父节点掌握度
  402. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  403. $allParentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? [];
  404. // 计算与本次考试相关的父节点掌握度(基于所有兄弟节点)
  405. $parentMasteryLevels = [];
  406. // 【修复】使用数据库查询正确匹配父子关系,而不是字符串前缀
  407. foreach ($allParentMasteryLevels as $parentKpCode => $parentMastery) {
  408. // 查询这个父节点的所有子节点
  409. $childNodes = DB::connection('mysql')
  410. ->table('knowledge_points')
  411. ->where('parent_kp_code', $parentKpCode)
  412. ->pluck('kp_code')
  413. ->toArray();
  414. // 检查是否有子节点在本次考试中出现
  415. $relevantChildren = array_intersect($examKpCodes, $childNodes);
  416. if (!empty($relevantChildren)) {
  417. // 【修复】计算父节点变化:基于所有子节点的平均变化
  418. $childChanges = [];
  419. foreach ($relevantChildren as $childKpCode) {
  420. $previousChild = $previousMasteryData[$childKpCode]['previous_mastery'] ?? null;
  421. $currentChild = null;
  422. foreach ($masteryData as $item) {
  423. if ($item['kp_code'] === $childKpCode) {
  424. $currentChild = $item['mastery_level'];
  425. break;
  426. }
  427. }
  428. if ($previousChild !== null && $currentChild !== null) {
  429. $childChanges[] = floatval($currentChild) - floatval($previousChild);
  430. }
  431. }
  432. $avgChange = !empty($childChanges) ? array_sum($childChanges) / count($childChanges) : null;
  433. // 获取父节点中文名称
  434. $parentKpInfo = DB::connection('mysql')
  435. ->table('knowledge_points')
  436. ->where('kp_code', $parentKpCode)
  437. ->first();
  438. $parentMasteryLevels[$parentKpCode] = [
  439. 'kp_code' => $parentKpCode,
  440. 'kp_name' => $parentKpInfo->name ?? $parentKpCode,
  441. 'mastery_level' => $parentMastery,
  442. 'mastery_percentage' => round($parentMastery * 100, 1),
  443. 'mastery_change' => $avgChange,
  444. 'children' => $relevantChildren,
  445. ];
  446. }
  447. }
  448. Log::info('ExamPdfExportService: 过滤后的父节点掌握度', [
  449. 'all_parent_count' => count($allParentMasteryLevels),
  450. 'filtered_parent_count' => count($parentMasteryLevels),
  451. 'filtered_codes' => array_keys($parentMasteryLevels)
  452. ]);
  453. } catch (\Exception $e) {
  454. Log::warning('ExamPdfExportService: 获取父节点掌握度失败', [
  455. 'error' => $e->getMessage()
  456. ]);
  457. }
  458. Log::info('ExamPdfExportService: 使用analysisData中的掌握度数据', [
  459. 'count' => count($masteryData),
  460. 'masteryData_sample' => !empty($masteryData) ? array_slice($masteryData, 0, 2) : []
  461. ]);
  462. } else {
  463. // 如果没有knowledge_point_analysis,使用MasteryCalculator获取多层级掌握度概览
  464. try {
  465. Log::info('ExamPdfExportService: 获取学生多层级掌握度概览', [
  466. 'student_id' => $studentId
  467. ]);
  468. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  469. $masteryData = $masteryOverview['details'] ?? [];
  470. $parentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? []; // 获取父节点掌握度
  471. // 【修复】将对象数组转换为关联数组(避免 stdClass 对象访问错误)
  472. if (!empty($masteryData) && is_array($masteryData)) {
  473. $masteryData = array_map(function($item) {
  474. if (is_object($item)) {
  475. return [
  476. 'kp_code' => $item->kp_code ?? null,
  477. 'kp_name' => $item->kp_name ?? null,
  478. 'mastery_level' => floatval($item->mastery_level ?? 0),
  479. 'mastery_change' => $item->mastery_change !== null ? floatval($item->mastery_change) : null,
  480. ];
  481. }
  482. return $item;
  483. }, $masteryData);
  484. }
  485. // 【修复】获取快照数据以计算掌握度变化
  486. $lastSnapshot = DB::connection('mysql')
  487. ->table('knowledge_point_mastery_snapshots')
  488. ->where('student_id', $studentId)
  489. ->latest('snapshot_time')
  490. ->first();
  491. if ($lastSnapshot) {
  492. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  493. foreach ($masteryData as &$item) {
  494. $kpCode = $item['kp_code'];
  495. if (isset($previousMasteryJson[$kpCode])) {
  496. $previous = floatval($previousMasteryJson[$kpCode]['previous_mastery'] ?? 0);
  497. $current = floatval($item['mastery_level']);
  498. $item['mastery_change'] = $current - $previous;
  499. }
  500. }
  501. unset($item);
  502. }
  503. Log::info('ExamPdfExportService: 成功获取多层级掌握度数据', [
  504. 'count' => count($masteryData),
  505. 'parent_count' => count($parentMasteryLevels)
  506. ]);
  507. } catch (\Exception $e) {
  508. Log::error('ExamPdfExportService: 获取掌握度数据失败', [
  509. 'student_id' => $studentId,
  510. 'error' => $e->getMessage()
  511. ]);
  512. }
  513. }
  514. // 【修改】使用本地方法获取学习路径推荐(替代API调用)
  515. $recommendations = [];
  516. try {
  517. Log::info('ExamPdfExportService: 获取学习路径推荐', [
  518. 'student_id' => $studentId
  519. ]);
  520. $learningPaths = $this->learningAnalyticsService->recommendLearningPaths($studentId, 3);
  521. $recommendations = $learningPaths['recommendations'] ?? [];
  522. Log::info('ExamPdfExportService: 成功获取学习路径推荐', [
  523. 'count' => count($recommendations)
  524. ]);
  525. } catch (\Exception $e) {
  526. Log::error('ExamPdfExportService: 获取学习路径推荐失败', [
  527. 'student_id' => $studentId,
  528. 'error' => $e->getMessage()
  529. ]);
  530. }
  531. // 获取知识点名称映射
  532. $kpNameMap = $this->buildKnowledgePointNameMap();
  533. Log::info('ExamPdfExportService: 获取知识点名称映射', [
  534. 'kpNameMap_count' => count($kpNameMap),
  535. 'kpNameMap_keys_sample' => !empty($kpNameMap) ? array_slice(array_keys($kpNameMap), 0, 5) : []
  536. ]);
  537. // 【修复】直接从MySQL数据库获取题目详情(不通过API)
  538. $questionDetails = $this->getQuestionDetailsFromMySQL($paper);
  539. // 处理题目数据
  540. $questions = $this->processQuestionsForReport($paper, $questionDetails, $kpNameMap);
  541. // 【关键调试】查看buildMasterySummary的返回结果
  542. $masterySummary = $this->buildMasterySummary($masteryData, $kpNameMap);
  543. Log::info('ExamPdfExportService: buildMasterySummary返回结果', [
  544. 'masteryData_count' => count($masteryData),
  545. 'kpNameMap_count' => count($kpNameMap),
  546. 'masterySummary_keys' => array_keys($masterySummary),
  547. 'masterySummary_items_count' => count($masterySummary['items'] ?? []),
  548. 'masterySummary_items_sample' => !empty($masterySummary['items']) ? array_slice($masterySummary['items'], 0, 2) : []
  549. ]);
  550. // 【修复】处理父节点掌握度数据:过滤零值、转换名称、构建层级关系
  551. $examKpCodes = array_column($masteryData, 'kp_code'); // 本次考试涉及的知识点
  552. $processedParentMastery = $this->processParentMasteryLevels($parentMasteryLevels, $kpNameMap, $examKpCodes);
  553. Log::info('ExamPdfExportService: 处理后的父节点掌握度', [
  554. 'raw_count' => count($parentMasteryLevels),
  555. 'processed_count' => count($processedParentMastery),
  556. 'processed_sample' => !empty($processedParentMastery) ? array_slice($processedParentMastery, 0, 3) : []
  557. ]);
  558. return [
  559. 'paper' => [
  560. 'id' => $paper->paper_id,
  561. 'name' => $paper->paper_name,
  562. 'total_questions' => $paper->question_count,
  563. 'total_score' => $paper->total_score,
  564. 'created_at' => $paper->created_at,
  565. ],
  566. 'student' => $studentInfo,
  567. 'questions' => $questions,
  568. 'mastery' => $masterySummary,
  569. 'parent_mastery_levels' => $processedParentMastery, // 【修复】使用处理后的父节点数据
  570. 'insights' => $analysisData['question_analysis'] ?? [], // 使用question_analysis替代question_results
  571. 'recommendations' => $recommendations,
  572. 'analysis_data' => $analysisData,
  573. ];
  574. }
  575. /**
  576. * 【修复】直接从PaperQuestion表获取题目详情(不通过API)
  577. */
  578. private function getQuestionDetailsFromMySQL(Paper $paper): array
  579. {
  580. $details = [];
  581. Log::info('ExamPdfExportService: 从PaperQuestion表查询题目详情', [
  582. 'paper_id' => $paper->paper_id,
  583. 'question_count' => $paper->questions->count()
  584. ]);
  585. foreach ($paper->questions as $pq) {
  586. try {
  587. // 【关键修复】直接从PaperQuestion对象获取solution和correct_answer
  588. $detail = [
  589. 'id' => $pq->question_id,
  590. 'content' => $pq->question_text,
  591. 'question_type' => $pq->question_type,
  592. 'answer' => $pq->correct_answer ?? null, // 【修复】从PaperQuestion获取正确答案
  593. 'solution' => $pq->solution ?? null, // 【修复】从PaperQuestion获取解题思路
  594. ];
  595. $details[(string) ($pq->question_id ?? $pq->id)] = $detail;
  596. Log::debug('ExamPdfExportService: 成功获取题目详情', [
  597. 'paper_question_id' => $pq->id,
  598. 'question_id' => $pq->question_id,
  599. 'has_answer' => !empty($pq->correct_answer),
  600. 'has_solution' => !empty($pq->solution),
  601. 'answer_preview' => $pq->correct_answer ? substr($pq->correct_answer, 0, 50) : null
  602. ]);
  603. } catch (\Throwable $e) {
  604. Log::error('ExamPdfExportService: 获取题目详情失败', [
  605. 'paper_question_id' => $pq->id,
  606. 'error' => $e->getMessage(),
  607. ]);
  608. }
  609. }
  610. return $details;
  611. }
  612. /**
  613. * 处理题目数据(用于报告)
  614. */
  615. private function processQuestionsForReport($paper, array $questionDetails, array $kpNameMap): array
  616. {
  617. $grouped = [
  618. 'choice' => [],
  619. 'fill' => [],
  620. 'answer' => [],
  621. ];
  622. // 【修复】处理空的试卷(questions可能不存在)
  623. $questions = $paper->questions ?? collect();
  624. if ($questions->isEmpty()) {
  625. Log::info('ExamPdfExportService: 试卷没有题目,返回空数组');
  626. return $grouped;
  627. }
  628. $sortedQuestions = $questions
  629. ->sortBy(function ($q, int $idx) {
  630. $number = $q->question_number ?? $idx + 1;
  631. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  632. });
  633. foreach ($sortedQuestions as $idx => $question) {
  634. $kpCode = $question->knowledge_point ?? '';
  635. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  636. // 【修复】直接从PaperQuestion对象获取solution和correct_answer
  637. $answer = $question->correct_answer ?? null; // 直接从PaperQuestion获取
  638. $solution = $question->solution ?? null; // 直接从PaperQuestion获取
  639. $detail = $questionDetails[(string) ($question->question_id ?? $question->id)] ?? [];
  640. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  641. $normalizedType = $this->normalizeQuestionType($typeRaw);
  642. $number = $question->question_number ?? ($idx + 1);
  643. $payload = [
  644. 'question_number' => $number,
  645. 'question_text' => is_array($question->question_text)
  646. ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
  647. : ($question->question_text ?? ''),
  648. 'question_type' => $normalizedType,
  649. 'knowledge_point' => $kpCode,
  650. 'knowledge_point_name' => $kpName,
  651. 'score' => $question->score,
  652. 'answer' => $answer, // 正确答案
  653. 'solution' => $solution, // 解题思路
  654. 'student_answer' => $question->student_answer ?? null, // 【新增】学生答案
  655. 'correct_answer' => $answer, // 【新增】正确答案
  656. 'is_correct' => $question->is_correct ?? null, // 【新增】判分结果
  657. 'score_obtained' => $question->score_obtained ?? null, // 【新增】得分
  658. ];
  659. $grouped[$normalizedType][] = $payload;
  660. // 【调试】记录题目数据
  661. Log::debug('ExamPdfExportService: 处理题目数据', [
  662. 'paper_question_id' => $question->id,
  663. 'question_id' => $question->question_id,
  664. 'has_answer' => !empty($answer),
  665. 'has_solution' => !empty($solution),
  666. 'answer_preview' => $answer ? substr($answer, 0, 50) : null
  667. ]);
  668. }
  669. $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  670. // 按卷面顺序重新编号
  671. foreach ($ordered as $i => &$q) {
  672. $q['display_number'] = $i + 1;
  673. }
  674. unset($q);
  675. return $ordered;
  676. }
  677. /**
  678. * 构建PDF
  679. */
  680. private function buildPdf(string $html): ?string
  681. {
  682. $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_') . '.html';
  683. $utf8Html = $this->ensureUtf8Html($html);
  684. file_put_contents($tmpHtml, $utf8Html);
  685. // 仅使用Chrome渲染
  686. $chromePdf = $this->renderWithChrome($tmpHtml);
  687. @unlink($tmpHtml);
  688. return $chromePdf;
  689. }
  690. /**
  691. * 使用Chrome渲染PDF
  692. */
  693. private function renderWithChrome(string $htmlPath): ?string
  694. {
  695. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_') . '.pdf';
  696. $userDataDir = sys_get_temp_dir() . '/chrome-profile-' . uniqid();
  697. $chromeBinary = $this->findChromeBinary();
  698. if (!$chromeBinary) {
  699. Log::error('ExamPdfExportService: 未找到可用的Chrome/Chromium');
  700. return null;
  701. }
  702. // 设置运行时目录
  703. $runtimeHome = sys_get_temp_dir() . '/chrome-home';
  704. $runtimeXdg = sys_get_temp_dir() . '/chrome-xdg';
  705. if (!File::exists($runtimeHome)) {
  706. @File::makeDirectory($runtimeHome, 0755, true);
  707. }
  708. if (!File::exists($runtimeXdg)) {
  709. @File::makeDirectory($runtimeXdg, 0755, true);
  710. }
  711. $process = new Process([
  712. $chromeBinary,
  713. '--headless',
  714. '--disable-gpu',
  715. '--no-sandbox',
  716. '--disable-setuid-sandbox',
  717. '--disable-dev-shm-usage',
  718. '--no-zygote',
  719. '--disable-features=VizDisplayCompositor',
  720. '--disable-software-rasterizer',
  721. '--disable-extensions',
  722. '--disable-background-networking',
  723. '--disable-component-update',
  724. '--disable-client-side-phishing-detection',
  725. '--disable-default-apps',
  726. '--disable-domain-reliability',
  727. '--disable-sync',
  728. '--safebrowsing-disable-auto-update',
  729. '--no-first-run',
  730. '--no-default-browser-check',
  731. '--disable-crash-reporter',
  732. '--disable-print-preview',
  733. '--disable-features=PrintHeaderFooter',
  734. '--disable-features=TranslateUI',
  735. '--disable-features=OptimizationHints',
  736. '--disable-ipc-flooding-protection',
  737. '--disable-background-networking',
  738. '--disable-background-timer-throttling',
  739. '--disable-backgrounding-occluded-windows',
  740. '--disable-renderer-backgrounding',
  741. '--disable-features=AudioServiceOutOfProcess',
  742. '--user-data-dir=' . $userDataDir,
  743. '--print-to-pdf=' . $tmpPdf,
  744. '--print-to-pdf-no-header',
  745. '--allow-file-access-from-files',
  746. 'file://' . $htmlPath,
  747. ], null, [
  748. 'HOME' => $runtimeHome,
  749. 'XDG_RUNTIME_DIR' => $runtimeXdg,
  750. ]);
  751. $process->setTimeout(60);
  752. $killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
  753. try {
  754. $startedAt = microtime(true);
  755. $process->start();
  756. $pdfGenerated = false;
  757. // 轮询检测PDF是否生成
  758. $pollStart = microtime(true);
  759. $maxPollSeconds = 30;
  760. while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
  761. if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
  762. $pdfGenerated = true;
  763. $process->stop(5, $killSignal);
  764. break;
  765. }
  766. usleep(200_000);
  767. }
  768. if ($process->isRunning()) {
  769. $process->stop(5, $killSignal);
  770. }
  771. $process->wait();
  772. } catch (ProcessTimedOutException|ProcessSignaledException $e) {
  773. if ($process->isRunning()) {
  774. $process->stop(5, $killSignal);
  775. }
  776. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
  777. } catch (\Throwable $e) {
  778. if ($process->isRunning()) {
  779. $process->stop(5, $killSignal);
  780. }
  781. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  782. }
  783. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  784. }
  785. /**
  786. * 处理Chrome进程结果
  787. */
  788. private function handleChromeProcessResult(string $tmpPdf, string $userDataDir, Process $process, ?float $startedAt): ?string
  789. {
  790. $pdfExists = file_exists($tmpPdf);
  791. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  792. if (!$process->isSuccessful()) {
  793. if ($pdfExists && $pdfSize > 0) {
  794. Log::warning('ExamPdfExportService: Chrome进程异常但生成了PDF', [
  795. 'exit_code' => $process->getExitCode(),
  796. 'tmp_pdf_size' => $pdfSize,
  797. ]);
  798. } else {
  799. Log::error('ExamPdfExportService: Chrome渲染失败', [
  800. 'exit_code' => $process->getExitCode(),
  801. 'error' => $process->getErrorOutput(),
  802. ]);
  803. @unlink($tmpPdf);
  804. File::deleteDirectory($userDataDir);
  805. return null;
  806. }
  807. }
  808. $pdfBinary = $pdfExists ? file_get_contents($tmpPdf) : null;
  809. @unlink($tmpPdf);
  810. File::deleteDirectory($userDataDir);
  811. return $pdfBinary ?: null;
  812. }
  813. /**
  814. * 查找Chrome二进制文件
  815. */
  816. private function findChromeBinary(): ?string
  817. {
  818. $candidates = [
  819. env('PDF_CHROME_BINARY'),
  820. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  821. '/usr/bin/google-chrome-stable',
  822. '/usr/bin/google-chrome',
  823. '/usr/bin/chromium-browser',
  824. '/usr/bin/chromium',
  825. ];
  826. foreach ($candidates as $path) {
  827. if ($path && is_file($path) && is_executable($path)) {
  828. return $path;
  829. }
  830. }
  831. return null;
  832. }
  833. /**
  834. * 确保HTML为UTF-8编码
  835. */
  836. private function ensureUtf8Html(string $html): string
  837. {
  838. $meta = '<meta charset="UTF-8">';
  839. if (stripos($html, '<head>') !== false) {
  840. return preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
  841. }
  842. return $meta . $html;
  843. }
  844. /**
  845. * 构建知识点名称映射
  846. */
  847. private function buildKnowledgePointNameMap(): array
  848. {
  849. try {
  850. $options = $this->questionServiceApi->getKnowledgePointOptions();
  851. return $options ?: [];
  852. } catch (\Throwable $e) {
  853. Log::warning('ExamPdfExportService: 获取知识点名称失败', [
  854. 'error' => $e->getMessage(),
  855. ]);
  856. return [];
  857. }
  858. }
  859. /**
  860. * 构建掌握度摘要
  861. */
  862. private function buildMasterySummary(array $masteryData, array $kpNameMap): array
  863. {
  864. Log::info('ExamPdfExportService: buildMasterySummary开始处理', [
  865. 'masteryData_count' => count($masteryData),
  866. 'kpNameMap_count' => count($kpNameMap)
  867. ]);
  868. $items = [];
  869. $total = 0;
  870. $count = 0;
  871. foreach ($masteryData as $row) {
  872. $code = $row['kp_code'] ?? null;
  873. // 【修复】使用kpNameMap转换名称为友好显示名
  874. $name = $kpNameMap[$code] ?? $row['kp_name'] ?? $code ?: '未知知识点';
  875. $level = (float)($row['mastery_level'] ?? 0);
  876. $delta = $row['mastery_change'] ?? null;
  877. $items[] = [
  878. 'kp_code' => $code,
  879. 'kp_name' => $name,
  880. 'mastery_level' => $level,
  881. 'mastery_change' => $delta,
  882. ];
  883. $total += $level;
  884. $count++;
  885. }
  886. $average = $count > 0 ? round($total / $count, 2) : null;
  887. // 按掌握度从低到高排序
  888. if (!empty($items)) {
  889. usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  890. }
  891. $result = [
  892. 'items' => $items,
  893. 'average' => $average,
  894. 'weak_list' => array_slice($items, 0, 5),
  895. ];
  896. Log::info('ExamPdfExportService: buildMasterySummary完成', [
  897. 'total_count' => $count,
  898. 'items_count' => count($items)
  899. ]);
  900. return $result;
  901. }
  902. /**
  903. * 标准化题型
  904. */
  905. private function normalizeQuestionType(string $type): string
  906. {
  907. $t = strtolower(trim($type));
  908. return match (true) {
  909. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  910. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  911. default => 'answer',
  912. };
  913. }
  914. /**
  915. * 保存PDF URL到数据库
  916. */
  917. private function savePdfUrlToDatabase(string $paperId, string $field, string $url): void
  918. {
  919. try {
  920. $paper = Paper::where('paper_id', $paperId)->first();
  921. if ($paper) {
  922. $paper->update([$field => $url]);
  923. Log::info('ExamPdfExportService: PDF URL已写入数据库', [
  924. 'paper_id' => $paperId,
  925. 'field' => $field,
  926. 'url' => $url,
  927. ]);
  928. }
  929. } catch (\Throwable $e) {
  930. Log::error('ExamPdfExportService: 写入PDF URL失败', [
  931. 'paper_id' => $paperId,
  932. 'field' => $field,
  933. 'error' => $e->getMessage(),
  934. ]);
  935. }
  936. }
  937. /**
  938. * 保存学情分析PDF URL
  939. */
  940. private function saveAnalysisPdfUrl(string $paperId, string $studentId, ?string $recordId, string $url): void
  941. {
  942. try {
  943. if ($recordId) {
  944. // OCR记录
  945. $ocrRecord = \App\Models\OCRRecord::find($recordId);
  946. if ($ocrRecord) {
  947. $ocrRecord->update(['analysis_pdf_url' => $url]);
  948. Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
  949. 'record_id' => $recordId,
  950. 'paper_id' => $paperId,
  951. 'student_id' => $studentId,
  952. 'url' => $url,
  953. ]);
  954. }
  955. } else {
  956. // 【修复】同时更新 exam_analysis_results 表和分析报告表
  957. $updated = \DB::connection('mysql')->table('exam_analysis_results')
  958. ->where('student_id', $studentId)
  959. ->where('paper_id', $paperId)
  960. ->update([
  961. 'analysis_pdf_url' => $url,
  962. 'updated_at' => now(),
  963. ]);
  964. if ($updated) {
  965. Log::info('ExamPdfExportService: 学情分析PDF URL已写入exam_analysis_results表', [
  966. 'student_id' => $studentId,
  967. 'paper_id' => $paperId,
  968. 'url' => $url,
  969. 'updated_rows' => $updated,
  970. ]);
  971. } else {
  972. Log::warning('ExamPdfExportService: 未找到要更新的学情分析记录', [
  973. 'student_id' => $studentId,
  974. 'paper_id' => $paperId,
  975. ]);
  976. }
  977. // 学生记录 - 使用新的 student_reports 表(备用)
  978. \App\Models\StudentReport::updateOrCreate(
  979. [
  980. 'student_id' => $studentId,
  981. 'report_type' => 'exam_analysis',
  982. 'paper_id' => $paperId,
  983. ],
  984. [
  985. 'pdf_url' => $url,
  986. 'generation_status' => 'completed',
  987. 'generated_at' => now(),
  988. 'updated_at' => now(),
  989. ]
  990. );
  991. Log::info('ExamPdfExportService: 学生学情报告PDF URL已保存到student_reports表(备用)', [
  992. 'student_id' => $studentId,
  993. 'paper_id' => $paperId,
  994. 'url' => $url,
  995. ]);
  996. }
  997. } catch (\Throwable $e) {
  998. Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
  999. 'paper_id' => $paperId,
  1000. 'student_id' => $studentId,
  1001. 'record_id' => $recordId,
  1002. 'error' => $e->getMessage(),
  1003. ]);
  1004. }
  1005. }
  1006. /**
  1007. * 【修复】处理父节点掌握度数据
  1008. * 1. 过滤掉掌握度为0或null的父节点
  1009. * 2. 将kp_code转换为友好的kp_name
  1010. * 3. 构建父子层级关系(只显示本次考试相关的子节点)
  1011. */
  1012. private function processParentMasteryLevels(array $parentMasteryLevels, array $kpNameMap, array $examKpCodes = []): array
  1013. {
  1014. $processed = [];
  1015. foreach ($parentMasteryLevels as $kpCode => $masteryData) {
  1016. // 兼容不同数据结构:可能是数组或数字
  1017. $masteryLevel = is_array($masteryData) ? ($masteryData['mastery_level'] ?? 0) : $masteryData;
  1018. $masteryChange = is_array($masteryData) ? ($masteryData['mastery_change'] ?? null) : null;
  1019. // 过滤零值和空值
  1020. if ($masteryLevel === null || $masteryLevel === 0.0 || $masteryLevel <= 0.001) {
  1021. continue;
  1022. }
  1023. // 获取友好名称
  1024. $kpName = $kpNameMap[$kpCode] ?? $kpCode;
  1025. // 构建父节点数据,包含子节点信息(只显示本次考试相关的)
  1026. $processed[$kpCode] = [
  1027. 'kp_code' => $kpCode,
  1028. 'kp_name' => $kpName,
  1029. 'mastery_level' => round(floatval($masteryLevel), 4),
  1030. 'mastery_percentage' => round(floatval($masteryLevel) * 100, 2),
  1031. 'mastery_change' => $masteryChange !== null ? round(floatval($masteryChange), 4) : null,
  1032. // 【修复】只获取本次考试涉及的子节点
  1033. 'children' => $this->getChildKnowledgePoints($kpCode, $kpNameMap, $examKpCodes),
  1034. 'level' => $this->calculateKnowledgePointLevel($kpCode),
  1035. ];
  1036. }
  1037. // 按掌握度降序排序
  1038. uasort($processed, function($a, $b) {
  1039. return $b['mastery_level'] <=> $a['mastery_level'];
  1040. });
  1041. return $processed;
  1042. }
  1043. /**
  1044. * 【修复】获取子知识点列表(只返回本次考试涉及的)
  1045. */
  1046. private function getChildKnowledgePoints(string $parentKpCode, array $kpNameMap, array $examKpCodes = []): array
  1047. {
  1048. $children = [];
  1049. try {
  1050. $childCodes = DB::connection('mysql')
  1051. ->table('knowledge_points')
  1052. ->where('parent_kp_code', $parentKpCode)
  1053. ->pluck('kp_code')
  1054. ->toArray();
  1055. foreach ($childCodes as $childCode) {
  1056. // 只包含本次考试涉及的知识点
  1057. if (in_array($childCode, $examKpCodes)) {
  1058. $children[] = [
  1059. 'kp_code' => $childCode,
  1060. 'kp_name' => $kpNameMap[$childCode] ?? $childCode,
  1061. ];
  1062. }
  1063. }
  1064. } catch (\Exception $e) {
  1065. Log::warning('获取子知识点失败', [
  1066. 'parent_kp_code' => $parentKpCode,
  1067. 'error' => $e->getMessage(),
  1068. ]);
  1069. }
  1070. return $children;
  1071. }
  1072. /**
  1073. * 计算知识点层级深度
  1074. */
  1075. private function calculateKnowledgePointLevel(string $kpCode): int
  1076. {
  1077. // 根据kp_code前缀判断层级深度
  1078. // 例如: M (1级) -> M01 (2级) -> M01A (3级)
  1079. if (preg_match('/^[A-Z]+$/', $kpCode)) {
  1080. return 1; // 一级分类,如 M, S, E, G
  1081. } elseif (preg_match('/^[A-Z]+\d+$/', $kpCode)) {
  1082. return 2; // 二级分类,如 M01, S02
  1083. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+$/', $kpCode)) {
  1084. return 3; // 三级分类,如 M01A, S02B
  1085. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+\d+$/', $kpCode)) {
  1086. return 4; // 四级分类,如 M01A1
  1087. }
  1088. return 1; // 默认一级
  1089. }
  1090. }