ExamPdfExportService.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. <?php
  2. namespace App\Services;
  3. use App\Http\Controllers\ExamPdfController;
  4. use App\Models\Paper;
  5. use App\Models\PaperQuestion;
  6. use App\Models\Student;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Support\Facades\File;
  9. use Illuminate\Support\Facades\Log;
  10. use Illuminate\Support\Facades\Storage;
  11. use Illuminate\Support\Facades\URL;
  12. use App\Services\LearningAnalyticsService;
  13. use App\Services\QuestionBankService;
  14. use App\Services\QuestionServiceApi;
  15. use App\Services\PdfStorageService;
  16. use Symfony\Component\Process\Exception\ProcessSignaledException;
  17. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  18. use Symfony\Component\Process\Process;
  19. class ExamPdfExportService
  20. {
  21. private ExamPdfController $controller;
  22. private LearningAnalyticsService $learningAnalyticsService;
  23. private QuestionBankService $questionBankService;
  24. private PdfStorageService $pdfStorageService;
  25. public function __construct(
  26. ExamPdfController $controller,
  27. LearningAnalyticsService $learningAnalyticsService,
  28. QuestionBankService $questionBankService,
  29. PdfStorageService $pdfStorageService
  30. )
  31. {
  32. $this->controller = $controller;
  33. $this->learningAnalyticsService = $learningAnalyticsService;
  34. $this->questionBankService = $questionBankService;
  35. $this->pdfStorageService = $pdfStorageService;
  36. }
  37. /**
  38. 生成试卷 PDF(不含答案)
  39. */
  40. public function generateExamPdf(string $paperId): ?string
  41. {
  42. $url = $this->renderAndStore($paperId, includeAnswer: false, suffix: 'exam');
  43. // 如果生成成功,将 URL 写入数据库
  44. if ($url) {
  45. try {
  46. $paper = Paper::where('paper_id', $paperId)->first();
  47. if ($paper) {
  48. $paper->update(['exam_pdf_url' => $url]);
  49. Log::info('ExamPdfExportService: 试卷PDF URL已写入数据库', [
  50. 'paper_id' => $paperId,
  51. 'url' => $url,
  52. ]);
  53. }
  54. } catch (\Throwable $e) {
  55. Log::error('ExamPdfExportService: 写入试卷PDF URL失败', [
  56. 'paper_id' => $paperId,
  57. 'error' => $e->getMessage(),
  58. ]);
  59. }
  60. }
  61. return $url;
  62. }
  63. /**
  64. 生成判卷 PDF(含答案与解析)
  65. */
  66. public function generateGradingPdf(string $paperId): ?string
  67. {
  68. $url = $this->renderAndStore($paperId, includeAnswer: true, suffix: 'grading', useGradingView: true);
  69. // 如果生成成功,将 URL 写入数据库
  70. if ($url) {
  71. try {
  72. $paper = Paper::where('paper_id', $paperId)->first();
  73. if ($paper) {
  74. $paper->update(['grading_pdf_url' => $url]);
  75. Log::info('ExamPdfExportService: 判卷PDF URL已写入数据库', [
  76. 'paper_id' => $paperId,
  77. 'url' => $url,
  78. ]);
  79. }
  80. } catch (\Throwable $e) {
  81. Log::error('ExamPdfExportService: 写入判卷PDF URL失败', [
  82. 'paper_id' => $paperId,
  83. 'error' => $e->getMessage(),
  84. ]);
  85. }
  86. }
  87. return $url;
  88. }
  89. /**
  90. * 生成学情分析 PDF
  91. */
  92. public function generateAnalysisReportPdf(string $paperId, string $studentId, ?string $recordId = null): ?string
  93. {
  94. if (function_exists('set_time_limit')) {
  95. @set_time_limit(240);
  96. }
  97. try {
  98. $payload = $this->buildAnalysisPayload($paperId, $studentId);
  99. if (!$payload) {
  100. return null;
  101. }
  102. $html = view('exam-analysis.pdf-report', $payload)->render();
  103. $pdfBinary = $this->buildPdf($html);
  104. if (!$pdfBinary) {
  105. return null;
  106. }
  107. $version = time();
  108. $path = "analysis_reports/{$paperId}_{$studentId}_{$version}.pdf";
  109. $url = $this->pdfStorageService->put($path, $pdfBinary);
  110. if (!$url) {
  111. Log::error('ExamPdfExportService: 保存学情 PDF 失败', [
  112. 'path' => $path,
  113. ]);
  114. return null;
  115. }
  116. // 根据记录类型将 URL 写入不同表
  117. try {
  118. if ($recordId) {
  119. // OCR 记录:写入 ocr_records 表
  120. $ocrRecord = \App\Models\OCRRecord::find($recordId);
  121. if ($ocrRecord) {
  122. $ocrRecord->update(['analysis_pdf_url' => $url]);
  123. Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
  124. 'record_id' => $recordId,
  125. 'paper_id' => $paperId,
  126. 'student_id' => $studentId,
  127. 'url' => $url,
  128. ]);
  129. }
  130. } else {
  131. // 学生记录:写入 students 表
  132. $student = \App\Models\Student::where('student_id', $studentId)->first();
  133. if ($student) {
  134. $student->update(['student_report_pdf_url' => $url]);
  135. Log::info('ExamPdfExportService: 学生学情报告PDF URL已写入数据库', [
  136. 'student_id' => $studentId,
  137. 'paper_id' => $paperId,
  138. 'url' => $url,
  139. ]);
  140. }
  141. }
  142. } catch (\Throwable $e) {
  143. Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
  144. 'paper_id' => $paperId,
  145. 'student_id' => $studentId,
  146. 'record_id' => $recordId,
  147. 'error' => $e->getMessage(),
  148. ]);
  149. }
  150. return $url;
  151. } catch (\Throwable $e) {
  152. Log::error('ExamPdfExportService: 生成学情分析 PDF 失败', [
  153. 'paper_id' => $paperId,
  154. 'student_id' => $studentId,
  155. 'record_id' => $recordId,
  156. 'error' => $e->getMessage(),
  157. 'exception' => get_class($e),
  158. 'trace' => $e->getTraceAsString(),
  159. ]);
  160. return null;
  161. }
  162. }
  163. private function renderAndStore(
  164. string $paperId,
  165. bool $includeAnswer,
  166. string $suffix,
  167. bool $useGradingView = false
  168. ): ?string {
  169. // 放宽脚本执行时间,避免长耗时渲染被 PHP 全局超时打断
  170. if (function_exists('set_time_limit')) {
  171. @set_time_limit(240);
  172. }
  173. try {
  174. $html = $this->renderHtml($paperId, $includeAnswer, $useGradingView);
  175. if (!$html) {
  176. Log::error('ExamPdfExportService: 渲染 HTML 为空', [
  177. 'paper_id' => $paperId,
  178. 'include_answer' => $includeAnswer,
  179. 'use_grading_view' => $useGradingView,
  180. ]);
  181. return null;
  182. }
  183. $pdfBinary = $this->buildPdf($html);
  184. if (!$pdfBinary) {
  185. return null;
  186. }
  187. $path = "exams/{$paperId}_{$suffix}.pdf";
  188. $url = $this->pdfStorageService->put($path, $pdfBinary);
  189. if (!$url) {
  190. Log::error('ExamPdfExportService: 保存 PDF 失败', [
  191. 'path' => $path,
  192. ]);
  193. return null;
  194. }
  195. return $url;
  196. } catch (\Throwable $e) {
  197. Log::error('ExamPdfExportService: 生成 PDF 失败', [
  198. 'paper_id' => $paperId,
  199. 'suffix' => $suffix,
  200. 'error' => $e->getMessage(),
  201. 'exception' => get_class($e),
  202. 'trace' => $e->getTraceAsString(),
  203. ]);
  204. return null;
  205. }
  206. }
  207. private function renderHtml(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
  208. {
  209. // 复用已有控制器的渲染逻辑,保证版式一致
  210. $request = Request::create(
  211. '/admin/intelligent-exam/' . ($useGradingView ? 'grading' : 'pdf') . '/' . $paperId,
  212. 'GET',
  213. ['answer' => $includeAnswer ? 'true' : 'false']
  214. );
  215. $view = $useGradingView
  216. ? $this->controller->showGrading($request, $paperId)
  217. : $this->controller->show($request, $paperId);
  218. if (is_object($view) && method_exists($view, 'render')) {
  219. return $this->ensureUtf8Html($view->render());
  220. }
  221. return null;
  222. }
  223. private function buildPdf(string $html): ?string
  224. {
  225. $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_') . '.html';
  226. $utf8Html = $this->ensureUtf8Html($html);
  227. file_put_contents($tmpHtml, $utf8Html);
  228. // 仅使用 Chrome 渲染,去掉 wkhtmltopdf 兜底以暴露真实问题
  229. $chromePdf = $this->renderWithChrome($tmpHtml);
  230. @unlink($tmpHtml);
  231. return $chromePdf;
  232. }
  233. private function renderWithChrome(string $htmlPath): ?string
  234. {
  235. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_') . '.pdf';
  236. // 每次使用唯一的临时用户目录,彻底避免钥匙串问题
  237. $userDataDir = sys_get_temp_dir() . '/chrome-profile-' . uniqid();
  238. $chromeBinary = env('PDF_CHROME_BINARY');
  239. if (!$chromeBinary) {
  240. $candidates = [
  241. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  242. '/usr/bin/google-chrome-stable',
  243. '/usr/bin/google-chrome',
  244. '/usr/bin/chromium-browser',
  245. '/usr/bin/chromium',
  246. ];
  247. foreach ($candidates as $path) {
  248. if (is_file($path) && is_executable($path)) {
  249. $chromeBinary = $path;
  250. break;
  251. }
  252. }
  253. }
  254. if (!$chromeBinary) {
  255. Log::error('ExamPdfExportService: 未找到可用的 Chrome/Chromium,已停止导出', [
  256. 'html_path' => $htmlPath,
  257. 'path_env' => env('PATH'),
  258. 'candidates_checked' => $candidates ?? [],
  259. ]);
  260. return null;
  261. }
  262. // 为无权限环境设置可写的 HOME/XDG 目录,避免创建 /var/www/.local 报错
  263. $runtimeHome = sys_get_temp_dir() . '/chrome-home';
  264. $runtimeXdg = sys_get_temp_dir() . '/chrome-xdg';
  265. if (!File::exists($runtimeHome)) {
  266. @File::makeDirectory($runtimeHome, 0755, true);
  267. }
  268. if (!File::exists($runtimeXdg)) {
  269. @File::makeDirectory($runtimeXdg, 0755, true);
  270. }
  271. $process = new Process([
  272. $chromeBinary,
  273. '--headless',
  274. '--disable-gpu',
  275. '--no-sandbox',
  276. '--disable-setuid-sandbox',
  277. '--disable-dev-shm-usage',
  278. '--no-zygote',
  279. '--disable-features=VizDisplayCompositor',
  280. '--disable-software-rasterizer',
  281. '--disable-extensions',
  282. '--disable-background-networking',
  283. '--disable-component-update',
  284. '--disable-client-side-phishing-detection',
  285. '--disable-default-apps',
  286. '--disable-domain-reliability',
  287. '--disable-sync',
  288. '--safebrowsing-disable-auto-update',
  289. '--no-first-run',
  290. '--no-default-browser-check',
  291. '--disable-crash-reporter',
  292. '--disable-print-preview',
  293. '--disable-features=PrintHeaderFooter',
  294. '--disable-features=TranslateUI',
  295. '--disable-features=OptimizationHints',
  296. '--disable-ipc-flooding-protection',
  297. '--disable-background-networking',
  298. '--disable-background-timer-throttling',
  299. '--disable-backgrounding-occluded-windows',
  300. '--disable-renderer-backgrounding',
  301. '--disable-features=AudioServiceOutOfProcess',
  302. '--user-data-dir=' . $userDataDir,
  303. '--print-to-pdf=' . $tmpPdf,
  304. '--print-to-pdf-no-header',
  305. '--allow-file-access-from-files',
  306. 'file://' . $htmlPath,
  307. ], null, [
  308. 'HOME' => $runtimeHome,
  309. 'XDG_RUNTIME_DIR' => $runtimeXdg,
  310. ]);
  311. $process->setTimeout(60);
  312. $killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
  313. try {
  314. $startedAt = microtime(true);
  315. Log::info('ExamPdfExportService: Chrome 渲染启动', [
  316. 'cmd' => $process->getCommandLine(),
  317. 'html_path' => $htmlPath,
  318. 'tmp_pdf' => $tmpPdf,
  319. 'user_data_dir' => $userDataDir,
  320. 'html_exists' => file_exists($htmlPath),
  321. 'html_size' => file_exists($htmlPath) ? filesize($htmlPath) : null,
  322. 'cwd' => $process->getWorkingDirectory(),
  323. ]);
  324. $process->start();
  325. $pdfGenerated = false;
  326. // 轮询检测 PDF 是否生成,尽快返回,避免等待 Chrome 完整退出
  327. $pollStart = microtime(true);
  328. $maxPollSeconds = 30;
  329. while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
  330. if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
  331. $pdfGenerated = true;
  332. Log::info('ExamPdfExportService: 发现 PDF 已生成,提前结束 Chrome', [
  333. 'duration_sec' => round(microtime(true) - $startedAt, 3),
  334. 'tmp_pdf_size' => filesize($tmpPdf),
  335. ]);
  336. $process->stop(5, $killSignal);
  337. break;
  338. }
  339. usleep(200_000); // 200ms
  340. }
  341. // 如果仍在运行且超过轮询窗口,则强制结束
  342. if ($process->isRunning()) {
  343. Log::warning('ExamPdfExportService: Chrome 轮询超时,强制结束', [
  344. 'duration_sec' => round(microtime(true) - $startedAt, 3),
  345. ]);
  346. $process->stop(5, $killSignal);
  347. }
  348. $process->wait();
  349. Log::info('ExamPdfExportService: Chrome 渲染完成', [
  350. 'duration_sec' => round(microtime(true) - $startedAt, 3),
  351. 'exit_code' => $process->getExitCode(),
  352. 'tmp_pdf_exists' => file_exists($tmpPdf),
  353. 'tmp_pdf_size' => file_exists($tmpPdf) ? filesize($tmpPdf) : null,
  354. 'stderr' => $process->getErrorOutput(),
  355. 'stdout' => $process->getOutput(),
  356. 'pdf_generated_during_poll' => $pdfGenerated,
  357. ]);
  358. } catch (ProcessTimedOutException|ProcessSignaledException $e) {
  359. Log::error('ExamPdfExportService: Chrome 进程异常', [
  360. 'cmd' => $process->getCommandLine(),
  361. 'signal' => method_exists($process, 'getTermSignal') ? $process->getTermSignal() : null,
  362. 'error' => $process->getErrorOutput(),
  363. 'output' => $process->getOutput(),
  364. 'exit_code' => $process->getExitCode(),
  365. 'exception' => $e->getMessage(),
  366. 'trace' => $e->getTraceAsString(),
  367. ]);
  368. if ($process->isRunning()) {
  369. $process->stop(5, $killSignal);
  370. }
  371. $pdfExists = file_exists($tmpPdf);
  372. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  373. if ($pdfExists && $pdfSize > 0) {
  374. Log::warning('ExamPdfExportService: Chrome 异常但产生了 PDF,尝试继续返回', [
  375. 'tmp_pdf_exists' => $pdfExists,
  376. 'tmp_pdf_size' => $pdfSize,
  377. 'duration_sec' => isset($startedAt) ? round(microtime(true) - $startedAt, 3) : null,
  378. ]);
  379. $pdfBinary = file_get_contents($tmpPdf);
  380. @unlink($tmpPdf);
  381. File::deleteDirectory($userDataDir);
  382. return $pdfBinary ?: null;
  383. }
  384. @unlink($tmpPdf);
  385. File::deleteDirectory($userDataDir);
  386. return null;
  387. } catch (\Throwable $e) {
  388. Log::error('ExamPdfExportService: Chrome 调用异常', [
  389. 'cmd' => $process->getCommandLine(),
  390. 'error' => $e->getMessage(),
  391. 'exit_code' => $process->getExitCode(),
  392. 'stderr' => $process->getErrorOutput(),
  393. 'stdout' => $process->getOutput(),
  394. 'trace' => $e->getTraceAsString(),
  395. ]);
  396. if ($process->isRunning()) {
  397. $process->stop(5, $killSignal);
  398. }
  399. $pdfExists = file_exists($tmpPdf);
  400. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  401. if ($pdfExists && $pdfSize > 0) {
  402. Log::warning('ExamPdfExportService: Chrome 调用异常但产生了 PDF,尝试继续返回', [
  403. 'tmp_pdf_exists' => $pdfExists,
  404. 'tmp_pdf_size' => $pdfSize,
  405. 'duration_sec' => isset($startedAt) ? round(microtime(true) - $startedAt, 3) : null,
  406. ]);
  407. $pdfBinary = file_get_contents($tmpPdf);
  408. @unlink($tmpPdf);
  409. File::deleteDirectory($userDataDir);
  410. return $pdfBinary ?: null;
  411. }
  412. @unlink($tmpPdf);
  413. File::deleteDirectory($userDataDir);
  414. return null;
  415. }
  416. $pdfExists = file_exists($tmpPdf);
  417. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  418. if (!$process->isSuccessful()) {
  419. if ($pdfExists && $pdfSize > 0) {
  420. Log::warning('ExamPdfExportService: Chrome 进程异常但生成了 PDF,继续使用', [
  421. 'cmd' => implode(' ', (array) $process->getCommandLine()),
  422. 'exit_code' => $process->getExitCode(),
  423. 'error' => $process->getErrorOutput(),
  424. 'output' => $process->getOutput(),
  425. 'tmp_pdf_exists' => $pdfExists,
  426. 'tmp_pdf_size' => $pdfSize,
  427. 'html_path' => $htmlPath,
  428. 'user_data_dir' => $userDataDir,
  429. ]);
  430. } else {
  431. Log::error('ExamPdfExportService: Chrome 渲染失败', [
  432. 'cmd' => implode(' ', (array) $process->getCommandLine()),
  433. 'exit_code' => $process->getExitCode(),
  434. 'error' => $process->getErrorOutput(),
  435. 'output' => $process->getOutput(),
  436. 'tmp_pdf_exists' => $pdfExists,
  437. 'tmp_pdf_size' => $pdfSize,
  438. 'html_path' => $htmlPath,
  439. 'user_data_dir' => $userDataDir,
  440. ]);
  441. @unlink($tmpPdf);
  442. File::deleteDirectory($userDataDir);
  443. return null;
  444. }
  445. }
  446. $pdfBinary = $pdfExists ? file_get_contents($tmpPdf) : null;
  447. @unlink($tmpPdf);
  448. File::deleteDirectory($userDataDir);
  449. return $pdfBinary ?: null;
  450. }
  451. private function buildAnalysisPayload(string $paperId, string $studentId): ?array
  452. {
  453. $paper = Paper::with(['questions' => function ($query) {
  454. $query->orderBy('question_number')->orderBy('id');
  455. }])->find($paperId);
  456. if (!$paper) {
  457. Log::error('ExamPdfExportService: 未找到试卷,无法生成学情报告', [
  458. 'paper_id' => $paperId,
  459. 'student_id' => $studentId,
  460. ]);
  461. return null;
  462. }
  463. $student = Student::find($studentId);
  464. $studentInfo = [
  465. 'id' => $student?->student_id ?? $studentId,
  466. 'name' => $student?->name ?? $studentId,
  467. 'grade' => $student?->grade ?? '未知年级',
  468. 'class' => $student?->class_name ?? '未知班级',
  469. ];
  470. // 调用学习分析服务获取本卷分析与掌握度
  471. $analysisData = [];
  472. if (!empty($paper->analysis_id)) {
  473. $analysis = $this->learningAnalyticsService->getAnalysisResult($paper->analysis_id);
  474. if (!empty($analysis['data'])) {
  475. $analysisData = $analysis['data'];
  476. }
  477. }
  478. $masteryData = [];
  479. $masteryResponse = $this->learningAnalyticsService->getStudentMastery($studentId);
  480. if (!empty($masteryResponse['data'])) {
  481. $masteryData = $masteryResponse['data'];
  482. }
  483. $recommendations = [];
  484. $recommendationResponse = $this->learningAnalyticsService->getLearningRecommendations($studentId);
  485. if (!empty($recommendationResponse['data'])) {
  486. $recommendations = $recommendationResponse['data'];
  487. }
  488. $kpNameMap = $this->buildKnowledgePointNameMap();
  489. // 预取题库详情用于解析/解题思路
  490. $questionDetails = [];
  491. $questionIds = $paper->questions->pluck('question_id')->filter()->unique()->values();
  492. foreach ($questionIds as $qid) {
  493. try {
  494. $detail = $this->questionBankService->getQuestion((string) $qid);
  495. if (!empty($detail)) {
  496. $questionDetails[(string) $qid] = $detail;
  497. }
  498. } catch (\Throwable $e) {
  499. Log::warning('ExamPdfExportService: 获取题库题目详情失败', [
  500. 'question_id' => $qid,
  501. 'error' => $e->getMessage(),
  502. ]);
  503. }
  504. }
  505. // 分组保持卷面顺序:选择题 -> 填空题 -> 解答题
  506. $grouped = [
  507. 'choice' => [],
  508. 'fill' => [],
  509. 'answer' => [],
  510. ];
  511. $sortedQuestions = $paper->questions
  512. ->sortBy(function (PaperQuestion $q, int $idx) {
  513. $number = $q->question_number ?? $idx + 1;
  514. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  515. });
  516. foreach ($sortedQuestions as $idx => $question) {
  517. $kpCode = $question->knowledge_point ?? '';
  518. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  519. $detail = $questionDetails[(string) ($question->question_id ?? '')] ?? [];
  520. $solution = $detail['solution'] ?? $detail['解析'] ?? $detail['analysis'] ?? null;
  521. // 题型优先使用试卷记录,其次题库详情
  522. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  523. $normalizedType = $this->normalizeQuestionType($typeRaw);
  524. $number = $question->question_number ?? ($idx + 1);
  525. $payload = [
  526. 'question_number' => $number,
  527. 'question_text' => is_array($question->question_text) ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE) : ($question->question_text ?? ''),
  528. 'question_type' => $normalizedType,
  529. 'knowledge_point' => $kpCode,
  530. 'knowledge_point_name' => $kpName,
  531. 'score' => $question->score,
  532. 'solution' => $solution,
  533. ];
  534. $grouped[$normalizedType][] = $payload;
  535. }
  536. $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  537. // 按卷面顺序重新编号以匹配判卷/显示
  538. foreach ($ordered as $i => &$q) {
  539. $q['display_number'] = $i + 1;
  540. }
  541. unset($q);
  542. $questions = $ordered;
  543. $questionInsights = $analysisData['question_results'] ?? [];
  544. $masterySummary = $this->buildMasterySummary($masteryData, $kpNameMap);
  545. return [
  546. 'paper' => [
  547. 'id' => $paper->paper_id,
  548. 'name' => $paper->paper_name,
  549. 'total_questions' => $paper->question_count,
  550. 'total_score' => $paper->total_score,
  551. 'created_at' => $paper->created_at,
  552. ],
  553. 'student' => $studentInfo,
  554. 'questions' => $questions,
  555. 'mastery' => $masterySummary,
  556. 'question_insights' => $questionInsights,
  557. 'recommendations' => $recommendations,
  558. 'analysis_data' => $analysisData,
  559. ];
  560. }
  561. private function buildKnowledgePointNameMap(): array
  562. {
  563. try {
  564. // 优先使用 QuestionServiceApi(已有知识点名称缓存)
  565. if (class_exists(QuestionServiceApi::class)) {
  566. /** @var QuestionServiceApi $service */
  567. $service = app(QuestionServiceApi::class);
  568. $options = $service->getKnowledgePointOptions();
  569. if (!empty($options)) {
  570. return $options;
  571. }
  572. }
  573. // 退回 QuestionBankService(可能缺少此方法)
  574. if (method_exists($this->questionBankService, 'getKnowledgePointOptions')) {
  575. $options = $this->questionBankService->getKnowledgePointOptions();
  576. $map = [];
  577. foreach ($options as $item) {
  578. if (is_array($item)) {
  579. $code = $item['kp_code'] ?? null;
  580. $name = $item['kp_name'] ?? $item['name'] ?? null;
  581. if ($code && $name) {
  582. $map[$code] = $name;
  583. }
  584. }
  585. }
  586. if (!empty($map)) {
  587. return $map;
  588. }
  589. }
  590. } catch (\Throwable $e) {
  591. Log::warning('ExamPdfExportService: 获取知识点名称失败,退回使用编码', [
  592. 'error' => $e->getMessage(),
  593. ]);
  594. }
  595. return [];
  596. }
  597. private function buildMasterySummary(array $masteryData, array $kpNameMap): array
  598. {
  599. $items = [];
  600. $total = 0;
  601. $count = 0;
  602. $hasMap = !empty($kpNameMap);
  603. foreach ($masteryData as $row) {
  604. $code = $row['kp_code'] ?? null;
  605. if ($hasMap && $code && !isset($kpNameMap[$code])) {
  606. // 不在知识图谱中的知识点不呈现
  607. continue;
  608. }
  609. $name = $row['kp_name'] ?? ($code ? ($kpNameMap[$code] ?? $code) : '未知知识点');
  610. $level = (float) ($row['mastery_level'] ?? 0);
  611. $delta = $row['mastery_change'] ?? null;
  612. $items[] = [
  613. 'kp_code' => $code,
  614. 'kp_name' => $name,
  615. 'mastery_level' => $level,
  616. 'mastery_change' => $delta,
  617. ];
  618. $total += $level;
  619. $count++;
  620. }
  621. $average = $count > 0 ? round($total / $count, 2) : null;
  622. // 按掌握度从低到高排序,便于突出薄弱点
  623. usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  624. return [
  625. 'items' => $items,
  626. 'average' => $average,
  627. 'weak_list' => array_slice($items, 0, 5),
  628. ];
  629. }
  630. private function normalizeQuestionType(?string $type): string
  631. {
  632. $t = strtolower(trim((string) $type));
  633. return match (true) {
  634. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  635. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  636. default => 'answer',
  637. };
  638. }
  639. private function ensureUtf8Html(string $html): string
  640. {
  641. $meta = '<meta charset="UTF-8">';
  642. if (stripos($html, '<head>') !== false) {
  643. return preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
  644. }
  645. return $meta . $html;
  646. }
  647. }