ExamPdfExportService.php 96 KB

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