ExamPdfExportService.php 120 KB

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