ExamPdfExportService.php 24 KB

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