ExamPdfExportService.php 138 KB

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