ExamPdfExportService.php 91 KB

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