ExamPdfExportService.php 165 KB

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