ExamPdfExportService.php 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045
  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. private ?KatexRenderer $katexRenderer = null;
  25. public function __construct(
  26. private readonly LearningAnalyticsService $learningAnalyticsService,
  27. private readonly QuestionBankService $questionBankService,
  28. private readonly QuestionServiceApi $questionServiceApi,
  29. private readonly PdfStorageService $pdfStorageService,
  30. private readonly MasteryCalculator $masteryCalculator,
  31. private readonly PdfMerger $pdfMerger
  32. ) {
  33. // 延迟初始化 KatexRenderer(避免循环依赖)
  34. $this->katexRenderer = new KatexRenderer();
  35. }
  36. /**
  37. * 生成试卷 PDF(不含答案)
  38. */
  39. public function generateExamPdf(string $paperId): ?string
  40. {
  41. Log::info('generateExamPdf 开始:', ['paper_id' => $paperId]);
  42. $url = $this->renderAndStoreExamPdf($paperId, includeAnswer: false, suffix: 'exam');
  43. Log::info('generateExamPdf url 生成结果:', ['paper_id' => $paperId, 'url' => $url]);
  44. // 如果生成成功,将 URL 写入数据库
  45. if ($url) {
  46. $this->savePdfUrlToDatabase($paperId, 'exam_pdf_url', $url);
  47. }
  48. return $url;
  49. }
  50. /**
  51. * 生成判卷 PDF(含答案与解析)
  52. */
  53. public function generateGradingPdf(string $paperId): ?string
  54. {
  55. Log::info('generateGradingPdf 开始:', ['paper_id' => $paperId]);
  56. $url = $this->renderAndStoreExamPdf($paperId, includeAnswer: true, suffix: 'grading', useGradingView: true);
  57. Log::info('generateGradingPdf url 生成结果:', ['paper_id' => $paperId, 'url' => $url]);
  58. // 如果生成成功,将 URL 写入数据库
  59. if ($url) {
  60. $this->savePdfUrlToDatabase($paperId, 'grading_pdf_url', $url);
  61. }
  62. return $url;
  63. }
  64. /**
  65. * 【优化方案】生成统一PDF(卷子 + 判卷一页完成)
  66. * 效率提升40-50%,只需生成一次PDF
  67. */
  68. public function generateUnifiedPdf(string $paperId): ?string
  69. {
  70. Log::info('generateUnifiedPdf 开始(终极优化版本,直接HTML合并生成PDF):', ['paper_id' => $paperId]);
  71. try {
  72. // 步骤1:同时渲染两个页面的HTML
  73. Log::info('generateUnifiedPdf: 开始渲染试卷HTML', ['paper_id' => $paperId]);
  74. $examHtml = $this->renderExamHtml($paperId, includeAnswer: false, useGradingView: false);
  75. if (!$examHtml) {
  76. Log::error('ExamPdfExportService: 渲染卷子HTML失败', ['paper_id' => $paperId]);
  77. return null;
  78. }
  79. Log::info('generateUnifiedPdf: 试卷HTML渲染完成', ['paper_id' => $paperId, 'length' => strlen($examHtml)]);
  80. Log::info('generateUnifiedPdf: 开始渲染判卷HTML', ['paper_id' => $paperId]);
  81. $gradingHtml = $this->renderExamHtml($paperId, includeAnswer: true, useGradingView: true);
  82. if (!$gradingHtml) {
  83. Log::error('ExamPdfExportService: 渲染判卷HTML失败', ['paper_id' => $paperId]);
  84. return null;
  85. }
  86. Log::info('generateUnifiedPdf: 判卷HTML渲染完成', ['paper_id' => $paperId, 'length' => strlen($gradingHtml)]);
  87. // 步骤2:插入分页符,合并HTML
  88. Log::info('generateUnifiedPdf: 开始合并HTML(保留原始样式)', ['paper_id' => $paperId]);
  89. $unifiedHtml = $this->mergeHtmlWithPageBreak($examHtml, $gradingHtml);
  90. if (!$unifiedHtml) {
  91. Log::error('ExamPdfExportService: HTML合并失败', ['paper_id' => $paperId]);
  92. return null;
  93. }
  94. Log::info('generateUnifiedPdf: HTML合并完成(将直接生成PDF,不使用pdfunite)', ['paper_id' => $paperId, 'length' => strlen($unifiedHtml)]);
  95. // 步骤3:一次性生成PDF(只需20-25秒,比原来节省10-25秒)
  96. Log::info('generateUnifiedPdf: 开始使用buildPdf直接生成PDF(不使用pdfunite)', ['paper_id' => $paperId]);
  97. $pdfBinary = $this->buildPdf($unifiedHtml);
  98. if (!$pdfBinary) {
  99. Log::error('ExamPdfExportService: 生成统一PDF失败', ['paper_id' => $paperId]);
  100. return null;
  101. }
  102. Log::info('generateUnifiedPdf: PDF生成完成', ['paper_id' => $paperId, 'pdf_size' => strlen($pdfBinary)]);
  103. // 步骤4:保存PDF
  104. $path = "exams/{$paperId}_all.pdf";
  105. Log::info('generateUnifiedPdf: 开始保存PDF到云存储', ['paper_id' => $paperId, 'path' => $path]);
  106. $url = $this->pdfStorageService->put($path, $pdfBinary);
  107. if (!$url) {
  108. Log::error('ExamPdfExportService: 保存统一PDF失败', ['path' => $path]);
  109. return null;
  110. }
  111. Log::info('generateUnifiedPdf: PDF保存完成', ['paper_id' => $paperId, 'url' => $url]);
  112. // 步骤5:保存URL到数据库(存储到all_pdf_url字段)
  113. Log::info('generateUnifiedPdf: 开始保存URL到数据库', ['paper_id' => $paperId, 'field' => 'all_pdf_url']);
  114. $this->savePdfUrlToDatabase($paperId, 'all_pdf_url', $url);
  115. Log::info('generateUnifiedPdf: URL保存完成', ['paper_id' => $paperId]);
  116. Log::info('generateUnifiedPdf 全部完成(终极优化:直接HTML合并生成一份PDF)', [
  117. 'paper_id' => $paperId,
  118. 'url' => $url,
  119. 'pdf_size' => strlen($pdfBinary),
  120. 'method' => 'direct HTML merge to PDF (no pdfunite)'
  121. ]);
  122. return $url;
  123. } catch (\Throwable $e) {
  124. Log::error('generateUnifiedPdf 失败', [
  125. 'paper_id' => $paperId,
  126. 'error' => $e->getMessage(),
  127. 'trace' => $e->getTraceAsString(),
  128. ]);
  129. return null;
  130. }
  131. }
  132. /**
  133. * 生成合并PDF(试卷 + 判卷)
  134. * 先分别生成两个PDF,然后合并
  135. */
  136. public function generateMergedPdf(string $paperId): ?string
  137. {
  138. Log::info('generateMergedPdf 开始:', ['paper_id' => $paperId]);
  139. $tempDir = storage_path("app/temp");
  140. if (!is_dir($tempDir)) {
  141. mkdir($tempDir, 0755, true);
  142. }
  143. $examPdfPath = null;
  144. $gradingPdfPath = null;
  145. $mergedPdfPath = null;
  146. try {
  147. // 先生成试卷PDF
  148. $examPdfUrl = $this->generateExamPdf($paperId);
  149. if (!$examPdfUrl) {
  150. Log::error('ExamPdfExportService: 生成试卷PDF失败', ['paper_id' => $paperId]);
  151. return null;
  152. }
  153. // 再生成判卷PDF
  154. $gradingPdfUrl = $this->generateGradingPdf($paperId);
  155. if (!$gradingPdfUrl) {
  156. Log::error('ExamPdfExportService: 生成判卷PDF失败', ['paper_id' => $paperId]);
  157. return null;
  158. }
  159. // 【修复】下载PDF文件到本地临时目录
  160. Log::info('开始下载PDF文件到本地', [
  161. 'exam_url' => $examPdfUrl,
  162. 'grading_url' => $gradingPdfUrl
  163. ]);
  164. $examPdfPath = $tempDir . "/{$paperId}_exam.pdf";
  165. $gradingPdfPath = $tempDir . "/{$paperId}_grading.pdf";
  166. // 下载试卷PDF
  167. $examContent = Http::get($examPdfUrl)->body();
  168. if (empty($examContent)) {
  169. Log::error('ExamPdfExportService: 下载试卷PDF失败', ['url' => $examPdfUrl]);
  170. return null;
  171. }
  172. file_put_contents($examPdfPath, $examContent);
  173. // 下载判卷PDF
  174. $gradingContent = Http::get($gradingPdfUrl)->body();
  175. if (empty($gradingContent)) {
  176. Log::error('ExamPdfExportService: 下载判卷PDF失败', ['url' => $gradingPdfUrl]);
  177. return null;
  178. }
  179. file_put_contents($gradingPdfPath, $gradingContent);
  180. Log::info('PDF文件下载完成', [
  181. 'exam_size' => filesize($examPdfPath),
  182. 'grading_size' => filesize($gradingPdfPath)
  183. ]);
  184. // 合并PDF文件
  185. $mergedPdfPath = $tempDir . "/{$paperId}_merged.pdf";
  186. $merged = $this->pdfMerger->merge([$examPdfPath, $gradingPdfPath], $mergedPdfPath);
  187. if (!$merged) {
  188. Log::error('ExamPdfExportService: PDF文件合并失败', [
  189. 'tool' => $this->pdfMerger->getMergeTool()
  190. ]);
  191. return null;
  192. }
  193. // 读取合并后的PDF内容并上传到云存储
  194. $mergedPdfContent = file_get_contents($mergedPdfPath);
  195. $path = "exams/{$paperId}_all.pdf";
  196. $mergedUrl = $this->pdfStorageService->put($path, $mergedPdfContent);
  197. if (!$mergedUrl) {
  198. Log::error('ExamPdfExportService: 保存合并PDF失败', ['path' => $path]);
  199. return null;
  200. }
  201. // 保存到数据库的all_pdf_url字段
  202. $this->saveAllPdfUrlToDatabase($paperId, $mergedUrl);
  203. Log::info('generateMergedPdf 完成:', [
  204. 'paper_id' => $paperId,
  205. 'url' => $mergedUrl,
  206. 'tool' => $this->pdfMerger->getMergeTool()
  207. ]);
  208. return $mergedUrl;
  209. } catch (\Throwable $e) {
  210. Log::error('ExamPdfExportService: 生成合并PDF失败', [
  211. 'paper_id' => $paperId,
  212. 'error' => $e->getMessage(),
  213. 'trace' => $e->getTraceAsString(),
  214. ]);
  215. return null;
  216. } finally {
  217. // 【修复】清理临时文件
  218. $tempFiles = [$examPdfPath, $gradingPdfPath, $mergedPdfPath];
  219. foreach ($tempFiles as $file) {
  220. if ($file && file_exists($file)) {
  221. @unlink($file);
  222. }
  223. }
  224. Log::debug('清理临时文件完成');
  225. }
  226. }
  227. /**
  228. * 将URL转换为本地文件路径
  229. */
  230. private function convertUrlToPath(string $url): ?string
  231. {
  232. // 如果是本地存储,URL格式类似:/storage/exams/paper_id_exam.pdf
  233. // 需要转换为绝对路径
  234. if (strpos($url, '/storage/') === 0) {
  235. return public_path(ltrim($url, '/'));
  236. }
  237. // 如果是完整路径,直接返回
  238. if (strpos($url, '/') === 0 && file_exists($url)) {
  239. return $url;
  240. }
  241. // 如果是相对路径,转换为绝对路径
  242. $path = public_path($url);
  243. if (file_exists($path)) {
  244. return $path;
  245. }
  246. return null;
  247. }
  248. /**
  249. * 保存合并PDF URL到数据库
  250. */
  251. private function saveAllPdfUrlToDatabase(string $paperId, string $url): void
  252. {
  253. try {
  254. \App\Models\Paper::where('paper_id', $paperId)->update([
  255. 'all_pdf_url' => $url
  256. ]);
  257. Log::debug('保存all_pdf_url成功', ['paper_id' => $paperId, 'url' => $url]);
  258. } catch (\Exception $e) {
  259. Log::error('保存all_pdf_url失败', [
  260. 'paper_id' => $paperId,
  261. 'url' => $url,
  262. 'error' => $e->getMessage()
  263. ]);
  264. throw $e;
  265. }
  266. }
  267. /**
  268. * 生成学情分析 PDF
  269. */
  270. public function generateAnalysisReportPdf(string $paperId, string $studentId, ?string $recordId = null): ?string
  271. {
  272. if (function_exists('set_time_limit')) {
  273. @set_time_limit(240);
  274. }
  275. try {
  276. // 【调试】打印输入参数
  277. Log::info('ExamPdfExportService: 开始生成学情分析PDF', [
  278. 'paper_id' => $paperId,
  279. 'student_id' => $studentId,
  280. 'record_id' => $recordId,
  281. ]);
  282. // 构建分析数据
  283. $analysisData = $this->buildAnalysisData($paperId, $studentId);
  284. if (!$analysisData) {
  285. Log::warning('ExamPdfExportService: buildAnalysisData返回空数据', [
  286. 'paper_id' => $paperId,
  287. 'student_id' => $studentId,
  288. ]);
  289. return null;
  290. }
  291. Log::info('ExamPdfExportService: buildAnalysisData返回数据', [
  292. 'paper_id' => $paperId,
  293. 'student_id' => $studentId,
  294. 'analysisData_keys' => array_keys($analysisData),
  295. 'mastery_count' => count($analysisData['mastery']['items'] ?? []),
  296. 'questions_count' => count($analysisData['questions'] ?? []),
  297. ]);
  298. // 创建DTO
  299. $dto = ExamAnalysisDataDto::fromArray($analysisData);
  300. $payloadDto = ReportPayloadDto::fromExamAnalysisDataDto($dto);
  301. // 【调试】打印传给模板的数据
  302. $templateData = $payloadDto->toArray();
  303. Log::info('ExamPdfExportService: 传给模板的数据', [
  304. 'paper' => $templateData['paper'] ?? null,
  305. 'student' => $templateData['student'] ?? null,
  306. 'mastery' => $templateData['mastery'] ?? null,
  307. 'parent_mastery_levels' => $templateData['parent_mastery_levels'] ?? null, // 新增:检查父节点掌握度
  308. 'questions_count' => count($templateData['questions'] ?? []),
  309. 'insights_count' => count($templateData['question_insights'] ?? []),
  310. 'recommendations_count' => count($templateData['recommendations'] ?? []),
  311. ]);
  312. // 渲染HTML
  313. $html = view('exam-analysis.pdf-report', $templateData)->render();
  314. if (!$html) {
  315. Log::error('ExamPdfExportService: 渲染HTML为空', ['paper_id' => $paperId]);
  316. return null;
  317. }
  318. // 生成PDF
  319. $pdfBinary = $this->buildPdf($html);
  320. if (!$pdfBinary) {
  321. return null;
  322. }
  323. // 保存PDF
  324. $version = time();
  325. $path = "analysis_reports/{$paperId}_{$studentId}_{$version}.pdf";
  326. $url = $this->pdfStorageService->put($path, $pdfBinary);
  327. if (!$url) {
  328. Log::error('ExamPdfExportService: 保存学情PDF失败', ['path' => $path]);
  329. return null;
  330. }
  331. // 保存URL到数据库
  332. $this->saveAnalysisPdfUrl($paperId, $studentId, $recordId, $url);
  333. return $url;
  334. } catch (\Throwable $e) {
  335. Log::error('ExamPdfExportService: 生成学情分析PDF失败', [
  336. 'paper_id' => $paperId,
  337. 'student_id' => $studentId,
  338. 'record_id' => $recordId,
  339. 'error' => $e->getMessage(),
  340. 'exception' => get_class($e),
  341. 'trace' => $e->getTraceAsString(),
  342. ]);
  343. return null;
  344. }
  345. }
  346. /**
  347. * 渲染并存储试卷PDF
  348. */
  349. private function renderAndStoreExamPdf(
  350. string $paperId,
  351. bool $includeAnswer,
  352. string $suffix,
  353. bool $useGradingView = false
  354. ): ?string {
  355. // 放宽脚本执行时间
  356. if (function_exists('set_time_limit')) {
  357. @set_time_limit(240);
  358. }
  359. try {
  360. $html = $this->renderExamHtml($paperId, $includeAnswer, $useGradingView);
  361. if (!$html) {
  362. Log::error('ExamPdfExportService: 渲染HTML为空', [
  363. 'paper_id' => $paperId,
  364. 'include_answer' => $includeAnswer,
  365. 'use_grading_view' => $useGradingView,
  366. ]);
  367. return null;
  368. }
  369. $pdfBinary = $this->buildPdf($html);
  370. if (!$pdfBinary) {
  371. Log::error('ExamPdfExportService: buildPdf为空', [
  372. 'paper_id' => $paperId,
  373. 'include_answer' => $includeAnswer,
  374. 'use_grading_view' => $useGradingView,
  375. ]);
  376. return null;
  377. }
  378. $path = "exams/{$paperId}_{$suffix}.pdf";
  379. $url = $this->pdfStorageService->put($path, $pdfBinary);
  380. if (!$url) {
  381. Log::error('ExamPdfExportService: 保存PDF失败', ['path' => $path]);
  382. return null;
  383. }
  384. return $url;
  385. } catch (\Throwable $e) {
  386. Log::error('ExamPdfExportService: 生成PDF失败', [
  387. 'paper_id' => $paperId,
  388. 'suffix' => $suffix,
  389. 'error' => $e->getMessage(),
  390. 'exception' => get_class($e),
  391. 'trace' => $e->getTraceAsString(),
  392. ]);
  393. return null;
  394. }
  395. }
  396. /**
  397. * 渲染试卷HTML(重构版)
  398. */
  399. private function renderExamHtml(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
  400. {
  401. // 直接构造请求URL,使用路由生成HTML
  402. $routeName = $useGradingView
  403. ? 'filament.admin.auth.intelligent-exam.grading'
  404. : 'filament.admin.auth.intelligent-exam.pdf';
  405. $url = route($routeName, ['paper_id' => $paperId, 'answer' => $includeAnswer ? 'true' : 'false']);
  406. // 使用HTTP客户端获取渲染后的HTML
  407. try {
  408. $response = Http::get($url);
  409. if ($response->successful()) {
  410. $html = $response->body();
  411. if (!empty(trim($html))) {
  412. return $this->ensureUtf8Html($html);
  413. } else {
  414. Log::warning('ExamPdfExportService: HTTP返回的HTML为空,使用备用方案', [
  415. 'paper_id' => $paperId,
  416. 'url' => $url,
  417. ]);
  418. }
  419. }
  420. } catch (\Exception $e) {
  421. Log::warning('ExamPdfExportService: 通过HTTP获取HTML失败,使用备用方案', [
  422. 'paper_id' => $paperId,
  423. 'error' => $e->getMessage(),
  424. ]);
  425. }
  426. // 备用方案:直接渲染视图(如果路由不可用)
  427. try {
  428. $paper = Paper::with('questions')->find($paperId);
  429. if (!$paper) {
  430. Log::error('ExamPdfExportService: 试卷不存在,备用方案无法渲染', [
  431. 'paper_id' => $paperId,
  432. 'include_answer' => $includeAnswer,
  433. 'use_grading_view' => $useGradingView,
  434. ]);
  435. return null;
  436. }
  437. // 检查试卷是否有题目
  438. if ($paper->questions->isEmpty()) {
  439. Log::error('ExamPdfExportService: 试卷没有题目数据', [
  440. 'paper_id' => $paperId,
  441. 'question_count' => 0,
  442. ]);
  443. return null;
  444. }
  445. $viewName = $useGradingView ? 'exam-pdf.grading' : 'exam-pdf.student';
  446. $html = view($viewName, compact('paper'))->render();
  447. if (empty(trim($html))) {
  448. Log::error('ExamPdfExportService: 视图渲染结果为空', [
  449. 'paper_id' => $paperId,
  450. 'view_name' => $viewName,
  451. 'question_count' => $paper->questions->count(),
  452. ]);
  453. return null;
  454. }
  455. return $this->ensureUtf8Html($html);
  456. } catch (\Exception $e) {
  457. Log::error('ExamPdfExportService: 备用方案渲染失败', [
  458. 'paper_id' => $paperId,
  459. 'error' => $e->getMessage(),
  460. 'trace' => $e->getTraceAsString(),
  461. ]);
  462. return null;
  463. }
  464. }
  465. /**
  466. * 构建分析数据(重构版)
  467. * 优先使用本地MySQL数据,减少API依赖
  468. */
  469. private function buildAnalysisData(string $paperId, string $studentId): ?array
  470. {
  471. // 【关键调试】确认方法被调用
  472. Log::warning('ExamPdfExportService: buildAnalysisData方法被调用了!', [
  473. 'paper_id' => $paperId,
  474. 'student_id' => $studentId,
  475. 'timestamp' => now()->toISOString()
  476. ]);
  477. $paper = Paper::with(['questions' => function ($query) {
  478. $query->orderBy('question_number')->orderBy('id');
  479. }])->find($paperId);
  480. if (!$paper) {
  481. Log::warning('ExamPdfExportService: 未找到试卷,将尝试仅基于分析数据生成PDF', [
  482. 'paper_id' => $paperId,
  483. 'student_id' => $studentId,
  484. ]);
  485. // 【修复】即使试卷不存在,也尝试基于分析数据生成PDF
  486. $paper = new \stdClass();
  487. $paper->paper_id = $paperId;
  488. $paper->paper_name = "学情分析报告_{$studentId}_{$paperId}";
  489. $paper->question_count = 0;
  490. $paper->total_score = 0;
  491. $paper->created_at = now();
  492. $paper->questions = collect();
  493. }
  494. $student = Student::find($studentId);
  495. $studentInfo = [
  496. 'id' => $student?->student_id ?? $studentId,
  497. 'name' => $student?->name ?? $studentId,
  498. 'grade' => $student?->grade ?? '未知年级',
  499. 'class' => $student?->class_name ?? '未知班级',
  500. ];
  501. // 【修改】直接从本地数据库获取分析数据(不再调用API)
  502. $analysisData = [];
  503. // 首先尝试从paper->analysis_id获取
  504. if (!empty($paper->analysis_id)) {
  505. Log::info('ExamPdfExportService: 从本地数据库获取试卷分析数据', [
  506. 'paper_id' => $paperId,
  507. 'student_id' => $studentId,
  508. 'analysis_id' => $paper->analysis_id
  509. ]);
  510. $analysisRecord = \DB::table('exam_analysis_results')
  511. ->where('id', $paper->analysis_id)
  512. ->where('student_id', $studentId)
  513. ->first();
  514. if ($analysisRecord && !empty($analysisRecord->analysis_data)) {
  515. $analysisData = json_decode($analysisRecord->analysis_data, true);
  516. Log::info('ExamPdfExportService: 成功获取本地分析数据(通过analysis_id)', [
  517. 'data_size' => strlen($analysisRecord->analysis_data)
  518. ]);
  519. } else {
  520. Log::warning('ExamPdfExportService: 未找到本地分析数据,将尝试其他方式', [
  521. 'paper_id' => $paperId,
  522. 'student_id' => $studentId,
  523. 'analysis_id' => $paper->analysis_id
  524. ]);
  525. }
  526. }
  527. // 如果没有analysis_id或未找到数据,直接从exam_analysis_results表查询
  528. if (empty($analysisData)) {
  529. Log::info('ExamPdfExportService: 直接从exam_analysis_results表查询分析数据', [
  530. 'paper_id' => $paperId,
  531. 'student_id' => $studentId
  532. ]);
  533. $analysisRecord = \DB::table('exam_analysis_results')
  534. ->where('paper_id', $paperId)
  535. ->where('student_id', $studentId)
  536. ->first();
  537. if ($analysisRecord && !empty($analysisRecord->analysis_data)) {
  538. $analysisData = json_decode($analysisRecord->analysis_data, true);
  539. Log::info('ExamPdfExportService: 成功获取本地分析数据(直接查询)', [
  540. 'data_size' => strlen($analysisRecord->analysis_data),
  541. 'question_count' => count($analysisData['question_analysis'] ?? [])
  542. ]);
  543. } else {
  544. Log::warning('ExamPdfExportService: 未找到任何分析数据,将使用空数据', [
  545. 'paper_id' => $paperId,
  546. 'student_id' => $studentId
  547. ]);
  548. }
  549. }
  550. // 【修复】优先使用analysisData中的knowledge_point_analysis数据
  551. $masteryData = [];
  552. $parentMasteryLevels = []; // 新增:父节点掌握度数据
  553. Log::info('ExamPdfExportService: 开始处理掌握度数据', [
  554. 'student_id' => $studentId,
  555. 'analysisData_keys' => array_keys($analysisData),
  556. 'has_knowledge_point_analysis' => !empty($analysisData['knowledge_point_analysis']),
  557. ]);
  558. if (!empty($analysisData['knowledge_point_analysis'])) {
  559. // 将knowledge_point_analysis转换为buildMasterySummary期望的格式
  560. foreach ($analysisData['knowledge_point_analysis'] as $kp) {
  561. $masteryData[] = [
  562. 'kp_code' => $kp['kp_id'] ?? null,
  563. 'kp_name' => $kp['kp_id'] ?? '未知知识点',
  564. 'mastery_level' => $kp['mastery_level'] ?? 0,
  565. 'mastery_change' => $kp['change'] ?? null,
  566. ];
  567. }
  568. // 【修复】基于所有兄弟节点历史数据计算父节点掌握度,并获取掌握度变化
  569. try {
  570. // 获取本次考试涉及的知识点代码列表
  571. $examKpCodes = array_column($masteryData, 'kp_code');
  572. Log::info('ExamPdfExportService: 本次考试涉及的知识点', [
  573. 'count' => count($examKpCodes),
  574. 'kp_codes' => $examKpCodes
  575. ]);
  576. // 获取上一个快照的数据(用于计算变化)
  577. // 如果没有其他试卷的记录,使用同一试卷的上一次快照
  578. $lastSnapshot = DB::connection('mysql')
  579. ->table('knowledge_point_mastery_snapshots')
  580. ->where('student_id', $studentId)
  581. ->where('paper_id', $paper->paper_id)
  582. ->where('snapshot_id', '!=', "snap_{$paper->paper_id}_" . date('YmdHis'))
  583. ->latest('snapshot_time')
  584. ->first();
  585. $previousMasteryData = [];
  586. if ($lastSnapshot) {
  587. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  588. foreach ($previousMasteryJson as $kpCode => $data) {
  589. $previousMasteryData[$kpCode] = [
  590. 'current_mastery' => $data['current_mastery'] ?? 0,
  591. 'previous_mastery' => $data['previous_mastery'] ?? null,
  592. ];
  593. }
  594. Log::info('ExamPdfExportService: 获取到上一次快照数据', [
  595. 'snapshot_time' => $lastSnapshot->snapshot_time,
  596. 'kp_count' => count($previousMasteryData)
  597. ]);
  598. }
  599. // 为当前知识点添加变化数据
  600. foreach ($masteryData as &$item) {
  601. $kpCode = $item['kp_code'];
  602. if (isset($previousMasteryData[$kpCode])) {
  603. $previous = floatval($previousMasteryData[$kpCode]['previous_mastery'] ?? 0);
  604. $current = floatval($item['mastery_level']);
  605. $item['mastery_change'] = $current - $previous;
  606. }
  607. }
  608. unset($item); // 解除引用
  609. // 获取所有父节点掌握度
  610. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  611. $allParentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? [];
  612. // 计算与本次考试相关的父节点掌握度(基于所有兄弟节点)
  613. $parentMasteryLevels = [];
  614. // 【修复】使用数据库查询正确匹配父子关系,而不是字符串前缀
  615. foreach ($allParentMasteryLevels as $parentKpCode => $parentMastery) {
  616. // 查询这个父节点的所有子节点
  617. $childNodes = DB::connection('mysql')
  618. ->table('knowledge_points')
  619. ->where('parent_kp_code', $parentKpCode)
  620. ->pluck('kp_code')
  621. ->toArray();
  622. // 检查是否有子节点在本次考试中出现
  623. $relevantChildren = array_intersect($examKpCodes, $childNodes);
  624. if (!empty($relevantChildren)) {
  625. // 【修复】计算父节点变化:基于所有子节点的平均变化
  626. $childChanges = [];
  627. foreach ($relevantChildren as $childKpCode) {
  628. $previousChild = $previousMasteryData[$childKpCode]['previous_mastery'] ?? null;
  629. $currentChild = null;
  630. foreach ($masteryData as $item) {
  631. if ($item['kp_code'] === $childKpCode) {
  632. $currentChild = $item['mastery_level'];
  633. break;
  634. }
  635. }
  636. if ($previousChild !== null && $currentChild !== null) {
  637. $childChanges[] = floatval($currentChild) - floatval($previousChild);
  638. }
  639. }
  640. $avgChange = !empty($childChanges) ? array_sum($childChanges) / count($childChanges) : null;
  641. // 获取父节点中文名称
  642. $parentKpInfo = DB::connection('mysql')
  643. ->table('knowledge_points')
  644. ->where('kp_code', $parentKpCode)
  645. ->first();
  646. $parentMasteryLevels[$parentKpCode] = [
  647. 'kp_code' => $parentKpCode,
  648. 'kp_name' => $parentKpInfo->name ?? $parentKpCode,
  649. 'mastery_level' => $parentMastery,
  650. 'mastery_percentage' => round($parentMastery * 100, 1),
  651. 'mastery_change' => $avgChange,
  652. 'children' => $relevantChildren,
  653. ];
  654. }
  655. }
  656. Log::info('ExamPdfExportService: 过滤后的父节点掌握度', [
  657. 'all_parent_count' => count($allParentMasteryLevels),
  658. 'filtered_parent_count' => count($parentMasteryLevels),
  659. 'filtered_codes' => array_keys($parentMasteryLevels)
  660. ]);
  661. } catch (\Exception $e) {
  662. Log::warning('ExamPdfExportService: 获取父节点掌握度失败', [
  663. 'error' => $e->getMessage()
  664. ]);
  665. }
  666. Log::info('ExamPdfExportService: 使用analysisData中的掌握度数据', [
  667. 'count' => count($masteryData),
  668. 'masteryData_sample' => !empty($masteryData) ? array_slice($masteryData, 0, 2) : []
  669. ]);
  670. } else {
  671. // 如果没有knowledge_point_analysis,使用MasteryCalculator获取多层级掌握度概览
  672. try {
  673. Log::info('ExamPdfExportService: 获取学生多层级掌握度概览', [
  674. 'student_id' => $studentId
  675. ]);
  676. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  677. $masteryData = $masteryOverview['details'] ?? [];
  678. $parentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? []; // 获取父节点掌握度
  679. // 【修复】将对象数组转换为关联数组(避免 stdClass 对象访问错误)
  680. if (!empty($masteryData) && is_array($masteryData)) {
  681. $masteryData = array_map(function($item) {
  682. if (is_object($item)) {
  683. return [
  684. 'kp_code' => $item->kp_code ?? null,
  685. 'kp_name' => $item->kp_name ?? null,
  686. 'mastery_level' => floatval($item->mastery_level ?? 0),
  687. 'mastery_change' => $item->mastery_change !== null ? floatval($item->mastery_change) : null,
  688. ];
  689. }
  690. return $item;
  691. }, $masteryData);
  692. }
  693. // 【修复】获取快照数据以计算掌握度变化
  694. $lastSnapshot = DB::connection('mysql')
  695. ->table('knowledge_point_mastery_snapshots')
  696. ->where('student_id', $studentId)
  697. ->latest('snapshot_time')
  698. ->first();
  699. if ($lastSnapshot) {
  700. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  701. foreach ($masteryData as &$item) {
  702. $kpCode = $item['kp_code'];
  703. if (isset($previousMasteryJson[$kpCode])) {
  704. $previous = floatval($previousMasteryJson[$kpCode]['previous_mastery'] ?? 0);
  705. $current = floatval($item['mastery_level']);
  706. $item['mastery_change'] = $current - $previous;
  707. }
  708. }
  709. unset($item);
  710. }
  711. Log::info('ExamPdfExportService: 成功获取多层级掌握度数据', [
  712. 'count' => count($masteryData),
  713. 'parent_count' => count($parentMasteryLevels)
  714. ]);
  715. } catch (\Exception $e) {
  716. Log::error('ExamPdfExportService: 获取掌握度数据失败', [
  717. 'student_id' => $studentId,
  718. 'error' => $e->getMessage()
  719. ]);
  720. }
  721. }
  722. // 【修改】使用本地方法获取学习路径推荐(替代API调用)
  723. $recommendations = [];
  724. try {
  725. Log::info('ExamPdfExportService: 获取学习路径推荐', [
  726. 'student_id' => $studentId
  727. ]);
  728. $learningPaths = $this->learningAnalyticsService->recommendLearningPaths($studentId, 3);
  729. $recommendations = $learningPaths['recommendations'] ?? [];
  730. Log::info('ExamPdfExportService: 成功获取学习路径推荐', [
  731. 'count' => count($recommendations)
  732. ]);
  733. } catch (\Exception $e) {
  734. Log::error('ExamPdfExportService: 获取学习路径推荐失败', [
  735. 'student_id' => $studentId,
  736. 'error' => $e->getMessage()
  737. ]);
  738. }
  739. // 获取知识点名称映射
  740. $kpNameMap = $this->buildKnowledgePointNameMap();
  741. Log::info('ExamPdfExportService: 获取知识点名称映射', [
  742. 'kpNameMap_count' => count($kpNameMap),
  743. 'kpNameMap_keys_sample' => !empty($kpNameMap) ? array_slice(array_keys($kpNameMap), 0, 5) : []
  744. ]);
  745. // 【修复】直接从MySQL数据库获取题目详情(不通过API)
  746. // 只有当 $paper 是 Paper 模型时才查询题目详情
  747. $questionDetails = ($paper instanceof \App\Models\Paper)
  748. ? $this->getQuestionDetailsFromMySQL($paper)
  749. : [];
  750. // 处理题目数据
  751. $questions = $this->processQuestionsForReport($paper, $questionDetails, $kpNameMap);
  752. // 【关键调试】查看buildMasterySummary的返回结果
  753. $masterySummary = $this->buildMasterySummary($masteryData, $kpNameMap);
  754. Log::info('ExamPdfExportService: buildMasterySummary返回结果', [
  755. 'masteryData_count' => count($masteryData),
  756. 'kpNameMap_count' => count($kpNameMap),
  757. 'masterySummary_keys' => array_keys($masterySummary),
  758. 'masterySummary_items_count' => count($masterySummary['items'] ?? []),
  759. 'masterySummary_items_sample' => !empty($masterySummary['items']) ? array_slice($masterySummary['items'], 0, 2) : []
  760. ]);
  761. // 【修复】处理父节点掌握度数据:过滤零值、转换名称、构建层级关系
  762. $examKpCodes = array_column($masteryData, 'kp_code'); // 本次考试涉及的知识点
  763. $processedParentMastery = $this->processParentMasteryLevels($parentMasteryLevels, $kpNameMap, $examKpCodes);
  764. Log::info('ExamPdfExportService: 处理后的父节点掌握度', [
  765. 'raw_count' => count($parentMasteryLevels),
  766. 'processed_count' => count($processedParentMastery),
  767. 'processed_sample' => !empty($processedParentMastery) ? array_slice($processedParentMastery, 0, 3) : []
  768. ]);
  769. return [
  770. 'paper' => [
  771. 'id' => $paper->paper_id,
  772. 'name' => $paper->paper_name,
  773. 'total_questions' => $paper->question_count,
  774. 'total_score' => $paper->total_score,
  775. 'created_at' => $paper->created_at,
  776. ],
  777. 'student' => $studentInfo,
  778. 'questions' => $questions,
  779. 'mastery' => $masterySummary,
  780. 'parent_mastery_levels' => $processedParentMastery, // 【修复】使用处理后的父节点数据
  781. 'insights' => $analysisData['question_analysis'] ?? [], // 使用question_analysis替代question_results
  782. 'recommendations' => $recommendations,
  783. 'analysis_data' => $analysisData,
  784. ];
  785. }
  786. /**
  787. * 【修复】直接从PaperQuestion表获取题目详情(不通过API)
  788. */
  789. private function getQuestionDetailsFromMySQL(Paper $paper): array
  790. {
  791. $details = [];
  792. Log::info('ExamPdfExportService: 从PaperQuestion表查询题目详情', [
  793. 'paper_id' => $paper->paper_id,
  794. 'question_count' => $paper->questions->count()
  795. ]);
  796. foreach ($paper->questions as $pq) {
  797. try {
  798. // 【关键修复】直接从PaperQuestion对象获取solution和correct_answer
  799. $detail = [
  800. 'id' => $pq->question_id,
  801. 'content' => $pq->question_text,
  802. 'question_type' => $pq->question_type,
  803. 'answer' => $pq->correct_answer ?? null, // 【修复】从PaperQuestion获取正确答案
  804. 'solution' => $pq->solution ?? null, // 【修复】从PaperQuestion获取解题思路
  805. ];
  806. $details[(string) ($pq->question_id ?? $pq->id)] = $detail;
  807. Log::debug('ExamPdfExportService: 成功获取题目详情', [
  808. 'paper_question_id' => $pq->id,
  809. 'question_id' => $pq->question_id,
  810. 'has_answer' => !empty($pq->correct_answer),
  811. 'has_solution' => !empty($pq->solution),
  812. 'answer_preview' => $pq->correct_answer ? substr($pq->correct_answer, 0, 50) : null
  813. ]);
  814. } catch (\Throwable $e) {
  815. Log::error('ExamPdfExportService: 获取题目详情失败', [
  816. 'paper_question_id' => $pq->id,
  817. 'error' => $e->getMessage(),
  818. ]);
  819. }
  820. }
  821. return $details;
  822. }
  823. /**
  824. * 处理题目数据(用于报告)
  825. */
  826. private function processQuestionsForReport($paper, array $questionDetails, array $kpNameMap): array
  827. {
  828. $grouped = [
  829. 'choice' => [],
  830. 'fill' => [],
  831. 'answer' => [],
  832. ];
  833. // 【修复】处理空的试卷(questions可能不存在)
  834. $questions = $paper->questions ?? collect();
  835. if ($questions->isEmpty()) {
  836. Log::info('ExamPdfExportService: 试卷没有题目,返回空数组');
  837. return $grouped;
  838. }
  839. $sortedQuestions = $questions
  840. ->sortBy(function ($q, int $idx) {
  841. $number = $q->question_number ?? $idx + 1;
  842. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  843. });
  844. foreach ($sortedQuestions as $idx => $question) {
  845. $kpCode = $question->knowledge_point ?? '';
  846. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  847. // 【修复】直接从PaperQuestion对象获取solution和correct_answer
  848. $answer = $question->correct_answer ?? null; // 直接从PaperQuestion获取
  849. $solution = $question->solution ?? null; // 直接从PaperQuestion获取
  850. $detail = $questionDetails[(string) ($question->question_id ?? $question->id)] ?? [];
  851. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  852. $normalizedType = $this->normalizeQuestionType($typeRaw);
  853. $number = $question->question_number ?? ($idx + 1);
  854. // 处理题干文本
  855. $questionText = is_array($question->question_text)
  856. ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
  857. : ($question->question_text ?? '');
  858. $payload = [
  859. 'question_number' => $number,
  860. 'question_text' => $this->formatNewlines($questionText), // 格式化换行
  861. 'question_type' => $normalizedType,
  862. 'knowledge_point' => $kpCode,
  863. 'knowledge_point_name' => $kpName,
  864. 'score' => $question->score,
  865. 'answer' => $this->formatNewlines($answer), // 格式化换行
  866. 'solution' => $this->formatNewlines($solution), // 格式化换行
  867. 'student_answer' => $this->formatNewlines($question->student_answer ?? null), // 格式化换行
  868. 'correct_answer' => $this->formatNewlines($answer), // 格式化换行
  869. 'is_correct' => $question->is_correct ?? null,
  870. 'score_obtained' => $question->score_obtained ?? null,
  871. ];
  872. $grouped[$normalizedType][] = $payload;
  873. // 【调试】记录题目数据
  874. Log::debug('ExamPdfExportService: 处理题目数据', [
  875. 'paper_question_id' => $question->id,
  876. 'question_id' => $question->question_id,
  877. 'has_answer' => !empty($answer),
  878. 'has_solution' => !empty($solution),
  879. 'answer_preview' => $answer ? substr($answer, 0, 50) : null
  880. ]);
  881. }
  882. $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  883. // 按卷面顺序重新编号
  884. foreach ($ordered as $i => &$q) {
  885. $q['display_number'] = $i + 1;
  886. }
  887. unset($q);
  888. return $ordered;
  889. }
  890. /**
  891. * 构建PDF
  892. */
  893. private function buildPdf(string $html): ?string
  894. {
  895. $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_') . '.html';
  896. $utf8Html = $this->ensureUtf8Html($html);
  897. $written = file_put_contents($tmpHtml, $utf8Html);
  898. Log::warning('ExamPdfExportService: [调试] HTML文件已创建', [
  899. 'path' => $tmpHtml,
  900. 'html_length' => strlen($utf8Html),
  901. 'written_bytes' => $written,
  902. 'file_exists' => file_exists($tmpHtml),
  903. 'file_size' => file_exists($tmpHtml) ? filesize($tmpHtml) : 0,
  904. ]);
  905. // 仅使用Chrome渲染
  906. $chromePdf = $this->renderWithChrome($tmpHtml);
  907. @unlink($tmpHtml);
  908. return $chromePdf;
  909. }
  910. /**
  911. * 使用Chrome渲染PDF
  912. */
  913. private function renderWithChrome(string $htmlPath): ?string
  914. {
  915. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_') . '.pdf';
  916. $userDataDir = sys_get_temp_dir() . '/chrome-profile-' . uniqid();
  917. $chromeBinary = $this->findChromeBinary();
  918. if (!$chromeBinary) {
  919. Log::error('ExamPdfExportService: 未找到可用的Chrome/Chromium');
  920. return null;
  921. }
  922. // 设置运行时目录
  923. $runtimeHome = sys_get_temp_dir() . '/chrome-home';
  924. $runtimeXdg = sys_get_temp_dir() . '/chrome-xdg';
  925. if (!File::exists($runtimeHome)) {
  926. @File::makeDirectory($runtimeHome, 0755, true);
  927. }
  928. if (!File::exists($runtimeXdg)) {
  929. @File::makeDirectory($runtimeXdg, 0755, true);
  930. }
  931. $process = new Process([
  932. $chromeBinary,
  933. '--headless=new', // 【优化】使用新渲染引擎
  934. '--disable-gpu',
  935. '--no-sandbox',
  936. '--disable-setuid-sandbox',
  937. '--disable-dev-shm-usage',
  938. '--disable-web-security',
  939. '--disable-features=VizDisplayCompositor',
  940. '--disable-extensions',
  941. // '--disable-background-networking', // 注释掉,可能阻止必要的网络请求
  942. '--disable-component-update',
  943. '--disable-client-side-phishing-detection',
  944. '--disable-default-apps',
  945. '--disable-domain-reliability',
  946. '--disable-sync',
  947. '--no-first-run',
  948. '--no-default-browser-check',
  949. '--disable-crash-reporter',
  950. '--disable-print-preview',
  951. '--disable-features=TranslateUI',
  952. '--disable-features=OptimizationHints',
  953. '--disable-ipc-flooding-protection',
  954. '--disable-background-timer-throttling',
  955. '--disable-backgrounding-occluded-windows',
  956. '--disable-renderer-backgrounding',
  957. '--disable-features=AudioServiceOutOfProcess',
  958. '--disable-gpu-sandbox',
  959. '--disable-software-rasterizer',
  960. '--disable-background-mode',
  961. '--disable-extensions-http-throttling',
  962. '--disable-ipc-flooding-protection',
  963. '--disable-features=Dbus', // 禁用 dbus
  964. // 【关键修复】添加虚拟时间预算,让Chrome有足够时间加载CDN资源和执行JS
  965. '--virtual-time-budget=30000', // 30秒虚拟时间用于加载外部资源
  966. '--run-all-compositor-stages-before-draw', // 确保所有渲染完成后再生成PDF
  967. '--user-data-dir=' . $userDataDir,
  968. '--print-to-pdf=' . $tmpPdf,
  969. '--print-to-pdf-no-header',
  970. '--allow-file-access-from-files',
  971. '--font-render-hinting=none', // 【优化】禁用字体渲染提示
  972. '--disable-font-antialiasing',
  973. 'file://' . $htmlPath,
  974. ], null, [
  975. 'HOME' => $runtimeHome,
  976. 'XDG_RUNTIME_DIR' => $runtimeXdg,
  977. ]);
  978. $process->setTimeout(90); // 【修复】增加超时时间到90秒
  979. $killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
  980. Log::warning('ExamPdfExportService: [调试] Chrome命令准备执行', [
  981. 'chrome_binary' => $chromeBinary,
  982. 'html_path' => $htmlPath,
  983. 'html_exists' => file_exists($htmlPath),
  984. 'html_size' => file_exists($htmlPath) ? filesize($htmlPath) : 0,
  985. 'pdf_path' => $tmpPdf,
  986. 'user_data_dir' => $userDataDir,
  987. ]);
  988. try {
  989. $startedAt = microtime(true);
  990. $process->start();
  991. $pdfGenerated = false;
  992. // 轮询检测PDF是否生成
  993. $pollStart = microtime(true);
  994. $maxPollSeconds = 80; // 【修复】增加轮询超时到80秒
  995. while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
  996. if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
  997. $pdfGenerated = true;
  998. Log::info('ExamPdfExportService: PDF生成成功,提前终止Chrome进程', [
  999. 'elapsed' => round(microtime(true) - $startedAt, 2),
  1000. 'pdf_size' => filesize($tmpPdf),
  1001. ]);
  1002. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1003. break;
  1004. }
  1005. usleep(100_000); // 【优化】从200ms减少到100ms
  1006. }
  1007. if ($process->isRunning()) {
  1008. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1009. }
  1010. // 【优化】删除不必要的wait()调用,避免重复等待
  1011. // $process->wait();
  1012. } catch (ProcessTimedOutException|ProcessSignaledException $e) {
  1013. if ($process->isRunning()) {
  1014. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1015. }
  1016. Log::warning('ExamPdfExportService: Chrome进程超时或被信号中断', [
  1017. 'elapsed' => round((microtime(true) - $startedAt), 2),
  1018. 'exception' => get_class($e),
  1019. ]);
  1020. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
  1021. } catch (\Throwable $e) {
  1022. if ($process->isRunning()) {
  1023. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1024. }
  1025. Log::error('ExamPdfExportService: Chrome进程异常', [
  1026. 'elapsed' => round((microtime(true) - $startedAt), 2),
  1027. 'error' => $e->getMessage(),
  1028. ]);
  1029. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  1030. }
  1031. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  1032. }
  1033. /**
  1034. * 处理Chrome进程结果
  1035. */
  1036. private function handleChromeProcessResult(string $tmpPdf, string $userDataDir, Process $process, ?float $startedAt): ?string
  1037. {
  1038. $pdfExists = file_exists($tmpPdf);
  1039. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  1040. $elapsed = $startedAt ? round((microtime(true) - $startedAt), 2) : null;
  1041. // 【优化】即使进程未成功,只要PDF存在且大小合理就返回
  1042. if ($pdfExists && $pdfSize > 1000) { // 至少1KB
  1043. Log::info('ExamPdfExportService: PDF生成成功', [
  1044. 'elapsed' => $elapsed,
  1045. 'pdf_size' => $pdfSize,
  1046. 'exit_code' => $process->getExitCode(),
  1047. 'is_successful' => $process->isSuccessful(),
  1048. ]);
  1049. $pdfBinary = file_get_contents($tmpPdf);
  1050. @unlink($tmpPdf);
  1051. File::deleteDirectory($userDataDir);
  1052. return $pdfBinary;
  1053. }
  1054. // 如果PDF不存在或太小,记录错误
  1055. Log::error('ExamPdfExportService: Chrome渲染失败', [
  1056. 'elapsed' => $elapsed,
  1057. 'pdf_exists' => $pdfExists,
  1058. 'pdf_size' => $pdfSize,
  1059. 'exit_code' => $process->getExitCode(),
  1060. 'error' => $process->getErrorOutput(),
  1061. 'output' => $process->getOutput(),
  1062. ]);
  1063. @unlink($tmpPdf);
  1064. File::deleteDirectory($userDataDir);
  1065. return null;
  1066. }
  1067. /**
  1068. * 查找Chrome二进制文件
  1069. */
  1070. private function findChromeBinary(): ?string
  1071. {
  1072. $candidates = [
  1073. env('PDF_CHROME_BINARY'),
  1074. env('CHROME_BIN'), // Docker Alpine 环境变量
  1075. '/usr/bin/chromium-browser', // Alpine Linux
  1076. '/usr/bin/chromium',
  1077. '/usr/bin/google-chrome-stable',
  1078. '/usr/bin/google-chrome',
  1079. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', // macOS
  1080. ];
  1081. foreach ($candidates as $path) {
  1082. if ($path && is_file($path) && is_executable($path)) {
  1083. return $path;
  1084. }
  1085. }
  1086. return null;
  1087. }
  1088. /**
  1089. * 确保HTML为UTF-8编码,并内联外部资源
  1090. */
  1091. private function ensureUtf8Html(string $html): string
  1092. {
  1093. $meta = '<meta charset="UTF-8">';
  1094. if (stripos($html, '<head>') !== false) {
  1095. $html = preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
  1096. } else {
  1097. $html = $meta . $html;
  1098. }
  1099. // 【关键修复】内联KaTeX CSS,避免Chrome在容器中加载CDN资源超时
  1100. $html = $this->inlineExternalResources($html);
  1101. return $html;
  1102. }
  1103. /**
  1104. * 将CDN资源替换为内联资源
  1105. * 【关键修复】避免Chrome在容器中加载CDN资源超时
  1106. */
  1107. private function inlineExternalResources(string $html): string
  1108. {
  1109. // 【调试】记录HTML内容信息
  1110. Log::warning('ExamPdfExportService: inlineExternalResources', [
  1111. 'html_length' => strlen($html),
  1112. 'has_katex_cdn' => strpos($html, 'cdn.jsdelivr.net/npm/katex') !== false,
  1113. 'html_head_preview' => substr($html, 0, 1000),
  1114. ]);
  1115. // 检查是否包含KaTeX CDN链接
  1116. if (strpos($html, 'cdn.jsdelivr.net/npm/katex') === false) {
  1117. Log::warning('ExamPdfExportService: HTML中没有KaTeX CDN链接,跳过内联');
  1118. return $html;
  1119. }
  1120. try {
  1121. // 读取本地KaTeX CSS文件并内联
  1122. $katexCssPath = public_path('css/katex/katex.min.css');
  1123. if (file_exists($katexCssPath)) {
  1124. $katexCss = file_get_contents($katexCssPath);
  1125. // 修复字体路径:将相对路径改为绝对路径(使用data URI或绝对路径)
  1126. // KaTeX CSS中的字体引用格式: url(fonts/KaTeX_xxx.woff2)
  1127. $fontsDir = public_path('css/katex/fonts');
  1128. $katexCss = preg_replace_callback(
  1129. '/url\(["\']?fonts\/([^"\')\s]+)["\']?\)/i',
  1130. function ($matches) use ($fontsDir) {
  1131. $fontFile = $fontsDir . '/' . $matches[1];
  1132. if (file_exists($fontFile)) {
  1133. // 将字体转换为data URI(适用于PDF生成)
  1134. $fontData = base64_encode(file_get_contents($fontFile));
  1135. $mimeType = str_ends_with($matches[1], '.woff2') ? 'font/woff2' : 'font/woff';
  1136. return 'url(data:' . $mimeType . ';base64,' . $fontData . ')';
  1137. }
  1138. return $matches[0];
  1139. },
  1140. $katexCss
  1141. );
  1142. // 替换CDN CSS链接为内联样式
  1143. $html = preg_replace(
  1144. '/<link[^>]*href=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*katex\.min\.css["\'][^>]*>/i',
  1145. '<style type="text/css">' . $katexCss . '</style>',
  1146. $html
  1147. );
  1148. Log::info('ExamPdfExportService: KaTeX CSS已内联(含字体data URI)');
  1149. }
  1150. // 读取本地KaTeX JS并内联
  1151. $katexJsPath = public_path('js/katex.min.js');
  1152. $autoRenderJsPath = public_path('js/auto-render.min.js');
  1153. if (file_exists($katexJsPath)) {
  1154. $katexJs = file_get_contents($katexJsPath);
  1155. $html = preg_replace(
  1156. '/<script[^>]*src=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*katex\.min\.js["\'][^>]*><\/script>/i',
  1157. '<script type="text/javascript">' . $katexJs . '</script>',
  1158. $html
  1159. );
  1160. }
  1161. if (file_exists($autoRenderJsPath)) {
  1162. $autoRenderJs = file_get_contents($autoRenderJsPath);
  1163. $html = preg_replace(
  1164. '/<script[^>]*src=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*auto-render[^"\']*["\'][^>]*><\/script>/i',
  1165. '<script type="text/javascript">' . $autoRenderJs . '</script>',
  1166. $html
  1167. );
  1168. }
  1169. // 【关键修复】使用服务端预渲染,而不是依赖客户端 JavaScript
  1170. // Chrome headless 的 --print-to-pdf 不会等待 JS 执行完成
  1171. // 所以我们使用 Node.js KaTeX 在服务端预渲染所有公式
  1172. // 1. 移除所有 KaTeX JavaScript(不再需要,因为使用服务端渲染)
  1173. // 移除内联的 katex.min.js
  1174. $html = preg_replace(
  1175. '/<script[^>]*type=["\']text\/javascript["\'][^>]*>[\s\S]*?katex[\s\S]*?<\/script>/i',
  1176. '<!-- KaTeX JS removed, using server-side rendering -->',
  1177. $html
  1178. );
  1179. // 移除 DOMContentLoaded 监听器
  1180. $html = preg_replace(
  1181. '/<script[^>]*>[\s\S]*?document\.addEventListener[\s\S]*?DOMContentLoaded[\s\S]*?<\/script>/i',
  1182. '<!-- DOMContentLoaded removed -->',
  1183. $html
  1184. );
  1185. // 2. 使用 KatexRenderer 进行服务端预渲染
  1186. if ($this->katexRenderer) {
  1187. $beforeLength = strlen($html);
  1188. $html = $this->katexRenderer->renderHtml($html);
  1189. $afterLength = strlen($html);
  1190. Log::info('ExamPdfExportService: LaTeX 公式服务端预渲染完成', [
  1191. 'before_length' => $beforeLength,
  1192. 'after_length' => $afterLength,
  1193. 'size_change' => $afterLength - $beforeLength,
  1194. ]);
  1195. } else {
  1196. Log::warning('ExamPdfExportService: KatexRenderer 未初始化,跳过预渲染');
  1197. }
  1198. // 【换行处理】将字面的 \n 转换为 <br> 标签(在 KaTeX 渲染后处理,避免破坏公式)
  1199. $html = str_replace(['\\n\\n', '\\n'], ['<br><br>', '<br>'], $html);
  1200. } catch (\Exception $e) {
  1201. Log::warning('ExamPdfExportService: 内联资源处理失败,保留原始HTML', [
  1202. 'error' => $e->getMessage()
  1203. ]);
  1204. }
  1205. return $html;
  1206. }
  1207. /**
  1208. * 【新增】合并两个HTML页面,插入分页符
  1209. * 保留原始页面样式和结构,只在中间插入分页符
  1210. */
  1211. private function mergeHtmlWithPageBreak(string $examHtml, string $gradingHtml): ?string
  1212. {
  1213. try {
  1214. // 确保HTML编码正确
  1215. $examHtml = $this->ensureUtf8Html($examHtml);
  1216. $gradingHtml = $this->ensureUtf8Html($gradingHtml);
  1217. // 提取body内容
  1218. $examBody = $this->extractBodyContent($examHtml);
  1219. $gradingBody = $this->extractBodyContent($gradingHtml);
  1220. if (empty($examBody) || empty($gradingBody)) {
  1221. Log::error('ExamPdfExportService: HTML内容提取失败', [
  1222. 'exam_body_length' => strlen($examBody),
  1223. 'grading_body_length' => strlen($gradingBody)
  1224. ]);
  1225. return null;
  1226. }
  1227. // 提取head内容(保留原始样式和meta信息)
  1228. $examHead = $this->extractHeadContent($examHtml);
  1229. // 构建统一HTML文档(保留原始结构)
  1230. $unifiedHtml = $this->buildUnifiedHtmlWithOriginalStructure($examHead, $examBody, $gradingBody);
  1231. Log::info('HTML合并成功(保留原始样式)', [
  1232. 'exam_length' => strlen($examBody),
  1233. 'grading_length' => strlen($gradingBody),
  1234. 'unified_length' => strlen($unifiedHtml),
  1235. 'head_length' => strlen($examHead)
  1236. ]);
  1237. return $unifiedHtml;
  1238. } catch (\Throwable $e) {
  1239. Log::error('mergeHtmlWithPageBreak 失败', [
  1240. 'error' => $e->getMessage(),
  1241. 'trace' => $e->getTraceAsString()
  1242. ]);
  1243. return null;
  1244. }
  1245. }
  1246. /**
  1247. * 【新增】提取HTML的body内容
  1248. */
  1249. private function extractBodyContent(string $html): string
  1250. {
  1251. // 匹配body标签内容
  1252. if (preg_match('/<body[^>]*>(.*)<\/body>/is', $html, $matches)) {
  1253. return $matches[1];
  1254. }
  1255. // 如果没有body标签,返回整个HTML
  1256. return $html;
  1257. }
  1258. /**
  1259. * 【新增】提取HTML的head内容
  1260. * 保留原始页面的样式和meta信息
  1261. */
  1262. private function extractHeadContent(string $html): string
  1263. {
  1264. // 匹配head标签内容
  1265. if (preg_match('/<head[^>]*>(.*)<\/head>/is', $html, $matches)) {
  1266. return $matches[1];
  1267. }
  1268. // 如果没有head标签,返回默认meta
  1269. return '<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">';
  1270. }
  1271. /**
  1272. * 【新增】构建统一的HTML文档(保留原始结构)
  1273. * 保留第一个HTML的完整head和样式,只在body之间插入分页符
  1274. */
  1275. private function buildUnifiedHtmlWithOriginalStructure(string $examHead, string $examBody, string $gradingBody): string
  1276. {
  1277. // 保留原始head内容,添加分页符样式
  1278. $headContent = $examHead . '
  1279. <style>
  1280. /* 分页符样式 - 插入到原始样式之后 */
  1281. .page-break {
  1282. page-break-before: always;
  1283. page-break-after: always;
  1284. break-before: page;
  1285. break-after: page;
  1286. }
  1287. /* 确保分页符在打印时生效 */
  1288. @media print {
  1289. .page-break {
  1290. page-break-before: always;
  1291. }
  1292. }
  1293. </style>';
  1294. return '<!DOCTYPE html>
  1295. <html lang="zh-CN">
  1296. <head>
  1297. ' . $headContent . '
  1298. </head>
  1299. <body>
  1300. <!-- 第一部分:试卷(不含答案) -->
  1301. ' . $examBody . '
  1302. <!-- 分页符:第二部分从这里开始 -->
  1303. <div class="page-break"></div>
  1304. <!-- 第二部分:判卷(含答案与解析) -->
  1305. ' . $gradingBody . '
  1306. </body>
  1307. </html>';
  1308. }
  1309. /**
  1310. * 【新增】获取PDF通用样式
  1311. */
  1312. private function getCommonPdfStyles(): string
  1313. {
  1314. return '
  1315. * {
  1316. margin: 0;
  1317. padding: 0;
  1318. box-sizing: border-box;
  1319. }
  1320. body {
  1321. font-family: "Microsoft YaHei", "SimHei", Arial, sans-serif;
  1322. font-size: 14px;
  1323. line-height: 1.6;
  1324. color: #333;
  1325. background: #fff;
  1326. }
  1327. .paper-container {
  1328. max-width: 210mm;
  1329. margin: 0 auto;
  1330. padding: 20mm;
  1331. background: white;
  1332. }
  1333. .paper-header {
  1334. text-align: center;
  1335. margin-bottom: 30px;
  1336. padding-bottom: 15px;
  1337. border-bottom: 2px solid #333;
  1338. }
  1339. .paper-title {
  1340. font-size: 24px;
  1341. font-weight: bold;
  1342. margin-bottom: 10px;
  1343. }
  1344. .paper-info {
  1345. font-size: 14px;
  1346. color: #666;
  1347. }
  1348. .question {
  1349. margin-bottom: 30px;
  1350. padding: 20px;
  1351. border: 1px solid #ddd;
  1352. border-radius: 5px;
  1353. }
  1354. .question-number {
  1355. font-weight: bold;
  1356. margin-bottom: 10px;
  1357. }
  1358. .question-stem {
  1359. margin-bottom: 15px;
  1360. }
  1361. .options {
  1362. list-style: none;
  1363. margin-left: 20px;
  1364. }
  1365. .options li {
  1366. margin-bottom: 8px;
  1367. }
  1368. .answer-section {
  1369. margin-top: 20px;
  1370. padding-top: 15px;
  1371. border-top: 1px solid #eee;
  1372. }
  1373. .answer-label {
  1374. font-weight: bold;
  1375. color: #d9534f;
  1376. }
  1377. .solution {
  1378. margin-top: 10px;
  1379. padding: 10px;
  1380. background: #f5f5f5;
  1381. border-left: 4px solid #5bc0de;
  1382. }
  1383. ';
  1384. }
  1385. /**
  1386. * 构建知识点名称映射
  1387. */
  1388. private function buildKnowledgePointNameMap(): array
  1389. {
  1390. try {
  1391. $options = $this->questionServiceApi->getKnowledgePointOptions();
  1392. return $options ?: [];
  1393. } catch (\Throwable $e) {
  1394. Log::warning('ExamPdfExportService: 获取知识点名称失败', [
  1395. 'error' => $e->getMessage(),
  1396. ]);
  1397. return [];
  1398. }
  1399. }
  1400. /**
  1401. * 构建掌握度摘要
  1402. */
  1403. private function buildMasterySummary(array $masteryData, array $kpNameMap): array
  1404. {
  1405. Log::info('ExamPdfExportService: buildMasterySummary开始处理', [
  1406. 'masteryData_count' => count($masteryData),
  1407. 'kpNameMap_count' => count($kpNameMap)
  1408. ]);
  1409. $items = [];
  1410. $total = 0;
  1411. $count = 0;
  1412. foreach ($masteryData as $row) {
  1413. $code = $row['kp_code'] ?? null;
  1414. // 【修复】使用kpNameMap转换名称为友好显示名
  1415. $name = $kpNameMap[$code] ?? $row['kp_name'] ?? $code ?: '未知知识点';
  1416. $level = (float)($row['mastery_level'] ?? 0);
  1417. $delta = $row['mastery_change'] ?? null;
  1418. $items[] = [
  1419. 'kp_code' => $code,
  1420. 'kp_name' => $name,
  1421. 'mastery_level' => $level,
  1422. 'mastery_change' => $delta,
  1423. ];
  1424. $total += $level;
  1425. $count++;
  1426. }
  1427. $average = $count > 0 ? round($total / $count, 2) : null;
  1428. // 按掌握度从低到高排序
  1429. if (!empty($items)) {
  1430. usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  1431. }
  1432. $result = [
  1433. 'items' => $items,
  1434. 'average' => $average,
  1435. 'weak_list' => array_slice($items, 0, 5),
  1436. ];
  1437. Log::info('ExamPdfExportService: buildMasterySummary完成', [
  1438. 'total_count' => $count,
  1439. 'items_count' => count($items)
  1440. ]);
  1441. return $result;
  1442. }
  1443. /**
  1444. * 标准化题型
  1445. */
  1446. private function normalizeQuestionType(string $type): string
  1447. {
  1448. $t = strtolower(trim($type));
  1449. return match (true) {
  1450. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  1451. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  1452. default => 'answer',
  1453. };
  1454. }
  1455. /**
  1456. * 保存PDF URL到数据库
  1457. */
  1458. private function savePdfUrlToDatabase(string $paperId, string $field, string $url): void
  1459. {
  1460. try {
  1461. $paper = Paper::where('paper_id', $paperId)->first();
  1462. if ($paper) {
  1463. $paper->update([$field => $url]);
  1464. Log::info('ExamPdfExportService: PDF URL已写入数据库', [
  1465. 'paper_id' => $paperId,
  1466. 'field' => $field,
  1467. 'url' => $url,
  1468. ]);
  1469. }
  1470. } catch (\Throwable $e) {
  1471. Log::error('ExamPdfExportService: 写入PDF URL失败', [
  1472. 'paper_id' => $paperId,
  1473. 'field' => $field,
  1474. 'error' => $e->getMessage(),
  1475. ]);
  1476. }
  1477. }
  1478. /**
  1479. * 保存学情分析PDF URL
  1480. */
  1481. private function saveAnalysisPdfUrl(string $paperId, string $studentId, ?string $recordId, string $url): void
  1482. {
  1483. try {
  1484. if ($recordId) {
  1485. // OCR记录
  1486. $ocrRecord = \App\Models\OCRRecord::find($recordId);
  1487. if ($ocrRecord) {
  1488. $ocrRecord->update(['analysis_pdf_url' => $url]);
  1489. Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
  1490. 'record_id' => $recordId,
  1491. 'paper_id' => $paperId,
  1492. 'student_id' => $studentId,
  1493. 'url' => $url,
  1494. ]);
  1495. }
  1496. } else {
  1497. // 【修复】同时更新 exam_analysis_results 表和分析报告表
  1498. $updated = \DB::connection('mysql')->table('exam_analysis_results')
  1499. ->where('student_id', $studentId)
  1500. ->where('paper_id', $paperId)
  1501. ->update([
  1502. 'analysis_pdf_url' => $url,
  1503. 'updated_at' => now(),
  1504. ]);
  1505. if ($updated) {
  1506. Log::info('ExamPdfExportService: 学情分析PDF URL已写入exam_analysis_results表', [
  1507. 'student_id' => $studentId,
  1508. 'paper_id' => $paperId,
  1509. 'url' => $url,
  1510. 'updated_rows' => $updated,
  1511. ]);
  1512. } else {
  1513. Log::warning('ExamPdfExportService: 未找到要更新的学情分析记录', [
  1514. 'student_id' => $studentId,
  1515. 'paper_id' => $paperId,
  1516. ]);
  1517. }
  1518. // 学生记录 - 使用新的 student_reports 表(备用)
  1519. \App\Models\StudentReport::updateOrCreate(
  1520. [
  1521. 'student_id' => $studentId,
  1522. 'report_type' => 'exam_analysis',
  1523. 'paper_id' => $paperId,
  1524. ],
  1525. [
  1526. 'pdf_url' => $url,
  1527. 'generation_status' => 'completed',
  1528. 'generated_at' => now(),
  1529. 'updated_at' => now(),
  1530. ]
  1531. );
  1532. Log::info('ExamPdfExportService: 学生学情报告PDF URL已保存到student_reports表(备用)', [
  1533. 'student_id' => $studentId,
  1534. 'paper_id' => $paperId,
  1535. 'url' => $url,
  1536. ]);
  1537. }
  1538. } catch (\Throwable $e) {
  1539. Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
  1540. 'paper_id' => $paperId,
  1541. 'student_id' => $studentId,
  1542. 'record_id' => $recordId,
  1543. 'error' => $e->getMessage(),
  1544. ]);
  1545. }
  1546. }
  1547. /**
  1548. * 【修复】处理父节点掌握度数据
  1549. * 1. 过滤掉掌握度为0或null的父节点
  1550. * 2. 将kp_code转换为友好的kp_name
  1551. * 3. 构建父子层级关系(只显示本次考试相关的子节点)
  1552. */
  1553. private function processParentMasteryLevels(array $parentMasteryLevels, array $kpNameMap, array $examKpCodes = []): array
  1554. {
  1555. $processed = [];
  1556. foreach ($parentMasteryLevels as $kpCode => $masteryData) {
  1557. // 兼容不同数据结构:可能是数组或数字
  1558. $masteryLevel = is_array($masteryData) ? ($masteryData['mastery_level'] ?? 0) : $masteryData;
  1559. $masteryChange = is_array($masteryData) ? ($masteryData['mastery_change'] ?? null) : null;
  1560. // 过滤零值和空值
  1561. if ($masteryLevel === null || $masteryLevel === 0.0 || $masteryLevel <= 0.001) {
  1562. continue;
  1563. }
  1564. // 获取友好名称
  1565. $kpName = $kpNameMap[$kpCode] ?? $kpCode;
  1566. // 构建父节点数据,包含子节点信息(只显示本次考试相关的)
  1567. $processed[$kpCode] = [
  1568. 'kp_code' => $kpCode,
  1569. 'kp_name' => $kpName,
  1570. 'mastery_level' => round(floatval($masteryLevel), 4),
  1571. 'mastery_percentage' => round(floatval($masteryLevel) * 100, 2),
  1572. 'mastery_change' => $masteryChange !== null ? round(floatval($masteryChange), 4) : null,
  1573. // 【修复】只获取本次考试涉及的子节点
  1574. 'children' => $this->getChildKnowledgePoints($kpCode, $kpNameMap, $examKpCodes),
  1575. 'level' => $this->calculateKnowledgePointLevel($kpCode),
  1576. ];
  1577. }
  1578. // 按掌握度降序排序
  1579. uasort($processed, function($a, $b) {
  1580. return $b['mastery_level'] <=> $a['mastery_level'];
  1581. });
  1582. return $processed;
  1583. }
  1584. /**
  1585. * 【修复】获取子知识点列表(只返回本次考试涉及的)
  1586. */
  1587. private function getChildKnowledgePoints(string $parentKpCode, array $kpNameMap, array $examKpCodes = []): array
  1588. {
  1589. $children = [];
  1590. try {
  1591. $childCodes = DB::connection('mysql')
  1592. ->table('knowledge_points')
  1593. ->where('parent_kp_code', $parentKpCode)
  1594. ->pluck('kp_code')
  1595. ->toArray();
  1596. foreach ($childCodes as $childCode) {
  1597. // 只包含本次考试涉及的知识点
  1598. if (in_array($childCode, $examKpCodes)) {
  1599. $children[] = [
  1600. 'kp_code' => $childCode,
  1601. 'kp_name' => $kpNameMap[$childCode] ?? $childCode,
  1602. ];
  1603. }
  1604. }
  1605. } catch (\Exception $e) {
  1606. Log::warning('获取子知识点失败', [
  1607. 'parent_kp_code' => $parentKpCode,
  1608. 'error' => $e->getMessage(),
  1609. ]);
  1610. }
  1611. return $children;
  1612. }
  1613. /**
  1614. * 计算知识点层级深度
  1615. */
  1616. private function calculateKnowledgePointLevel(string $kpCode): int
  1617. {
  1618. // 根据kp_code前缀判断层级深度
  1619. // 例如: M (1级) -> M01 (2级) -> M01A (3级)
  1620. if (preg_match('/^[A-Z]+$/', $kpCode)) {
  1621. return 1; // 一级分类,如 M, S, E, G
  1622. } elseif (preg_match('/^[A-Z]+\d+$/', $kpCode)) {
  1623. return 2; // 二级分类,如 M01, S02
  1624. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+$/', $kpCode)) {
  1625. return 3; // 三级分类,如 M01A, S02B
  1626. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+\d+$/', $kpCode)) {
  1627. return 4; // 四级分类,如 M01A1
  1628. }
  1629. return 1; // 默认一级
  1630. }
  1631. /**
  1632. * 构建题目数据(用于PDF生成)
  1633. */
  1634. private function buildQuestionsData(Paper $paper): array
  1635. {
  1636. $paperQuestions = $paper->questions()->orderBy('question_number')->get();
  1637. $questionsData = [];
  1638. foreach ($paperQuestions as $pq) {
  1639. $questionsData[] = [
  1640. 'id' => $pq->question_bank_id,
  1641. 'kp_code' => $pq->knowledge_point,
  1642. 'question_type' => $pq->question_type ?? 'answer',
  1643. 'stem' => $pq->question_text ?? '题目内容缺失',
  1644. 'solution' => $pq->solution ?? '',
  1645. 'answer' => $pq->correct_answer ?? '',
  1646. 'difficulty' => $pq->difficulty ?? 0.5,
  1647. 'score' => $pq->score ?? 5,
  1648. 'tags' => '',
  1649. 'content' => $pq->question_text ?? '',
  1650. ];
  1651. }
  1652. // 获取完整题目详情
  1653. if (!empty($questionsData)) {
  1654. $questionIds = array_column($questionsData, 'id');
  1655. $questionsResponse = $this->questionServiceApi->getQuestionsByIds($questionIds);
  1656. $responseData = $questionsResponse['data'] ?? [];
  1657. if (!empty($responseData)) {
  1658. $responseDataMap = [];
  1659. foreach ($responseData as $respQ) {
  1660. $responseDataMap[$respQ['id']] = $respQ;
  1661. }
  1662. $questionsData = array_map(function($q) use ($responseDataMap) {
  1663. if (isset($responseDataMap[$q['id']])) {
  1664. $apiData = $responseDataMap[$q['id']];
  1665. $q['stem'] = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  1666. $q['content'] = $q['stem'];
  1667. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  1668. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  1669. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  1670. $q['options'] = $apiData['options'] ?? [];
  1671. }
  1672. return $q;
  1673. }, $questionsData);
  1674. }
  1675. }
  1676. // 按题型分类
  1677. $classified = ['choice' => [], 'fill' => [], 'answer' => []];
  1678. foreach ($questionsData as $q) {
  1679. $type = $this->determineQuestionType($q);
  1680. $classified[$type][] = (object) $q;
  1681. }
  1682. return $classified;
  1683. }
  1684. /**
  1685. * 获取学生信息
  1686. */
  1687. private function getStudentInfo(?string $studentId): array
  1688. {
  1689. if (!$studentId) {
  1690. return [
  1691. 'name' => '未知学生',
  1692. 'grade' => '未知年级',
  1693. 'class' => '未知班级'
  1694. ];
  1695. }
  1696. try {
  1697. $student = DB::table('students')
  1698. ->where('student_id', $studentId)
  1699. ->first();
  1700. if ($student) {
  1701. return [
  1702. 'name' => $student->name ?? $studentId,
  1703. 'grade' => $student->grade ?? '未知',
  1704. 'class' => $student->class ?? '未知'
  1705. ];
  1706. }
  1707. } catch (\Exception $e) {
  1708. Log::warning('获取学生信息失败', [
  1709. 'student_id' => $studentId,
  1710. 'error' => $e->getMessage()
  1711. ]);
  1712. }
  1713. return [
  1714. 'name' => $studentId,
  1715. 'grade' => '未知',
  1716. 'class' => '未知'
  1717. ];
  1718. }
  1719. /**
  1720. * 获取教师信息
  1721. */
  1722. private function getTeacherInfo(?string $teacherId): array
  1723. {
  1724. if (!$teacherId) {
  1725. return [
  1726. 'name' => '未知老师',
  1727. 'subject' => '数学'
  1728. ];
  1729. }
  1730. try {
  1731. $teacher = DB::table('teachers')
  1732. ->where('teacher_id', $teacherId)
  1733. ->first();
  1734. if ($teacher) {
  1735. return [
  1736. 'name' => $teacher->name ?? $teacherId,
  1737. 'subject' => $teacher->subject ?? '数学'
  1738. ];
  1739. }
  1740. } catch (\Exception $e) {
  1741. Log::warning('获取教师信息失败', [
  1742. 'teacher_id' => $teacherId,
  1743. 'error' => $e->getMessage()
  1744. ]);
  1745. }
  1746. return [
  1747. 'name' => $teacherId,
  1748. 'subject' => '数学'
  1749. ];
  1750. }
  1751. /**
  1752. * 判断题目类型
  1753. */
  1754. private function determineQuestionType(array $question): string
  1755. {
  1756. $stem = $question['stem'] ?? $question['content'] ?? '';
  1757. $tags = $question['tags'] ?? '';
  1758. // 根据题干内容判断选择题
  1759. if (is_string($stem)) {
  1760. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  1761. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  1762. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  1763. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  1764. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0);
  1765. if ($optionCount >= 2) {
  1766. return 'choice';
  1767. }
  1768. // 检查是否有填空标记
  1769. if (preg_match('/(\s*)|\(\s*\)/', $stem)) {
  1770. return 'fill';
  1771. }
  1772. }
  1773. // 根据已有类型字段判断
  1774. if (!empty($question['question_type'])) {
  1775. $type = strtolower(trim($question['question_type']));
  1776. if (in_array($type, ['choice', '选择题'])) return 'choice';
  1777. if (in_array($type, ['fill', '填空题'])) return 'fill';
  1778. if (in_array($type, ['answer', '解答题'])) return 'answer';
  1779. }
  1780. // 默认返回解答题
  1781. return 'answer';
  1782. }
  1783. /**
  1784. * 格式化换行符:将字面的 \n 转换为 HTML <br> 标签
  1785. * 用于 PDF 渲染时正确显示换行
  1786. */
  1787. private function formatNewlines(?string $text): ?string
  1788. {
  1789. if ($text === null) {
  1790. return null;
  1791. }
  1792. // 先处理 \n\n(双换行),再处理 \n(单换行)
  1793. return str_replace(['\\n\\n', '\\n'], ['<br><br>', '<br>'], $text);
  1794. }
  1795. }