ExamPdfExportService.php 212 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588
  1. <?php
  2. namespace App\Services;
  3. use App\DTO\ExamAnalysisDataDto;
  4. use App\DTO\ReportPayloadDto;
  5. use App\Http\Controllers\ExamPdfController;
  6. use App\Models\Paper;
  7. use App\Models\Question;
  8. use App\Models\Student;
  9. use App\Services\Analytics\QuestionDifficultyCalibrationAnalyzer;
  10. use App\Support\GradingStyleQuestionStem;
  11. use App\Support\PaperNaming;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Cache;
  14. use Illuminate\Support\Facades\File;
  15. use Illuminate\Support\Facades\Http;
  16. use Illuminate\Support\Facades\Log;
  17. use Illuminate\Support\Facades\Schema;
  18. use Illuminate\Support\Facades\Storage;
  19. use Illuminate\Support\Facades\URL;
  20. use Illuminate\Http\Request;
  21. use Illuminate\Support\Str;
  22. use Symfony\Component\Process\Exception\ProcessSignaledException;
  23. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  24. use Symfony\Component\Process\Process;
  25. /**
  26. * PDF导出服务(重构版)
  27. * 负责生成试卷PDF、判卷PDF和学情报告PDF
  28. */
  29. class ExamPdfExportService
  30. {
  31. private ?KatexRenderer $katexRenderer = null;
  32. private const PDF_IMAGE_WIDTH_WIDE_PX = 250;
  33. private const PDF_IMAGE_WIDTH_VERY_WIDE_PX = 330;
  34. private const KNOWLEDGE_POINTS_CACHE_TTL_SECONDS = 86400 * 3;
  35. private const KNOWLEDGE_POINTS_VERSION_TTL_SECONDS = 600;
  36. /**
  37. * @var array<string, array{w:int,h:int}|null>
  38. */
  39. private array $pdfImageDimensionCache = [];
  40. private ?bool $hasPdfImageMetricsTable = null;
  41. private array $knowledgePointMetaCache = [];
  42. private ?string $lastDebugHtmlPath = null;
  43. public function __construct(
  44. private readonly LearningAnalyticsService $learningAnalyticsService,
  45. private readonly QuestionBankService $questionBankService,
  46. private readonly QuestionServiceApi $questionServiceApi,
  47. private readonly PdfStorageService $pdfStorageService,
  48. private readonly MasteryCalculator $masteryCalculator,
  49. private readonly PdfMerger $pdfMerger
  50. ) {
  51. // 延迟初始化 KatexRenderer(避免循环依赖)
  52. $this->katexRenderer = new KatexRenderer;
  53. }
  54. /**
  55. * 生成试卷 PDF(不含答案)
  56. */
  57. public function generateExamPdf(string $paperId): ?string
  58. {
  59. Log::info('generateExamPdf 开始:', ['paper_id' => $paperId]);
  60. $url = $this->renderAndStoreExamPdf($paperId, includeAnswer: false, suffix: 'exam');
  61. Log::info('generateExamPdf url 生成结果:', ['paper_id' => $paperId, 'url' => $url]);
  62. // 如果生成成功,将 URL 写入数据库
  63. if ($url) {
  64. $this->savePdfUrlToDatabase($paperId, 'exam_pdf_url', $url);
  65. }
  66. return $url;
  67. }
  68. /**
  69. * 生成判卷 PDF(含答案与解析)
  70. */
  71. public function generateGradingPdf(string $paperId): ?string
  72. {
  73. Log::info('generateGradingPdf 开始:', ['paper_id' => $paperId]);
  74. $url = $this->renderAndStoreExamPdf($paperId, includeAnswer: true, suffix: 'grading', useGradingView: true);
  75. Log::info('generateGradingPdf url 生成结果:', ['paper_id' => $paperId, 'url' => $url]);
  76. // 如果生成成功,将 URL 写入数据库
  77. if ($url) {
  78. $this->savePdfUrlToDatabase($paperId, 'grading_pdf_url', $url);
  79. }
  80. return $url;
  81. }
  82. /**
  83. * 渲染试卷 HTML → 生成 PDF → 上传存储(generateExamPdf / generateGradingPdf 共用)
  84. */
  85. private function renderAndStoreExamPdf(string $paperId, bool $includeAnswer, string $suffix, bool $useGradingView = false): ?string
  86. {
  87. $html = $this->renderExamHtml($paperId, $includeAnswer, $useGradingView);
  88. if ($html === null || trim($html) === '') {
  89. Log::error('renderAndStoreExamPdf: HTML 为空', [
  90. 'paper_id' => $paperId,
  91. 'suffix' => $suffix,
  92. ]);
  93. return null;
  94. }
  95. $pdfBinary = $this->buildPdf($html, ! $includeAnswer && ! $useGradingView);
  96. if ($pdfBinary === null || $pdfBinary === '') {
  97. Log::error('renderAndStoreExamPdf: buildPdf 失败', [
  98. 'paper_id' => $paperId,
  99. 'suffix' => $suffix,
  100. ]);
  101. return null;
  102. }
  103. $paper = Paper::query()->where('paper_id', $paperId)->first();
  104. if (! $paper) {
  105. Log::error('renderAndStoreExamPdf: 试卷不存在', ['paper_id' => $paperId]);
  106. return null;
  107. }
  108. $stamp = now()->format('YmdHis').strtoupper(Str::random(4));
  109. $base = $this->buildPaperNamePrefix($paper).'_'.$suffix.'_'.$stamp;
  110. $safe = PaperNaming::toSafeFilename($base).'.pdf';
  111. $path = 'exams/'.$safe;
  112. $url = $this->pdfStorageService->put($path, $pdfBinary);
  113. if (! $url) {
  114. Log::error('renderAndStoreExamPdf: 上传失败', ['paper_id' => $paperId, 'path' => $path]);
  115. return null;
  116. }
  117. Log::info('renderAndStoreExamPdf: 完成', [
  118. 'paper_id' => $paperId,
  119. 'suffix' => $suffix,
  120. 'url' => $url,
  121. ]);
  122. return $url;
  123. }
  124. /**
  125. * 【优化方案】生成统一PDF(卷子 + 判卷一页完成)
  126. * 效率提升40-50%,只需生成一次PDF
  127. *
  128. * @param string $paperId 试卷ID
  129. * @return string|null PDF URL
  130. */
  131. public function generateUnifiedPdf(string $paperId): ?string
  132. {
  133. $flowStart = microtime(true);
  134. $lastMark = $flowStart;
  135. $timings = [];
  136. $mark = static function (string $label) use (&$lastMark, &$timings): void {
  137. $now = microtime(true);
  138. $timings[$label] = round(($now - $lastMark) * 1000, 1);
  139. $lastMark = $now;
  140. };
  141. // 与组卷规则保持一致:仅知识点组卷类型(paper_type=2)包含知识点讲解。
  142. $paperType = Paper::query()
  143. ->where('paper_id', $paperId)
  144. ->value('paper_type');
  145. $shouldIncludeKpExplain = ((int) $paperType) === 2;
  146. $mark('load_paper_type_ms');
  147. Log::info('generateUnifiedPdf 开始(终极优化版本,直接HTML合并生成PDF):', [
  148. 'paper_id' => $paperId,
  149. 'has_kp_explain' => $shouldIncludeKpExplain,
  150. ]);
  151. try {
  152. $totalStartedAt = microtime(true);
  153. // 步骤0:获取知识点讲解HTML(如需要)
  154. $kpExplainHtml = null;
  155. if ($shouldIncludeKpExplain) {
  156. $kpStartedAt = microtime(true);
  157. Log::info('generateUnifiedPdf: 开始获取知识点讲解HTML', ['paper_id' => $paperId]);
  158. $kpExplainHtml = $this->fetchKnowledgeExplanationHtml($paperId);
  159. $mark('kp_explain_html_ms');
  160. if ($kpExplainHtml) {
  161. // 统一在 mergeHtmlWithPageBreak()->ensureUtf8Html() 阶段处理内联与公式预渲染,
  162. // 避免在此处重复处理导致额外耗时。
  163. Log::info('generateUnifiedPdf: 知识点讲解HTML获取并处理成功', [
  164. 'paper_id' => $paperId,
  165. 'length' => strlen($kpExplainHtml),
  166. 'elapsed_ms' => (int) round((microtime(true) - $kpStartedAt) * 1000),
  167. ]);
  168. } else {
  169. Log::warning('generateUnifiedPdf: 知识点讲解HTML获取失败,将跳过', ['paper_id' => $paperId]);
  170. }
  171. } else {
  172. $timings['kp_explain_html_ms'] = 0.0;
  173. }
  174. // 步骤1:同时渲染两个页面的HTML
  175. $examRenderStartedAt = microtime(true);
  176. Log::info('generateUnifiedPdf: 开始渲染试卷HTML', ['paper_id' => $paperId]);
  177. $examHtml = $this->renderExamHtml($paperId, includeAnswer: false, useGradingView: false);
  178. $mark('exam_html_ms');
  179. if (! $examHtml) {
  180. Log::error('ExamPdfExportService: 渲染卷子HTML失败', ['paper_id' => $paperId]);
  181. return null;
  182. }
  183. Log::info('generateUnifiedPdf: 试卷HTML渲染完成', [
  184. 'paper_id' => $paperId,
  185. 'length' => strlen($examHtml),
  186. 'elapsed_ms' => (int) round((microtime(true) - $examRenderStartedAt) * 1000),
  187. ]);
  188. $gradingRenderStartedAt = microtime(true);
  189. Log::info('generateUnifiedPdf: 开始渲染判卷HTML', ['paper_id' => $paperId]);
  190. $gradingHtml = $this->renderExamHtml($paperId, includeAnswer: true, useGradingView: true);
  191. $mark('grading_html_ms');
  192. if (! $gradingHtml) {
  193. Log::error('ExamPdfExportService: 渲染判卷HTML失败', ['paper_id' => $paperId]);
  194. return null;
  195. }
  196. Log::info('generateUnifiedPdf: 判卷HTML渲染完成', [
  197. 'paper_id' => $paperId,
  198. 'length' => strlen($gradingHtml),
  199. 'elapsed_ms' => (int) round((microtime(true) - $gradingRenderStartedAt) * 1000),
  200. ]);
  201. // 步骤2:插入分页符,合并HTML
  202. $mergeStartedAt = microtime(true);
  203. Log::info('generateUnifiedPdf: 开始合并HTML(保留原始样式)', ['paper_id' => $paperId]);
  204. $unifiedHtml = $this->mergeHtmlWithPageBreak($examHtml, $gradingHtml, $kpExplainHtml);
  205. $mark('merge_html_ms');
  206. if (! $unifiedHtml) {
  207. Log::error('ExamPdfExportService: HTML合并失败', ['paper_id' => $paperId]);
  208. return null;
  209. }
  210. Log::info('generateUnifiedPdf: HTML合并完成(将直接生成PDF,不使用pdfunite)', [
  211. 'paper_id' => $paperId,
  212. 'length' => strlen($unifiedHtml),
  213. 'has_kp_explain' => ! empty($kpExplainHtml),
  214. 'elapsed_ms' => (int) round((microtime(true) - $mergeStartedAt) * 1000),
  215. ]);
  216. // 步骤3:一次性生成PDF(只需20-25秒,比原来节省10-25秒)
  217. $pdfRenderStartedAt = microtime(true);
  218. Log::info('generateUnifiedPdf: 开始使用buildPdf直接生成PDF(不使用pdfunite)', ['paper_id' => $paperId]);
  219. $this->lastDebugHtmlPath = null;
  220. $pdfBinary = $this->buildPdf($unifiedHtml, true, true);
  221. $mark('build_pdf_ms');
  222. if (! $pdfBinary) {
  223. Log::error('ExamPdfExportService: 生成统一PDF失败', ['paper_id' => $paperId]);
  224. return null;
  225. }
  226. Log::info('generateUnifiedPdf: PDF生成完成', [
  227. 'paper_id' => $paperId,
  228. 'pdf_size' => strlen($pdfBinary),
  229. 'elapsed_ms' => (int) round((microtime(true) - $pdfRenderStartedAt) * 1000),
  230. ]);
  231. // 步骤4:保存PDF
  232. $paper = Paper::where('paper_id', $paperId)->first();
  233. if (! $paper) {
  234. Log::error('ExamPdfExportService: 生成统一PDF失败,未找到试卷', ['paper_id' => $paperId]);
  235. return null;
  236. }
  237. $allPdfName = $this->buildPdfFileName($paper);
  238. $path = "exams/{$allPdfName}";
  239. $storageStartedAt = microtime(true);
  240. Log::info('generateUnifiedPdf: 开始保存PDF到云存储', ['paper_id' => $paperId, 'path' => $path]);
  241. $url = $this->pdfStorageService->put($path, $pdfBinary);
  242. $mark('upload_pdf_ms');
  243. if (! $url) {
  244. Log::error('ExamPdfExportService: 保存统一PDF失败', ['path' => $path]);
  245. return null;
  246. }
  247. Log::info('generateUnifiedPdf: PDF保存完成', [
  248. 'paper_id' => $paperId,
  249. 'url' => $url,
  250. 'elapsed_ms' => (int) round((microtime(true) - $storageStartedAt) * 1000),
  251. ]);
  252. // 步骤5:保存URL到数据库(存储到all_pdf_url字段)
  253. Log::info('generateUnifiedPdf: 开始保存URL到数据库', ['paper_id' => $paperId, 'field' => 'all_pdf_url']);
  254. $this->savePdfUrlToDatabase($paperId, 'all_pdf_url', $url);
  255. $mark('save_url_ms');
  256. Log::info('generateUnifiedPdf: URL保存完成', ['paper_id' => $paperId]);
  257. Log::warning('PDF_GENERATION_TIMING', [
  258. 'paper_id' => $paperId,
  259. 'paper_type' => (int) $paperType,
  260. 'has_kp_explain' => ! empty($kpExplainHtml),
  261. 'exam_html_bytes' => strlen($examHtml),
  262. 'grading_html_bytes' => strlen($gradingHtml),
  263. 'kp_explain_html_bytes' => $kpExplainHtml ? strlen($kpExplainHtml) : 0,
  264. 'unified_html_bytes' => strlen($unifiedHtml),
  265. 'pdf_bytes' => strlen($pdfBinary),
  266. 'timings_ms' => $timings,
  267. 'total_ms' => round((microtime(true) - $flowStart) * 1000, 1),
  268. 'debug_html_path' => $this->lastDebugHtmlPath,
  269. ]);
  270. Log::info('generateUnifiedPdf 全部完成(终极优化:直接HTML合并生成一份PDF)', [
  271. 'paper_id' => $paperId,
  272. 'url' => $url,
  273. 'pdf_size' => strlen($pdfBinary),
  274. 'method' => 'direct HTML merge to PDF (no pdfunite)',
  275. 'elapsed_ms' => (int) round((microtime(true) - $totalStartedAt) * 1000),
  276. ]);
  277. return $url;
  278. } catch (\Throwable $e) {
  279. Log::error('generateUnifiedPdf 失败', [
  280. 'paper_id' => $paperId,
  281. 'error' => $e->getMessage(),
  282. 'trace' => $e->getTraceAsString(),
  283. ]);
  284. return null;
  285. }
  286. }
  287. /**
  288. * 生成学情分析 PDF
  289. */
  290. public function generateAnalysisReportPdf(string $paperId, string $studentId, ?string $recordId = null): ?string
  291. {
  292. if (function_exists('set_time_limit')) {
  293. @set_time_limit(240);
  294. }
  295. try {
  296. $flowStart = microtime(true);
  297. $lastMark = $flowStart;
  298. $marks = [];
  299. $mark = static function (string $label) use (&$lastMark, &$marks): void {
  300. $now = microtime(true);
  301. $marks[$label] = round(($now - $lastMark) * 1000, 1);
  302. $lastMark = $now;
  303. };
  304. // 构建分析数据
  305. $analysisData = $this->buildAnalysisData($paperId, $studentId);
  306. $mark('build_analysis_data_ms');
  307. if (! $analysisData) {
  308. Log::warning('ExamPdfExportService: buildAnalysisData返回空数据', [
  309. 'paper_id' => $paperId,
  310. 'student_id' => $studentId,
  311. ]);
  312. return null;
  313. }
  314. // 创建DTO
  315. $dto = ExamAnalysisDataDto::fromArray($analysisData);
  316. $payloadDto = ReportPayloadDto::fromExamAnalysisDataDto($dto);
  317. $mark('build_payload_dto_ms');
  318. $templateData = $this->reduceTemplateDataForV3($payloadDto->toArray());
  319. unset($analysisData, $dto, $payloadDto);
  320. if (function_exists('gc_collect_cycles')) {
  321. gc_collect_cycles();
  322. }
  323. // V3 学情报告不再渲染逐题错题卡,保留题目元数据用于统计即可。
  324. $mark('prepare_report_data_ms');
  325. // 组装V3报告展示数据(模块化)
  326. $templateData['v3'] = $this->buildAnalysisReportV3Data($templateData);
  327. $mark('build_v3_data_ms');
  328. // 渲染HTML(V3模板)
  329. $html = view('exam-analysis.pdf-report-v3', $templateData)->render();
  330. $mark('render_html_ms');
  331. if (! $html) {
  332. Log::error('ExamPdfExportService: 渲染HTML为空', ['paper_id' => $paperId]);
  333. return null;
  334. }
  335. // 生成PDF
  336. $pdfBinary = $this->buildPdf($html);
  337. $mark('build_pdf_ms');
  338. if (! $pdfBinary) {
  339. return null;
  340. }
  341. // 保存PDF(命名统一:姓名_分析报告_卷子id_卷子类型_时间戳)
  342. $studentName = (string) ($templateData['student']['name'] ?? $studentId);
  343. $paperCode = PaperNaming::extractExamCode((string) ($templateData['paper']['id'] ?? $paperId));
  344. $assembleTypeLabel = (string) ($templateData['paper']['assemble_type_label'] ?? '未知类型');
  345. $stamp = now()->format('YmdHis') . strtoupper(Str::random(4));
  346. $analysisBase = "{$studentName}_分析报告_{$paperCode}_{$assembleTypeLabel}_{$stamp}";
  347. $safeAnalysisFile = PaperNaming::toSafeFilename($analysisBase) . '.pdf';
  348. $path = "analysis_reports/{$safeAnalysisFile}";
  349. $url = $this->pdfStorageService->put($path, $pdfBinary);
  350. $mark('upload_pdf_ms');
  351. if (! $url) {
  352. Log::error('ExamPdfExportService: 保存学情PDF失败', ['path' => $path]);
  353. return null;
  354. }
  355. // 保存URL到数据库
  356. $this->saveAnalysisPdfUrl($paperId, $studentId, $recordId, $url);
  357. $mark('save_pdf_url_ms');
  358. $marks['total_ms'] = round((microtime(true) - $flowStart) * 1000, 1);
  359. Log::warning('ExamPdfExportService: 学情分析PDF耗时明细', [
  360. 'paper_id' => $paperId,
  361. 'student_id' => $studentId,
  362. 'record_id' => $recordId,
  363. 'timing' => $marks,
  364. ]);
  365. return $url;
  366. } catch (\Throwable $e) {
  367. Log::error('ExamPdfExportService: 生成学情分析PDF失败', [
  368. 'paper_id' => $paperId,
  369. 'student_id' => $studentId,
  370. 'record_id' => $recordId,
  371. 'error' => $e->getMessage(),
  372. 'exception' => get_class($e),
  373. 'trace' => $e->getTraceAsString(),
  374. ]);
  375. return null;
  376. }
  377. }
  378. /**
  379. * 构建学情报告 V3 展示数据(模块化视图)
  380. */
  381. private function buildAnalysisReportV3Data(array $templateData): array
  382. {
  383. $rawAnalysis = $templateData['analysis_data'] ?? [];
  384. $kpRows = $rawAnalysis['knowledge_point_analysis'] ?? [];
  385. $questionRows = $rawAnalysis['question_analysis'] ?? [];
  386. $overallSummary = $rawAnalysis['overall_summary'] ?? [];
  387. $grade = (string) ($templateData['student']['grade'] ?? '');
  388. $stage = $this->resolveRadarStage($grade, $templateData['full_parent_mastery_levels'] ?? []);
  389. $profile = $this->getRadarProfileByStage($stage);
  390. $rootCode = (string) ($profile['root_code'] ?? 'M00');
  391. $moduleCodes = $profile['module_codes'] ?? [];
  392. $moduleNames = $profile['module_names'] ?? [];
  393. $kpMeta = $this->getKnowledgePointMetaMap($rootCode, $moduleCodes);
  394. $moduleAgg = [];
  395. foreach ($moduleCodes as $moduleCode) {
  396. $moduleAgg[$moduleCode] = [
  397. 'mastery_sum' => 0.0,
  398. 'mastery_count' => 0,
  399. 'question_max' => 0.0,
  400. 'question_obtained' => 0.0,
  401. 'question_count' => 0,
  402. ];
  403. }
  404. $fullParentMap = $templateData['full_parent_mastery_levels'] ?? [];
  405. if (! is_array($fullParentMap)) {
  406. $fullParentMap = [];
  407. }
  408. foreach ($kpRows as $row) {
  409. $kpId = trim((string) ($row['kp_id'] ?? ''));
  410. if ($kpId === '') {
  411. continue;
  412. }
  413. $moduleCode = $this->mapKpToStageModule($kpId, $kpMeta, $rootCode);
  414. if (! $moduleCode || ! isset($moduleAgg[$moduleCode])) {
  415. continue;
  416. }
  417. $mastery = (float) ($row['mastery_level'] ?? 0);
  418. $moduleAgg[$moduleCode]['mastery_sum'] += $mastery;
  419. $moduleAgg[$moduleCode]['mastery_count']++;
  420. }
  421. foreach ($questionRows as $questionRow) {
  422. $maxScore = (float) ($questionRow['max_score'] ?? 0);
  423. $obtainedScore = (float) ($questionRow['score_obtained'] ?? 0);
  424. if ($maxScore <= 0) {
  425. continue;
  426. }
  427. $kpId = '';
  428. $questionKps = $questionRow['knowledge_points'] ?? [];
  429. if (is_array($questionKps) && ! empty($questionKps)) {
  430. $first = $questionKps[0] ?? [];
  431. if (is_array($first)) {
  432. $kpId = trim((string) ($first['kp_id'] ?? ''));
  433. }
  434. }
  435. if ($kpId === '') {
  436. continue;
  437. }
  438. $moduleCode = $this->mapKpToStageModule($kpId, $kpMeta, $rootCode);
  439. if (! $moduleCode || ! isset($moduleAgg[$moduleCode])) {
  440. continue;
  441. }
  442. $moduleAgg[$moduleCode]['question_max'] += $maxScore;
  443. $moduleAgg[$moduleCode]['question_obtained'] += max(0.0, min($obtainedScore, $maxScore));
  444. $moduleAgg[$moduleCode]['question_count']++;
  445. }
  446. $moduleRows = [];
  447. foreach ($moduleCodes as $moduleCode) {
  448. $agg = $moduleAgg[$moduleCode] ?? null;
  449. $masteryLevel = null;
  450. $kpCount = 0;
  451. if (isset($fullParentMap[$moduleCode])) {
  452. $parentRow = $fullParentMap[$moduleCode];
  453. $masteryLevel = isset($parentRow['mastery_level']) ? (float) $parentRow['mastery_level'] : null;
  454. $kpCount = (int) ($parentRow['children_total_count'] ?? 0);
  455. }
  456. if ($masteryLevel === null && $agg && $agg['mastery_count'] > 0) {
  457. $masteryLevel = $agg['mastery_sum'] / $agg['mastery_count'];
  458. }
  459. $masteryScore5 = $masteryLevel !== null ? round($masteryLevel * 5, 2) : null;
  460. $examMax = (float) ($agg['question_max'] ?? 0.0);
  461. $examObtained = (float) ($agg['question_obtained'] ?? 0.0);
  462. $examRate = $examMax > 0 ? round($examObtained / $examMax, 4) : null;
  463. if ($kpCount <= 0) {
  464. $kpCount = (int) ($agg['mastery_count'] ?? 0);
  465. }
  466. $moduleRows[] = [
  467. 'module_code' => $moduleCode,
  468. 'module_name' => $moduleNames[$moduleCode] ?? $moduleCode,
  469. 'mastery_level' => $masteryLevel !== null ? round($masteryLevel, 4) : null,
  470. 'mastery_score_5' => $masteryScore5,
  471. 'status' => $this->resolveMasteryStatus($masteryLevel),
  472. 'kp_count' => $kpCount,
  473. 'question_count' => (int) ($agg['question_count'] ?? 0),
  474. 'exam_max_score' => round($examMax, 2),
  475. 'exam_obtained_score' => round($examObtained, 2),
  476. 'exam_score_rate' => $examRate,
  477. ];
  478. }
  479. $allMax = 0.0;
  480. $allObtained = 0.0;
  481. foreach ($moduleRows as $moduleRow) {
  482. $allMax += (float) ($moduleRow['exam_max_score'] ?? 0);
  483. $allObtained += (float) ($moduleRow['exam_obtained_score'] ?? 0);
  484. }
  485. $scoreRate = $allMax > 0 ? round($allObtained / $allMax, 4) : null;
  486. $avgMastery = isset($overallSummary['average_mastery'])
  487. ? (float) $overallSummary['average_mastery']
  488. : $this->averageByKey(array_filter($moduleRows, fn ($m) => $m['mastery_level'] !== null), 'mastery_level');
  489. $paths = $this->buildV3LearningPaths($moduleRows);
  490. $difficultyInsight = $this->buildV3DifficultyInsight($templateData);
  491. $comparisonInsight = $this->buildV3ComparisonInsight(
  492. $templateData,
  493. $scoreRate,
  494. $avgMastery
  495. );
  496. $fallbackOverallLabel = $overallSummary['overall_performance'] ?? $this->resolveOverallPerformanceLabel($avgMastery);
  497. $overallComposite = $this->buildV3OverallCompositeEvaluation(
  498. $scoreRate,
  499. $avgMastery,
  500. $difficultyInsight,
  501. $comparisonInsight,
  502. $fallbackOverallLabel
  503. );
  504. $overallLabel = (string) ($overallComposite['label'] ?? $fallbackOverallLabel);
  505. // 雷达图:轴固定为学段根节点的“第一层父知识点”(根节点的直接子节点)
  506. // 掌握度计算口径:严格沿用上一版父节点掌握度口径(full_parent_mastery_levels / parent_mastery_levels)。
  507. $radar = [];
  508. $hitParentMap = $templateData['parent_mastery_levels'] ?? [];
  509. if (! is_array($hitParentMap)) {
  510. $hitParentMap = [];
  511. }
  512. // 第二块聚类视图数据:严格按学段知识树叶子节点分组(与 math.client-pc 层级一致)
  513. $radarChildrenByModule = [];
  514. $examHitCodes = $templateData['exam_hit_kp_codes'] ?? [];
  515. if (! is_array($examHitCodes)) {
  516. $examHitCodes = [];
  517. }
  518. $examHitSet = array_fill_keys(array_map(static fn ($v) => (string) $v, $examHitCodes), true);
  519. $masteryMapForCluster = $templateData['mastery_map'] ?? [];
  520. if (! is_array($masteryMapForCluster)) {
  521. $masteryMapForCluster = [];
  522. }
  523. $kpChangeMap = [];
  524. foreach ($kpRows as $row) {
  525. $code = trim((string) ($row['kp_code'] ?? $row['knowledge_point_code'] ?? $row['code'] ?? ''));
  526. if ($code === '') {
  527. continue;
  528. }
  529. $changeRaw = $row['mastery_change'] ?? $row['change'] ?? null;
  530. if ($changeRaw === null || $changeRaw === '') {
  531. continue;
  532. }
  533. $kpChangeMap[$code] = (float) $changeRaw;
  534. }
  535. if (empty($kpChangeMap)) {
  536. $studentId = (string) ($templateData['student']['id'] ?? '');
  537. $paperId = (string) ($templateData['paper']['id'] ?? '');
  538. if ($studentId !== '' && $paperId !== '') {
  539. try {
  540. $snapshot = DB::connection('mysql')
  541. ->table('knowledge_point_mastery_snapshots')
  542. ->where('student_id', $studentId)
  543. ->where('paper_id', $paperId)
  544. ->latest('snapshot_time')
  545. ->first();
  546. if ($snapshot && ! empty($snapshot->mastery_data)) {
  547. $snapshotData = json_decode((string) $snapshot->mastery_data, true);
  548. if (is_array($snapshotData)) {
  549. foreach ($snapshotData as $kpCode => $node) {
  550. if (! is_array($node)) {
  551. continue;
  552. }
  553. $change = $node['change'] ?? null;
  554. if ($change === null && isset($node['current_mastery'], $node['previous_mastery'])) {
  555. $change = floatval($node['current_mastery']) - floatval($node['previous_mastery']);
  556. }
  557. if ($change === null || $change === '') {
  558. continue;
  559. }
  560. $code = trim((string) $kpCode);
  561. if ($code === '') {
  562. continue;
  563. }
  564. $kpChangeMap[$code] = (float) $change;
  565. }
  566. }
  567. }
  568. } catch (\Throwable $e) {
  569. Log::warning('ExamPdfExportService: 聚类变化值快照回填失败', [
  570. 'paper_id' => $paperId,
  571. 'student_id' => $studentId,
  572. 'error' => $e->getMessage(),
  573. ]);
  574. }
  575. }
  576. }
  577. $moduleSet = array_fill_keys(array_map(static fn ($code) => (string) $code, $moduleCodes), true);
  578. $stageCodes = [];
  579. foreach (array_keys($kpMeta) as $kpCode) {
  580. if ($kpCode === $rootCode || isset($moduleSet[$kpCode])) {
  581. continue;
  582. }
  583. $stageCodes[] = $kpCode;
  584. }
  585. $childrenByParent = [];
  586. foreach ($kpMeta as $code => $meta) {
  587. $p = trim((string) ($meta['parent_kp_code'] ?? ''));
  588. if ($p !== '') {
  589. $childrenByParent[$p][] = (string) $code;
  590. }
  591. }
  592. $expandedExamHitSet = $examHitSet;
  593. foreach (array_keys($examHitSet) as $hitCode) {
  594. foreach ($this->collectLeafDescendants($hitCode, $childrenByParent) as $leafCode) {
  595. $expandedExamHitSet[$leafCode] = true;
  596. }
  597. }
  598. $resolveHierarchyForCluster = function (string $kpId) use ($kpMeta, $rootCode): array {
  599. $rootName = trim((string) ($kpMeta[$rootCode]['name'] ?? $rootCode));
  600. $lineage = [];
  601. $cursor = $kpId;
  602. $guard = 0;
  603. while ($cursor !== '' && isset($kpMeta[$cursor]) && $guard < 24) {
  604. $nodeName = trim((string) ($kpMeta[$cursor]['name'] ?? $cursor));
  605. if ($nodeName !== '') {
  606. $lineage[] = $nodeName;
  607. }
  608. $parent = trim((string) ($kpMeta[$cursor]['parent_kp_code'] ?? ''));
  609. if ($parent === '' || $parent === $cursor || $parent === $rootCode) {
  610. break;
  611. }
  612. $cursor = $parent;
  613. $guard++;
  614. }
  615. $nonRootPath = array_reverse($lineage); // 等价前端去 root 后的路径
  616. $safePath = !empty($nonRootPath) ? $nonRootPath : [trim((string) ($kpMeta[$kpId]['name'] ?? $kpId))];
  617. $pathCount = count($safePath);
  618. $parentName = $safePath[$pathCount - 2] ?? $safePath[$pathCount - 1] ?? $rootName;
  619. $grandParentName = $safePath[$pathCount - 3] ?? $safePath[0] ?? $parentName;
  620. $greatGrandParentName = $safePath[$pathCount - 4] ?? $safePath[0] ?? $grandParentName;
  621. $path = implode(' > ', array_filter(array_merge([$rootName], $safePath)));
  622. return [
  623. 'parent_name' => $parentName,
  624. 'grand_parent_name' => $grandParentName,
  625. 'great_grand_parent_name' => $greatGrandParentName,
  626. 'path' => $path,
  627. ];
  628. };
  629. foreach ($stageCodes as $kpId) {
  630. $kpId = trim((string) $kpId);
  631. if ($kpId === '' || ! isset($kpMeta[$kpId])) {
  632. continue;
  633. }
  634. // 仅纳入叶子知识点,保证与前端 flattenKnowledgePoints 一致
  635. if (! empty($childrenByParent[$kpId] ?? [])) {
  636. continue;
  637. }
  638. $moduleCode = $this->mapKpToStageModule($kpId, $kpMeta, $rootCode);
  639. if (! $moduleCode || ! in_array($moduleCode, $moduleCodes, true)) {
  640. continue;
  641. }
  642. $parentCode = (string) ($kpMeta[$kpId]['parent_kp_code'] ?? '');
  643. $depth = $this->resolveDepthToModule($kpId, $moduleCode, $kpMeta);
  644. $hierarchy = $resolveHierarchyForCluster($kpId);
  645. $masteryValue = array_key_exists($kpId, $masteryMapForCluster)
  646. ? floatval($masteryMapForCluster[$kpId])
  647. : null;
  648. $changeValue = array_key_exists($kpId, $kpChangeMap)
  649. ? (float) $kpChangeMap[$kpId]
  650. : null;
  651. $isHit = isset($expandedExamHitSet[$kpId]);
  652. $radarChildrenByModule[$moduleCode][] = [
  653. 'code' => $kpId,
  654. 'name' => $kpMeta[$kpId]['name'] ?? $kpId,
  655. 'parent_code' => $parentCode,
  656. 'parent_name' => $hierarchy['parent_name'],
  657. 'grand_parent_name' => $hierarchy['grand_parent_name'],
  658. 'great_grand_parent_name' => $hierarchy['great_grand_parent_name'],
  659. 'path' => $hierarchy['path'],
  660. 'depth' => $depth,
  661. 'change' => $changeValue !== null ? round($changeValue, 4) : null,
  662. 'mastery_level' => $masteryValue !== null ? round($masteryValue, 4) : null,
  663. 'changed' => $changeValue !== null,
  664. 'is_hit' => $isHit,
  665. ];
  666. }
  667. foreach ($radarChildrenByModule as $moduleCode => $items) {
  668. usort($items, static function ($a, $b) {
  669. $da = (int) ($a['depth'] ?? 1);
  670. $db = (int) ($b['depth'] ?? 1);
  671. if ($da !== $db) {
  672. return $da <=> $db;
  673. }
  674. $ca = abs((float) ($a['change'] ?? 0));
  675. $cb = abs((float) ($b['change'] ?? 0));
  676. if ($ca === $cb) {
  677. return strcmp((string) ($a['code'] ?? ''), (string) ($b['code'] ?? ''));
  678. }
  679. return $cb <=> $ca;
  680. });
  681. $radarChildrenByModule[$moduleCode] = $items;
  682. }
  683. foreach ($moduleCodes as $moduleCode) {
  684. $hitParentRow = $hitParentMap[$moduleCode] ?? null;
  685. $hitAvg = null;
  686. if (is_array($hitParentRow) && isset($hitParentRow['children_hit_avg_mastery'])) {
  687. $hitAvg = (float) $hitParentRow['children_hit_avg_mastery'];
  688. }
  689. $fullParentRow = $fullParentMap[$moduleCode] ?? null;
  690. $fullMastery = null;
  691. if (is_array($fullParentRow) && isset($fullParentRow['mastery_level'])) {
  692. $fullMastery = (float) $fullParentRow['mastery_level'];
  693. }
  694. $mastery = $hitAvg ?? $fullMastery;
  695. $hasMastery = $mastery !== null;
  696. $score5 = $hasMastery ? round($mastery * 5, 2) : 0.0;
  697. $status = $hasMastery ? $this->resolveMasteryStatus($mastery) : '未涉及';
  698. $radar[] = [
  699. 'code' => $moduleCode,
  700. 'name' => $moduleNames[$moduleCode] ?? $moduleCode,
  701. 'value' => $score5,
  702. 'status' => $status,
  703. 'has_mastery' => $hasMastery,
  704. 'children' => $radarChildrenByModule[$moduleCode] ?? [],
  705. ];
  706. }
  707. return [
  708. 'summary' => [
  709. 'score_obtained' => round($allObtained, 1),
  710. 'score_total' => round($allMax, 1),
  711. 'score_rate' => $scoreRate,
  712. 'average_mastery' => $avgMastery !== null ? round($avgMastery, 4) : null,
  713. 'overall_label' => $overallLabel,
  714. 'overall_label_detail' => $overallComposite,
  715. 'stage' => $stage,
  716. 'difficulty' => $difficultyInsight,
  717. 'comparison' => $comparisonInsight,
  718. ],
  719. 'radar' => $radar,
  720. 'modules' => $moduleRows,
  721. 'paths' => $paths,
  722. ];
  723. }
  724. private function buildV3LearningPaths(array $moduleRows): array
  725. {
  726. $items = [];
  727. foreach ($moduleRows as $moduleRow) {
  728. if (! isset($moduleRow['mastery_level']) || $moduleRow['mastery_level'] === null) {
  729. continue;
  730. }
  731. $items[] = [
  732. 'name' => (string) ($moduleRow['module_name'] ?? ''),
  733. 'module_code' => (string) ($moduleRow['module_code'] ?? ''),
  734. 'mastery_level' => (float) $moduleRow['mastery_level'],
  735. 'status' => $moduleRow['status'] ?? '未学习',
  736. ];
  737. }
  738. usort($items, fn ($a, $b) => $a['mastery_level'] <=> $b['mastery_level']);
  739. $lowToHigh = $items;
  740. $highToLow = array_reverse($items);
  741. $keep = array_values(array_filter($highToLow, fn ($i) => ($this->toPcMasteryPercent($i['mastery_level']) ?? -1) >= 85));
  742. $boost = array_values(array_filter($lowToHigh, function ($i) {
  743. $percent = $this->toPcMasteryPercent($i['mastery_level']) ?? -1;
  744. return $percent >= 60 && $percent < 85;
  745. }));
  746. $key = array_values(array_filter($lowToHigh, fn ($i) => ($this->toPcMasteryPercent($i['mastery_level']) ?? 101) < 60));
  747. return [
  748. 'keep' => $keep,
  749. 'boost' => $boost,
  750. 'key' => $key,
  751. ];
  752. }
  753. private function resolveMasteryStatus(?float $mastery): string
  754. {
  755. $percent = $this->toPcMasteryPercent($mastery);
  756. if ($percent === null) {
  757. return '未学习';
  758. }
  759. if ($percent >= 85) {
  760. return '已掌握';
  761. }
  762. if ($percent >= 60) {
  763. return '薄弱';
  764. }
  765. return '未入门';
  766. }
  767. private function toPcMasteryPercent(?float $mastery): ?int
  768. {
  769. if ($mastery === null) {
  770. return null;
  771. }
  772. // PC API returns mastery rounded to 2 decimals, then the frontend Math.rounds it to 0-100.
  773. return (int) round(round($mastery, 2) * 100);
  774. }
  775. private function resolveOverallPerformanceLabel(?float $avgMastery): string
  776. {
  777. if ($avgMastery === null) {
  778. return '待评估';
  779. }
  780. if ($avgMastery >= 0.85) {
  781. return '优秀';
  782. }
  783. if ($avgMastery >= 0.7) {
  784. return '良好';
  785. }
  786. if ($avgMastery >= 0.55) {
  787. return '一般';
  788. }
  789. return '需提升';
  790. }
  791. private function averageByKey(array $rows, string $key): ?float
  792. {
  793. if (empty($rows)) {
  794. return null;
  795. }
  796. $sum = 0.0;
  797. $count = 0;
  798. foreach ($rows as $row) {
  799. if (! isset($row[$key])) {
  800. continue;
  801. }
  802. $sum += (float) $row[$key];
  803. $count++;
  804. }
  805. return $count > 0 ? ($sum / $count) : null;
  806. }
  807. private function buildV3DifficultyInsight(array $templateData): array
  808. {
  809. $paper = $templateData['paper'] ?? [];
  810. $questions = $templateData['questions'] ?? [];
  811. $rawCategory = (string) ($paper['difficulty_category'] ?? '');
  812. $level = QuestionDifficultyCalibrationAnalyzer::parsePaperDifficultyCategory($rawCategory);
  813. $levelInt = $level !== null ? (int) round($level) : null;
  814. $range = $this->difficultyRangeByLevel($levelInt);
  815. $difficulties = [];
  816. foreach ($questions as $q) {
  817. $d = $q['difficulty'] ?? null;
  818. if ($d !== null && is_numeric($d)) {
  819. $dv = (float) $d;
  820. if ($dv >= 0.0 && $dv <= 1.0) {
  821. $difficulties[] = $dv;
  822. }
  823. }
  824. }
  825. $actualAvg = ! empty($difficulties) ? (array_sum($difficulties) / count($difficulties)) : null;
  826. $actualLevel = $actualAvg !== null ? $this->mapDifficultyValueToLevel($actualAvg) : null;
  827. $targetCenter = $range !== null ? (($range['min'] + $range['max']) / 2.0) : null;
  828. $deviation = ($actualAvg !== null && $targetCenter !== null) ? ($actualAvg - $targetCenter) : null;
  829. $matchStatus = '暂无';
  830. if ($actualAvg !== null && $range !== null) {
  831. if ($actualAvg > $range['max']) {
  832. $matchStatus = '偏难';
  833. } elseif ($actualAvg < $range['min']) {
  834. $matchStatus = '偏易';
  835. } else {
  836. $matchStatus = '匹配';
  837. }
  838. }
  839. $scoreRate = $this->resolveCurrentScoreRateForDifficultyInsight($templateData);
  840. $scoreBand = $this->resolveScoreRateBandForDifficultyInsight($scoreRate);
  841. $seed = sprintf(
  842. '%s|%s|%s|%s',
  843. (string) ($paper['id'] ?? ''),
  844. (string) (($templateData['student'] ?? [])['id'] ?? ''),
  845. $matchStatus,
  846. $scoreBand
  847. );
  848. $explain = $this->buildDifficultyExplainByContext($matchStatus, $scoreBand, $seed);
  849. return [
  850. 'target_category_raw' => $rawCategory,
  851. 'target_level' => $levelInt,
  852. 'target_label' => $this->difficultyLevelLabel($levelInt, $rawCategory),
  853. 'target_range' => $range,
  854. 'actual_average_difficulty' => $actualAvg !== null ? round($actualAvg, 4) : null,
  855. 'actual_level' => $actualLevel,
  856. 'actual_label' => $actualLevel !== null ? $this->difficultyLevelLabel($actualLevel) : null,
  857. 'deviation' => $deviation !== null ? round($deviation, 4) : null,
  858. 'status' => $matchStatus,
  859. 'question_count' => count($difficulties),
  860. 'score_rate' => $scoreRate !== null ? round($scoreRate, 4) : null,
  861. 'score_band' => $scoreBand,
  862. 'explain' => $explain,
  863. ];
  864. }
  865. private function resolveCurrentScoreRateForDifficultyInsight(array $templateData): ?float
  866. {
  867. $rawOverall = (array) (($templateData['analysis_data'] ?? [])['overall_summary'] ?? []);
  868. if (isset($rawOverall['score_rate']) && is_numeric($rawOverall['score_rate'])) {
  869. $v = (float) $rawOverall['score_rate'];
  870. if ($v >= 0.0 && $v <= 1.0) {
  871. return $v;
  872. }
  873. if ($v > 1.0 && $v <= 100.0) {
  874. return $v / 100.0;
  875. }
  876. }
  877. $questions = $templateData['questions'] ?? [];
  878. $total = 0.0;
  879. $obtained = 0.0;
  880. foreach ($questions as $q) {
  881. $max = $q['score'] ?? $q['max_score'] ?? null;
  882. $got = $q['score_obtained'] ?? null;
  883. if (! is_numeric($max) || ! is_numeric($got)) {
  884. continue;
  885. }
  886. $maxVal = (float) $max;
  887. if ($maxVal <= 0) {
  888. continue;
  889. }
  890. $gotVal = max(0.0, min((float) $got, $maxVal));
  891. $total += $maxVal;
  892. $obtained += $gotVal;
  893. }
  894. return $total > 0 ? ($obtained / $total) : null;
  895. }
  896. private function resolveScoreRateBandForDifficultyInsight(?float $scoreRate): string
  897. {
  898. if ($scoreRate === null) {
  899. return 'unknown';
  900. }
  901. if ($scoreRate >= 0.8) {
  902. return 'high';
  903. }
  904. if ($scoreRate >= 0.6) {
  905. return 'mid';
  906. }
  907. return 'low';
  908. }
  909. private function buildDifficultyExplainByContext(string $matchStatus, string $scoreBand, string $seed): string
  910. {
  911. $messageMap = config('exam.analysis_report_v3.difficulty_explain_messages', []);
  912. if (! is_array($messageMap) || empty($messageMap)) {
  913. $messageMap = [
  914. '暂无' => [
  915. 'unknown' => [
  916. '暂无足够数据评估难度匹配。',
  917. ],
  918. ],
  919. ];
  920. }
  921. $statusMap = $messageMap[$matchStatus] ?? $messageMap['暂无'];
  922. $candidates = $statusMap[$scoreBand] ?? $statusMap['unknown'] ?? $messageMap['暂无']['unknown'];
  923. return $this->pickStableVariantMessage($candidates, $seed);
  924. }
  925. private function pickStableVariantMessage(array $messages, string $seed): string
  926. {
  927. if (empty($messages)) {
  928. return '暂无足够数据评估难度匹配。';
  929. }
  930. $idx = abs(crc32($seed)) % count($messages);
  931. return (string) $messages[$idx];
  932. }
  933. private function buildV3ComparisonInsight(array $templateData, ?float $currentScoreRate, ?float $currentMastery): array
  934. {
  935. $paper = $templateData['paper'] ?? [];
  936. $student = $templateData['student'] ?? [];
  937. $studentId = (string) ($student['id'] ?? '');
  938. $grade = (string) ($student['grade'] ?? '');
  939. $paperId = (string) ($paper['id'] ?? '');
  940. $paperType = isset($paper['paper_type']) ? (int) $paper['paper_type'] : null;
  941. $history = [
  942. 'has_data' => false,
  943. 'is_first_exam' => false,
  944. 'low_baseline_guard' => false,
  945. 'sample_size' => 0,
  946. 'baseline_score_rate' => null,
  947. 'delta_score_rate' => null,
  948. 'trend' => '暂无',
  949. 'message' => '历史样本不足,暂无法形成稳定趋势。',
  950. ];
  951. $peers = [
  952. 'has_data' => false,
  953. 'sample_size' => 0,
  954. 'raw_sample_size' => 0,
  955. 'peer_avg_score_rate' => null,
  956. 'delta_score_rate' => null,
  957. 'percentile' => null,
  958. 'band' => '暂无',
  959. 'display_mode' => 'none',
  960. 'show_line' => false,
  961. 'band_icon' => '•',
  962. 'band_color' => '#64748b',
  963. 'message' => '同群体样本不足,暂无法做稳健对比。',
  964. ];
  965. if ($studentId === '') {
  966. return ['history' => $history, 'peers' => $peers];
  967. }
  968. try {
  969. $historyRows = DB::connection('mysql')
  970. ->table('papers as p')
  971. ->join('paper_questions as pq', 'pq.paper_id', '=', 'p.paper_id')
  972. ->where('p.student_id', $studentId)
  973. ->when($paperId !== '', fn ($q) => $q->where('p.paper_id', '!=', $paperId))
  974. ->groupBy('p.paper_id', 'p.created_at')
  975. ->selectRaw('p.paper_id, p.created_at, SUM(COALESCE(pq.score, 0)) as total_score, SUM(COALESCE(pq.score_obtained, 0)) as obtained_score')
  976. ->havingRaw('SUM(COALESCE(pq.score, 0)) > 0')
  977. ->orderByDesc('p.created_at')
  978. ->limit(7)
  979. ->get();
  980. $historyRates = [];
  981. foreach ($historyRows as $row) {
  982. $total = (float) ($row->total_score ?? 0);
  983. if ($total <= 0) {
  984. continue;
  985. }
  986. $historyRates[] = (float) ($row->obtained_score ?? 0) / $total;
  987. }
  988. if (! empty($historyRates) && $currentScoreRate !== null) {
  989. $baseline = array_sum($historyRates) / count($historyRates);
  990. $delta = $currentScoreRate - $baseline;
  991. $history['has_data'] = true;
  992. $history['sample_size'] = count($historyRates);
  993. $history['baseline_score_rate'] = round($baseline, 4);
  994. $history['delta_score_rate'] = round($delta, 4);
  995. if ($baseline <= 0.02 && count($historyRates) >= 5) {
  996. $history['low_baseline_guard'] = true;
  997. $history['trend'] = '基线偏低';
  998. $history['message'] = '近7次历史基线过低,单次涨跌参考意义有限,建议重点看后续连续3次趋势。';
  999. } else {
  1000. $history['trend'] = $this->resolveDeltaTrendLabel($delta);
  1001. $history['message'] = $delta >= 0
  1002. ? '相较于近期个人表现,本次成绩处于上行区间。'
  1003. : '相较于近期个人表现,本次成绩略有回落,建议优先复盘错因分布。';
  1004. }
  1005. } elseif ($currentScoreRate !== null) {
  1006. $history['is_first_exam'] = true;
  1007. $history['message'] = $this->pickFirstExamEncouragementMessageByScore($currentScoreRate);
  1008. }
  1009. } catch (\Throwable $e) {
  1010. Log::warning('ExamPdfExportService: 构建历史对比失败', ['error' => $e->getMessage()]);
  1011. }
  1012. try {
  1013. if ($grade !== '' && $currentScoreRate !== null) {
  1014. $peerRows = DB::connection('mysql')
  1015. ->table('papers as p')
  1016. ->join('students as s', 's.student_id', '=', 'p.student_id')
  1017. ->join('paper_questions as pq', 'pq.paper_id', '=', 'p.paper_id')
  1018. ->where('s.grade', $grade)
  1019. ->where('p.student_id', '!=', $studentId)
  1020. ->when($paperType !== null, fn ($q) => $q->where('p.paper_type', $paperType))
  1021. ->groupBy('p.paper_id', 'p.created_at')
  1022. ->selectRaw('p.paper_id, p.created_at, SUM(COALESCE(pq.score, 0)) as total_score, SUM(COALESCE(pq.score_obtained, 0)) as obtained_score')
  1023. ->havingRaw('SUM(COALESCE(pq.score, 0)) > 0')
  1024. ->orderByDesc('p.created_at')
  1025. ->limit(300)
  1026. ->get();
  1027. $peerRates = [];
  1028. foreach ($peerRows as $row) {
  1029. $total = (float) ($row->total_score ?? 0);
  1030. if ($total <= 0) {
  1031. continue;
  1032. }
  1033. $peerRates[] = (float) ($row->obtained_score ?? 0) / $total;
  1034. }
  1035. if (! empty($peerRates)) {
  1036. sort($peerRates);
  1037. $peerAvg = array_sum($peerRates) / count($peerRates);
  1038. $ltCount = 0;
  1039. $eqCount = 0;
  1040. foreach ($peerRates as $rate) {
  1041. if ($rate < $currentScoreRate) {
  1042. $ltCount++;
  1043. } elseif (abs($rate - $currentScoreRate) < 1e-9) {
  1044. $eqCount++;
  1045. }
  1046. }
  1047. // 使用 mid-rank percentile,避免并列值把分位夸大到 100%
  1048. $percentile = (100.0 * ($ltCount + 0.5 * $eqCount)) / count($peerRates);
  1049. $delta = $currentScoreRate - $peerAvg;
  1050. $peerCount = count($peerRates);
  1051. $band = $this->resolvePeerBand($percentile);
  1052. $bandVisual = $this->resolvePeerBandVisual($band);
  1053. $peers['has_data'] = true;
  1054. $peers['show_line'] = true;
  1055. $peers['sample_size'] = $peerCount;
  1056. $peers['raw_sample_size'] = $peerCount;
  1057. $peers['peer_avg_score_rate'] = round($peerAvg, 4);
  1058. $peers['delta_score_rate'] = round($delta, 4);
  1059. $peers['percentile'] = round($percentile, 1);
  1060. $peers['band'] = $band;
  1061. $peers['band_icon'] = $bandVisual['icon'];
  1062. $peers['band_color'] = $bandVisual['color'];
  1063. if ($peerCount < 50) {
  1064. $peers['display_mode'] = 'masked';
  1065. $peers['sample_size'] = null;
  1066. $peers['peer_avg_score_rate'] = null;
  1067. $peers['percentile'] = null;
  1068. $peers['message'] = '已建立同群体参照,当前处于'.$band.'区间。';
  1069. } elseif ($peerCount > 200) {
  1070. $peers['display_mode'] = 'percentile_only';
  1071. $peers['sample_size'] = null;
  1072. $peers['peer_avg_score_rate'] = null;
  1073. $peers['percentile'] = null;
  1074. $peers['message'] = '和上百位同年级同类型学生相比,你当前处于'.$band.'水平。';
  1075. } else {
  1076. $peers['display_mode'] = 'detailed';
  1077. $peers['message'] = '同年级同类型参照中,你当前位于 '
  1078. .number_format($percentile, 1).'% 分位,群体均值 '
  1079. .number_format($peerAvg * 100, 1).'% 。';
  1080. }
  1081. }
  1082. }
  1083. } catch (\Throwable $e) {
  1084. Log::warning('ExamPdfExportService: 构建同群体对比失败', ['error' => $e->getMessage()]);
  1085. }
  1086. return [
  1087. 'history' => $history,
  1088. 'peers' => $peers,
  1089. 'mastery' => [
  1090. 'current_average_mastery' => $currentMastery !== null ? round($currentMastery, 4) : null,
  1091. ],
  1092. ];
  1093. }
  1094. private function difficultyRangeByLevel(?int $level): ?array
  1095. {
  1096. $map = [
  1097. 0 => ['min' => 0.00, 'max' => 0.10],
  1098. 1 => ['min' => 0.10, 'max' => 0.25],
  1099. 2 => ['min' => 0.25, 'max' => 0.50],
  1100. 3 => ['min' => 0.50, 'max' => 0.75],
  1101. 4 => ['min' => 0.75, 'max' => 1.00],
  1102. ];
  1103. if ($level === null || ! isset($map[$level])) {
  1104. return null;
  1105. }
  1106. return $map[$level];
  1107. }
  1108. private function mapDifficultyValueToLevel(float $difficulty): int
  1109. {
  1110. if ($difficulty < 0.10) {
  1111. return 0;
  1112. }
  1113. if ($difficulty < 0.25) {
  1114. return 1;
  1115. }
  1116. if ($difficulty < 0.50) {
  1117. return 2;
  1118. }
  1119. if ($difficulty < 0.75) {
  1120. return 3;
  1121. }
  1122. return 4;
  1123. }
  1124. private function difficultyLevelLabel(?int $level, ?string $fallback = null): string
  1125. {
  1126. $map = [
  1127. 0 => '0基础',
  1128. 1 => '筑基',
  1129. 2 => '提分',
  1130. 3 => '培优',
  1131. 4 => '竞赛',
  1132. ];
  1133. if ($level !== null && isset($map[$level])) {
  1134. return $map[$level];
  1135. }
  1136. $fallback = trim((string) $fallback);
  1137. return $fallback !== '' ? $fallback : '未设置';
  1138. }
  1139. private function resolveDeltaTrendLabel(float $delta): string
  1140. {
  1141. if ($delta >= 0.05) {
  1142. return '显著提升';
  1143. }
  1144. if ($delta >= 0.02) {
  1145. return '小幅提升';
  1146. }
  1147. if ($delta > -0.02) {
  1148. return '基本持平';
  1149. }
  1150. if ($delta > -0.05) {
  1151. return '小幅回落';
  1152. }
  1153. return '明显回落';
  1154. }
  1155. private function resolvePeerBand(float $percentile): string
  1156. {
  1157. if ($percentile >= 75) {
  1158. return '领先';
  1159. }
  1160. if ($percentile >= 45) {
  1161. return '中上';
  1162. }
  1163. if ($percentile >= 25) {
  1164. return '中下';
  1165. }
  1166. return '待提升';
  1167. }
  1168. /**
  1169. * 综合当前表现、历史趋势、同群体位置,给出“整体水平”。
  1170. *
  1171. * @return array{
  1172. * label:string,
  1173. * composite_score:float,
  1174. * current_score:float,
  1175. * history_score:float,
  1176. * peer_score:float,
  1177. * difficulty_adjust:float
  1178. * }
  1179. */
  1180. private function buildV3OverallCompositeEvaluation(
  1181. ?float $scoreRate,
  1182. ?float $avgMastery,
  1183. array $difficultyInsight,
  1184. array $comparisonInsight,
  1185. string $fallbackLabel
  1186. ): array {
  1187. $currentScoreRatePct = $scoreRate !== null ? max(0.0, min(100.0, $scoreRate * 100.0)) : 50.0;
  1188. $currentMasteryPct = $avgMastery !== null ? max(0.0, min(100.0, $avgMastery * 100.0)) : 50.0;
  1189. $currentScore = (0.7 * $currentScoreRatePct) + (0.3 * $currentMasteryPct);
  1190. $history = $comparisonInsight['history'] ?? [];
  1191. $historyScore = 60.0;
  1192. if (! empty($history['is_first_exam'])) {
  1193. $historyScore = 60.0;
  1194. } elseif (! empty($history['low_baseline_guard'])) {
  1195. $historyScore = 60.0;
  1196. } elseif (! empty($history['has_data']) && isset($history['delta_score_rate'])) {
  1197. $delta = (float) $history['delta_score_rate']; // ±1
  1198. $historyScore = 60.0 + (200.0 * $delta); // delta 0.1 => +20
  1199. $historyScore = max(0.0, min(100.0, $historyScore));
  1200. }
  1201. $peers = $comparisonInsight['peers'] ?? [];
  1202. $peerScore = 60.0;
  1203. if (! empty($peers['show_line'])) {
  1204. if (isset($peers['percentile']) && $peers['percentile'] !== null) {
  1205. $peerScore = max(0.0, min(100.0, (float) $peers['percentile']));
  1206. } else {
  1207. $band = (string) ($peers['band'] ?? '暂无');
  1208. $peerScore = match ($band) {
  1209. '领先' => 82.0,
  1210. '中上' => 66.0,
  1211. '中下' => 46.0,
  1212. '待提升' => 28.0,
  1213. default => 60.0,
  1214. };
  1215. }
  1216. }
  1217. $difficultyAdjust = 0.0;
  1218. $difficultyStatus = (string) ($difficultyInsight['status'] ?? '');
  1219. if ($difficultyStatus === '偏难') {
  1220. $difficultyAdjust = 5.0;
  1221. } elseif ($difficultyStatus === '偏易') {
  1222. $difficultyAdjust = -5.0;
  1223. }
  1224. $composite = (0.50 * $currentScore) + (0.25 * $historyScore) + (0.25 * $peerScore) + $difficultyAdjust;
  1225. $composite = max(0.0, min(100.0, $composite));
  1226. // 等级标准统一:
  1227. // S: 90-100, A: 75-89, B: 60-74, C: 40-59, D: 0-39
  1228. $grade = match (true) {
  1229. $composite >= 90.0 => 'S',
  1230. $composite >= 75.0 => 'A',
  1231. $composite >= 60.0 => 'B',
  1232. $composite >= 40.0 => 'C',
  1233. default => 'D',
  1234. };
  1235. $label = match ($grade) {
  1236. 'S', 'A' => '优秀',
  1237. 'B' => '良好',
  1238. 'C' => '一般',
  1239. default => '需加强',
  1240. };
  1241. if ($scoreRate === null && $avgMastery === null) {
  1242. $label = $fallbackLabel !== '' ? $fallbackLabel : '待评估';
  1243. }
  1244. return [
  1245. 'grade' => $grade,
  1246. 'label' => $label,
  1247. 'composite_score' => round($composite, 1),
  1248. 'current_score' => round($currentScore, 1),
  1249. 'history_score' => round($historyScore, 1),
  1250. 'peer_score' => round($peerScore, 1),
  1251. 'difficulty_adjust' => round($difficultyAdjust, 1),
  1252. ];
  1253. }
  1254. /**
  1255. * 首次出报告时,按得分档位随机抽取鼓励文案(每档10条)。
  1256. *
  1257. * 档位标准统一:
  1258. * A: 90-100, B: 75-89, C: 60-74, D: 40-59, E: 0-39
  1259. */
  1260. private function pickFirstExamEncouragementMessageByScore(?float $scoreRate): string
  1261. {
  1262. $score = 0.0;
  1263. if ($scoreRate !== null) {
  1264. $raw = (float) $scoreRate;
  1265. $score = $raw <= 1.0 ? ($raw * 100.0) : $raw;
  1266. $score = max(0.0, min(100.0, $score));
  1267. }
  1268. $bucket = match (true) {
  1269. $score >= 90.0 => 'A',
  1270. $score >= 75.0 => 'B',
  1271. $score >= 60.0 => 'C',
  1272. $score >= 40.0 => 'D',
  1273. default => 'E',
  1274. };
  1275. $messagesByBucket = config('exam.analysis_report_v3.first_exam_messages_by_bucket', []);
  1276. if (! is_array($messagesByBucket) || empty($messagesByBucket)) {
  1277. $messagesByBucket = [
  1278. 'A' => ['这次开局很稳,说明你的基础和状态都在线。'],
  1279. 'B' => ['这个分数是很不错的起点,方向完全正确。'],
  1280. 'C' => ['这是正常且可提升的起点,先稳住基础最关键。'],
  1281. 'D' => ['第一次这个分数不代表上限,只代表当前起点。'],
  1282. 'E' => ['第一次分数偏低很正常,先把学习路径走顺。'],
  1283. ];
  1284. }
  1285. $messages = $messagesByBucket[$bucket] ?? $messagesByBucket['C'];
  1286. $idx = random_int(0, count($messages) - 1);
  1287. return $messages[$idx];
  1288. }
  1289. /**
  1290. * 为同群体区间提供可视化图标与颜色。
  1291. *
  1292. * @return array{icon:string,color:string}
  1293. */
  1294. private function resolvePeerBandVisual(string $band): array
  1295. {
  1296. return match ($band) {
  1297. '领先' => ['icon' => '▲', 'color' => '#16a34a'],
  1298. '中上' => ['icon' => '↗', 'color' => '#0ea5e9'],
  1299. '中下' => ['icon' => '↘', 'color' => '#f59e0b'],
  1300. '待提升' => ['icon' => '▼', 'color' => '#ef4444'],
  1301. default => ['icon' => '•', 'color' => '#64748b'],
  1302. };
  1303. }
  1304. /**
  1305. * 收集某学段根节点下的全量后代知识点(不含根节点本身)
  1306. */
  1307. private function collectStageKnowledgePoints(string $rootCode): array
  1308. {
  1309. if ($rootCode === '') {
  1310. return [];
  1311. }
  1312. $cacheVersion = $this->getKnowledgePointsCacheVersion();
  1313. $cacheKey = sprintf('exam_pdf:kp_descendants:v1:%s:%s', $rootCode, $cacheVersion);
  1314. try {
  1315. return $this->rememberWithFallback($cacheKey, self::KNOWLEDGE_POINTS_CACHE_TTL_SECONDS, function () use ($rootCode) {
  1316. $result = [];
  1317. $currentParents = [$rootCode];
  1318. $visitedParents = [];
  1319. $seenCodes = [];
  1320. while (! empty($currentParents)) {
  1321. $batchParents = [];
  1322. foreach ($currentParents as $parentCode) {
  1323. $parentCode = trim((string) $parentCode);
  1324. if ($parentCode === '' || isset($visitedParents[$parentCode])) {
  1325. continue;
  1326. }
  1327. $visitedParents[$parentCode] = true;
  1328. $batchParents[] = $parentCode;
  1329. }
  1330. if ($batchParents === []) {
  1331. break;
  1332. }
  1333. $rows = DB::connection('mysql')
  1334. ->table('knowledge_points')
  1335. ->whereIn('parent_kp_code', $batchParents)
  1336. ->select('kp_code')
  1337. ->get();
  1338. $nextParents = [];
  1339. foreach ($rows as $row) {
  1340. $childCode = trim((string) ($row->kp_code ?? ''));
  1341. if ($childCode === '' || $childCode === $rootCode || isset($seenCodes[$childCode])) {
  1342. continue;
  1343. }
  1344. $seenCodes[$childCode] = true;
  1345. $result[] = $childCode;
  1346. $nextParents[] = $childCode;
  1347. }
  1348. $currentParents = $nextParents;
  1349. }
  1350. return $result;
  1351. });
  1352. } catch (\Throwable $e) {
  1353. Log::warning('ExamPdfExportService: collectStageKnowledgePoints failed', [
  1354. 'root_code' => $rootCode,
  1355. 'error' => $e->getMessage(),
  1356. ]);
  1357. return [];
  1358. }
  1359. }
  1360. /**
  1361. * Expand a hit knowledge point to leaf descendants so PDF cluster callouts match higher-level paper targets.
  1362. *
  1363. * @param array<string, array<int, string>> $childrenByParent
  1364. * @return array<int, string>
  1365. */
  1366. private function collectLeafDescendants(string $rootCode, array $childrenByParent): array
  1367. {
  1368. $rootCode = trim($rootCode);
  1369. if ($rootCode === '') {
  1370. return [];
  1371. }
  1372. $leaves = [];
  1373. $queue = [$rootCode];
  1374. $visited = [];
  1375. while (! empty($queue)) {
  1376. $code = array_shift($queue);
  1377. if (isset($visited[$code])) {
  1378. continue;
  1379. }
  1380. $visited[$code] = true;
  1381. $children = $childrenByParent[$code] ?? [];
  1382. if (empty($children)) {
  1383. if ($code !== $rootCode) {
  1384. $leaves[] = $code;
  1385. }
  1386. continue;
  1387. }
  1388. foreach ($children as $childCode) {
  1389. $childCode = trim((string) $childCode);
  1390. if ($childCode !== '') {
  1391. $queue[] = $childCode;
  1392. }
  1393. }
  1394. }
  1395. return array_values(array_unique($leaves));
  1396. }
  1397. private function resolveRadarStage(string $grade, array $fullParentLevels = []): string
  1398. {
  1399. $g = trim($grade);
  1400. if ($g !== '') {
  1401. if (preg_match('/高一|高二|高三/u', $g)) {
  1402. return 'high';
  1403. }
  1404. if (preg_match('/\d+/', $g, $m)) {
  1405. $n = (int) $m[0];
  1406. if ($n >= 10) {
  1407. return 'high';
  1408. }
  1409. if ($n > 0 && $n <= 9) {
  1410. return 'junior';
  1411. }
  1412. }
  1413. }
  1414. foreach (array_keys($fullParentLevels) as $kpCode) {
  1415. if (str_starts_with((string) $kpCode, 'S')) {
  1416. return 'high';
  1417. }
  1418. }
  1419. return 'junior';
  1420. }
  1421. private function getRadarProfileByStage(string $stage): array
  1422. {
  1423. if ($stage === 'high') {
  1424. $moduleNames = [
  1425. 'S01_000' => '集合',
  1426. 'S02_000' => '逻辑用语',
  1427. 'S03_000' => '不等式',
  1428. 'S04_000' => '函数',
  1429. 'S05_000' => '导数',
  1430. 'S06_000' => '三角函数与向量',
  1431. 'S07_000' => '立体几何',
  1432. 'S08_000' => '解析几何',
  1433. 'S09_000' => '数列',
  1434. 'S10_000' => '概率统计',
  1435. 'S11_000' => '复数',
  1436. ];
  1437. return [
  1438. 'root_code' => 'S000_000',
  1439. 'module_codes' => array_keys($moduleNames),
  1440. 'module_names' => $moduleNames,
  1441. ];
  1442. }
  1443. return [
  1444. 'root_code' => 'M00',
  1445. 'module_codes' => ['M01', 'M02', 'M03', 'M04', 'M05', 'M06', 'M07'],
  1446. 'module_names' => [
  1447. 'M01' => '数与代数',
  1448. 'M02' => '方程与不等式',
  1449. 'M03' => '图形性质',
  1450. 'M04' => '图形变化与度量',
  1451. 'M05' => '相似与勾股',
  1452. 'M06' => '统计与概率',
  1453. 'M07' => '函数',
  1454. ],
  1455. ];
  1456. }
  1457. private function getKnowledgePointMetaMap(string $rootCode, array $moduleCodes): array
  1458. {
  1459. $moduleCodes = array_values(array_unique(array_filter(array_map(static fn ($code) => trim((string) $code), $moduleCodes))));
  1460. $cacheVersion = $this->getKnowledgePointsCacheVersion();
  1461. $inMemoryKey = $rootCode.'|'.implode(',', $moduleCodes).'|'.$cacheVersion;
  1462. if (isset($this->knowledgePointMetaCache[$inMemoryKey])) {
  1463. return $this->knowledgePointMetaCache[$inMemoryKey];
  1464. }
  1465. $cacheKey = sprintf('exam_pdf:kp_meta_map:v2:%s:%s:%s', $rootCode, md5(implode(',', $moduleCodes)), $cacheVersion);
  1466. $map = $this->rememberWithFallback($cacheKey, self::KNOWLEDGE_POINTS_CACHE_TTL_SECONDS, function () use ($rootCode, $moduleCodes) {
  1467. $seedCodes = array_values(array_unique(array_filter(array_merge([$rootCode], $moduleCodes))));
  1468. if ($seedCodes === []) {
  1469. return [];
  1470. }
  1471. $rows = DB::connection('mysql')
  1472. ->table('knowledge_points')
  1473. ->whereIn('kp_code', $seedCodes)
  1474. ->select(['kp_code', 'name', 'parent_kp_code'])
  1475. ->get();
  1476. $result = [];
  1477. foreach ($rows as $row) {
  1478. $code = trim((string) ($row->kp_code ?? ''));
  1479. if ($code === '') {
  1480. continue;
  1481. }
  1482. $result[$code] = [
  1483. 'name' => (string) ($row->name ?? $code),
  1484. 'parent_kp_code' => trim((string) ($row->parent_kp_code ?? '')),
  1485. ];
  1486. }
  1487. // 从模块出发按层拉取子树,避免从学段根节点全量展开
  1488. $currentParents = $moduleCodes;
  1489. $visitedParents = [];
  1490. $guard = 0;
  1491. while (! empty($currentParents) && $guard < 40) {
  1492. $batchParents = [];
  1493. foreach ($currentParents as $parentCode) {
  1494. $parentCode = trim((string) $parentCode);
  1495. if ($parentCode === '' || isset($visitedParents[$parentCode])) {
  1496. continue;
  1497. }
  1498. $visitedParents[$parentCode] = true;
  1499. $batchParents[] = $parentCode;
  1500. }
  1501. if ($batchParents === []) {
  1502. break;
  1503. }
  1504. $childRows = DB::connection('mysql')
  1505. ->table('knowledge_points')
  1506. ->whereIn('parent_kp_code', $batchParents)
  1507. ->select(['kp_code', 'name', 'parent_kp_code'])
  1508. ->get();
  1509. $nextParents = [];
  1510. foreach ($childRows as $row) {
  1511. $code = trim((string) ($row->kp_code ?? ''));
  1512. if ($code === '' || isset($result[$code])) {
  1513. continue;
  1514. }
  1515. $result[$code] = [
  1516. 'name' => (string) ($row->name ?? $code),
  1517. 'parent_kp_code' => trim((string) ($row->parent_kp_code ?? '')),
  1518. ];
  1519. $nextParents[] = $code;
  1520. }
  1521. $currentParents = $nextParents;
  1522. $guard++;
  1523. }
  1524. // 补齐祖先链,确保路径与模块归属计算不丢失
  1525. $pendingParents = [];
  1526. foreach ($result as $meta) {
  1527. $parent = trim((string) ($meta['parent_kp_code'] ?? ''));
  1528. if ($parent !== '' && ! isset($result[$parent])) {
  1529. $pendingParents[$parent] = true;
  1530. }
  1531. }
  1532. $ancestorGuard = 0;
  1533. while (! empty($pendingParents) && $ancestorGuard < 24) {
  1534. $parentBatch = array_keys($pendingParents);
  1535. $pendingParents = [];
  1536. foreach (array_chunk($parentBatch, 500) as $chunk) {
  1537. $ancestorRows = DB::connection('mysql')
  1538. ->table('knowledge_points')
  1539. ->whereIn('kp_code', $chunk)
  1540. ->select(['kp_code', 'name', 'parent_kp_code'])
  1541. ->get();
  1542. foreach ($ancestorRows as $row) {
  1543. $code = trim((string) ($row->kp_code ?? ''));
  1544. if ($code === '') {
  1545. continue;
  1546. }
  1547. if (! isset($result[$code])) {
  1548. $result[$code] = [
  1549. 'name' => (string) ($row->name ?? $code),
  1550. 'parent_kp_code' => trim((string) ($row->parent_kp_code ?? '')),
  1551. ];
  1552. }
  1553. $parent = trim((string) ($result[$code]['parent_kp_code'] ?? ''));
  1554. if ($parent !== '' && ! isset($result[$parent])) {
  1555. $pendingParents[$parent] = true;
  1556. }
  1557. }
  1558. }
  1559. $ancestorGuard++;
  1560. }
  1561. return $result;
  1562. });
  1563. $this->knowledgePointMetaCache[$inMemoryKey] = $map;
  1564. return $map;
  1565. }
  1566. private function getKnowledgePointsCacheVersion(): string
  1567. {
  1568. return $this->rememberWithFallback('exam_pdf:kp_cache_version:v1', self::KNOWLEDGE_POINTS_VERSION_TTL_SECONDS, function () {
  1569. $row = DB::connection('mysql')
  1570. ->table('knowledge_points')
  1571. ->selectRaw('COALESCE(UNIX_TIMESTAMP(MAX(updated_at)), 0) as max_updated_ts, COUNT(*) as total_count')
  1572. ->first();
  1573. $maxUpdatedTs = (string) (($row->max_updated_ts ?? 0));
  1574. $totalCount = (string) (($row->total_count ?? 0));
  1575. return $maxUpdatedTs.'_'.$totalCount;
  1576. });
  1577. }
  1578. private function rememberWithFallback(string $key, int $ttlSeconds, callable $resolver): mixed
  1579. {
  1580. $resolved = false;
  1581. $resolvedValue = null;
  1582. try {
  1583. return Cache::remember($key, now()->addSeconds($ttlSeconds), function () use ($resolver, &$resolved, &$resolvedValue) {
  1584. $resolvedValue = $resolver();
  1585. $resolved = true;
  1586. return $resolvedValue;
  1587. });
  1588. } catch (\Throwable $e) {
  1589. Log::warning('ExamPdfExportService: 缓存不可用,回退直查', [
  1590. 'cache_key' => $key,
  1591. 'error' => $e->getMessage(),
  1592. ]);
  1593. if ($resolved) {
  1594. return $resolvedValue;
  1595. }
  1596. return $resolver();
  1597. }
  1598. }
  1599. /**
  1600. * V3 报告仅保留模板和统计所需字段,避免大对象在内存中长期驻留。
  1601. */
  1602. private function reduceTemplateDataForV3(array $templateData): array
  1603. {
  1604. unset($templateData['question_insights'], $templateData['recommendations']);
  1605. $templateData['questions'] = $this->compactQuestionsForV3($templateData['questions'] ?? []);
  1606. if (isset($templateData['analysis_data']['question_analysis']) && is_array($templateData['analysis_data']['question_analysis'])) {
  1607. $templateData['analysis_data']['question_analysis'] = array_map(static function ($item) {
  1608. if (! is_array($item)) {
  1609. return [];
  1610. }
  1611. return [
  1612. 'question_id' => $item['question_id'] ?? null,
  1613. 'question_bank_id' => $item['question_bank_id'] ?? null,
  1614. 'is_correct' => $item['is_correct'] ?? null,
  1615. // V3 诊断得分计算依赖这两个字段,不能裁掉
  1616. 'max_score' => $item['max_score'] ?? null,
  1617. 'score_obtained' => $item['score_obtained'] ?? null,
  1618. // V3 模块归属计算依赖知识点信息,不能裁掉
  1619. 'knowledge_points' => $item['knowledge_points'] ?? [],
  1620. ];
  1621. }, $templateData['analysis_data']['question_analysis']);
  1622. }
  1623. return $templateData;
  1624. }
  1625. /**
  1626. * 仅输出摘要日志,避免将大数组序列化进日志造成额外内存开销。
  1627. *
  1628. * @return array<string, mixed>
  1629. */
  1630. private function summarizeTemplateDataForLog(array $templateData): array
  1631. {
  1632. return [
  1633. 'paper_id' => $templateData['paper']['id'] ?? null,
  1634. 'student_id' => $templateData['student']['id'] ?? null,
  1635. 'questions_count' => count($templateData['questions'] ?? []),
  1636. 'analysis_question_count' => count($templateData['analysis_data']['question_analysis'] ?? []),
  1637. 'mastery_count' => count($templateData['mastery']['items'] ?? []),
  1638. 'exam_hit_kp_count' => count($templateData['exam_hit_kp_codes'] ?? []),
  1639. 'parent_mastery_count' => count($templateData['parent_mastery_levels'] ?? []),
  1640. 'full_parent_mastery_count' => count($templateData['full_parent_mastery_levels'] ?? []),
  1641. ];
  1642. }
  1643. /**
  1644. * 仅保留 PDF V3 模板使用到的题目字段,减少内存占用与序列化开销。
  1645. *
  1646. * @return array<int, array<string, mixed>>
  1647. */
  1648. private function compactQuestionsForV3(array $questions): array
  1649. {
  1650. $compact = [];
  1651. foreach ($this->flattenQuestionPayloadRows($questions) as $question) {
  1652. if (! is_array($question)) {
  1653. continue;
  1654. }
  1655. $compact[] = [
  1656. 'question_id' => $question['question_id'] ?? null,
  1657. 'question_bank_id' => $question['question_bank_id'] ?? null,
  1658. 'is_correct' => $question['is_correct'] ?? null,
  1659. 'difficulty' => $question['difficulty'] ?? null,
  1660. 'score' => $question['score'] ?? null,
  1661. 'score_obtained' => $question['score_obtained'] ?? null,
  1662. 'student_answer' => $question['student_answer'] ?? null,
  1663. 'answer' => $question['answer'] ?? null,
  1664. 'correct_answer' => $question['correct_answer'] ?? null,
  1665. 'knowledge_point' => $question['knowledge_point'] ?? null,
  1666. 'knowledge_point_name' => $question['knowledge_point_name'] ?? null,
  1667. ];
  1668. }
  1669. return $compact;
  1670. }
  1671. /**
  1672. * V3 构建阶段只需要题目摘要;这里把 choice/fill/answer 分组结构拍平成题目列表。
  1673. *
  1674. * @return array<int, array<string, mixed>>
  1675. */
  1676. private function flattenQuestionPayloadRows(array $questions): array
  1677. {
  1678. $rows = [];
  1679. foreach ($questions as $key => $value) {
  1680. if (is_array($value) && in_array($key, ['choice', 'fill', 'answer'], true)) {
  1681. foreach ($value as $item) {
  1682. if (is_array($item)) {
  1683. $rows[] = $item;
  1684. }
  1685. }
  1686. continue;
  1687. }
  1688. if (is_array($value)) {
  1689. $rows[] = $value;
  1690. }
  1691. }
  1692. return $rows;
  1693. }
  1694. private function mapKpToStageModule(string $kpCode, array $kpMeta, string $rootCode): ?string
  1695. {
  1696. $code = trim($kpCode);
  1697. if ($code === '' || empty($kpMeta[$code])) {
  1698. return null;
  1699. }
  1700. $cursor = $code;
  1701. for ($depth = 0; $depth < 16; $depth++) {
  1702. $node = $kpMeta[$cursor] ?? null;
  1703. if (! $node) {
  1704. return null;
  1705. }
  1706. $parent = (string) ($node['parent_kp_code'] ?? '');
  1707. if ($parent === $rootCode) {
  1708. return $cursor;
  1709. }
  1710. if ($parent === '' || $parent === $cursor) {
  1711. return null;
  1712. }
  1713. $cursor = $parent;
  1714. }
  1715. return null;
  1716. }
  1717. private function resolveDepthToModule(string $kpCode, string $moduleCode, array $kpMeta): int
  1718. {
  1719. $depth = 1;
  1720. $cursor = trim($kpCode);
  1721. for ($i = 0; $i < 24; $i++) {
  1722. if ($cursor === '' || ! isset($kpMeta[$cursor])) {
  1723. break;
  1724. }
  1725. if ($cursor === $moduleCode) {
  1726. return max(1, $depth - 1);
  1727. }
  1728. $parent = trim((string) ($kpMeta[$cursor]['parent_kp_code'] ?? ''));
  1729. if ($parent === '' || $parent === $cursor) {
  1730. break;
  1731. }
  1732. $cursor = $parent;
  1733. $depth++;
  1734. }
  1735. return max(1, $depth);
  1736. }
  1737. /**
  1738. * 生成合并PDF(试卷 + 判卷)
  1739. * 先分别生成两个PDF,然后合并
  1740. */
  1741. public function generateMergedPdf(string $paperId): ?string
  1742. {
  1743. Log::info('generateMergedPdf 开始:', ['paper_id' => $paperId]);
  1744. $tempDir = storage_path('app/temp');
  1745. if (! is_dir($tempDir)) {
  1746. mkdir($tempDir, 0755, true);
  1747. }
  1748. $examPdfPath = null;
  1749. $gradingPdfPath = null;
  1750. $mergedPdfPath = null;
  1751. try {
  1752. // 先生成试卷PDF
  1753. $examPdfUrl = $this->generateExamPdf($paperId);
  1754. if (! $examPdfUrl) {
  1755. Log::error('ExamPdfExportService: 生成试卷PDF失败', ['paper_id' => $paperId]);
  1756. return null;
  1757. }
  1758. // 再生成判卷PDF
  1759. $gradingPdfUrl = $this->generateGradingPdf($paperId);
  1760. if (! $gradingPdfUrl) {
  1761. Log::error('ExamPdfExportService: 生成判卷PDF失败', ['paper_id' => $paperId]);
  1762. return null;
  1763. }
  1764. // 【修复】下载PDF文件到本地临时目录
  1765. Log::info('开始下载PDF文件到本地', [
  1766. 'exam_url' => $examPdfUrl,
  1767. 'grading_url' => $gradingPdfUrl,
  1768. ]);
  1769. $examPdfPath = $tempDir."/{$paperId}_exam.pdf";
  1770. $gradingPdfPath = $tempDir."/{$paperId}_grading.pdf";
  1771. // 下载试卷PDF
  1772. $examContent = Http::get($examPdfUrl)->body();
  1773. if (empty($examContent)) {
  1774. Log::error('ExamPdfExportService: 下载试卷PDF失败', ['url' => $examPdfUrl]);
  1775. return null;
  1776. }
  1777. file_put_contents($examPdfPath, $examContent);
  1778. // 下载判卷PDF
  1779. $gradingContent = Http::get($gradingPdfUrl)->body();
  1780. if (empty($gradingContent)) {
  1781. Log::error('ExamPdfExportService: 下载判卷PDF失败', ['url' => $gradingPdfUrl]);
  1782. return null;
  1783. }
  1784. file_put_contents($gradingPdfPath, $gradingContent);
  1785. Log::info('PDF文件下载完成', [
  1786. 'exam_size' => filesize($examPdfPath),
  1787. 'grading_size' => filesize($gradingPdfPath),
  1788. ]);
  1789. // 合并PDF文件
  1790. $mergedPdfPath = $tempDir."/{$paperId}_merged.pdf";
  1791. $merged = $this->pdfMerger->merge([$examPdfPath, $gradingPdfPath], $mergedPdfPath);
  1792. if (! $merged) {
  1793. Log::error('ExamPdfExportService: PDF文件合并失败', [
  1794. 'tool' => $this->pdfMerger->getMergeTool(),
  1795. ]);
  1796. return null;
  1797. }
  1798. // 读取合并后的PDF内容并上传到云存储
  1799. $mergedPdfContent = file_get_contents($mergedPdfPath);
  1800. $paper = Paper::where('paper_id', $paperId)->first();
  1801. if (! $paper) {
  1802. Log::error('ExamPdfExportService: 合并PDF失败,未找到试卷', ['paper_id' => $paperId]);
  1803. return null;
  1804. }
  1805. $allPdfName = $this->buildPdfFileName($paper);
  1806. $path = "exams/{$allPdfName}";
  1807. $mergedUrl = $this->pdfStorageService->put($path, $mergedPdfContent);
  1808. if (! $mergedUrl) {
  1809. Log::error('ExamPdfExportService: 保存合并PDF失败', ['path' => $path]);
  1810. return null;
  1811. }
  1812. // 保存到数据库的all_pdf_url字段
  1813. $this->saveAllPdfUrlToDatabase($paperId, $mergedUrl);
  1814. Log::info('generateMergedPdf 完成:', [
  1815. 'paper_id' => $paperId,
  1816. 'url' => $mergedUrl,
  1817. 'tool' => $this->pdfMerger->getMergeTool(),
  1818. ]);
  1819. return $mergedUrl;
  1820. } catch (\Throwable $e) {
  1821. Log::error('ExamPdfExportService: 生成合并PDF失败', [
  1822. 'paper_id' => $paperId,
  1823. 'error' => $e->getMessage(),
  1824. 'trace' => $e->getTraceAsString(),
  1825. ]);
  1826. return null;
  1827. } finally {
  1828. // 【修复】清理临时文件
  1829. $tempFiles = [$examPdfPath, $gradingPdfPath, $mergedPdfPath];
  1830. foreach ($tempFiles as $file) {
  1831. if ($file && file_exists($file)) {
  1832. @unlink($file);
  1833. }
  1834. }
  1835. Log::debug('清理临时文件完成');
  1836. }
  1837. }
  1838. /**
  1839. * 将URL转换为本地文件路径
  1840. */
  1841. private function convertUrlToPath(string $url): ?string
  1842. {
  1843. // 如果是本地存储,URL格式类似:/storage/exams/paper_id_exam.pdf
  1844. // 需要转换为绝对路径
  1845. if (strpos($url, '/storage/') === 0) {
  1846. return public_path(ltrim($url, '/'));
  1847. }
  1848. // 如果是完整路径,直接返回
  1849. if (strpos($url, '/') === 0 && file_exists($url)) {
  1850. return $url;
  1851. }
  1852. // 如果是相对路径,转换为绝对路径
  1853. $path = public_path($url);
  1854. if (file_exists($path)) {
  1855. return $path;
  1856. }
  1857. return null;
  1858. }
  1859. /**
  1860. * 【新增】获取知识点讲解HTML
  1861. */
  1862. private function fetchKnowledgeExplanationHtml(string $paperId): ?string
  1863. {
  1864. $html = $this->renderKnowledgeExplanationHtmlFromController($paperId);
  1865. if ($html !== null) {
  1866. return $html;
  1867. }
  1868. try {
  1869. $url = route('filament.admin.auth.intelligent-exam.knowledge-explanation', ['paper_id' => $paperId]);
  1870. $timeout = max(1, (int) config('pdf.kp_explain_fetch_timeout_seconds', 2));
  1871. $response = Http::timeout($timeout)->get($url);
  1872. if ($response->successful()) {
  1873. $html = $response->body();
  1874. if (! empty(trim($html))) {
  1875. Log::info('ExamPdfExportService: 成功获取知识点讲解HTML', [
  1876. 'paper_id' => $paperId,
  1877. 'length' => strlen($html),
  1878. ]);
  1879. $html = $this->ensureUtf8Html($html);
  1880. $html = $this->renderKpExplainMarkdown($html);
  1881. return $html;
  1882. }
  1883. }
  1884. Log::warning('ExamPdfExportService: 获取知识点讲解HTML失败', [
  1885. 'paper_id' => $paperId,
  1886. 'url' => $url,
  1887. 'timeout_seconds' => $timeout,
  1888. ]);
  1889. return null;
  1890. } catch (\Exception $e) {
  1891. Log::warning('ExamPdfExportService: 获取知识点讲解HTML异常', [
  1892. 'paper_id' => $paperId,
  1893. 'error' => $e->getMessage(),
  1894. 'timeout_seconds' => config('pdf.kp_explain_fetch_timeout_seconds', 2),
  1895. ]);
  1896. return null;
  1897. }
  1898. }
  1899. private function renderKnowledgeExplanationHtmlFromController(string $paperId): ?string
  1900. {
  1901. try {
  1902. $request = Request::create("/admin/intelligent-exam/knowledge-explanation/{$paperId}", 'GET');
  1903. $result = app(ExamPdfController::class)->showKnowledgeExplanation($request, $paperId);
  1904. $html = $this->renderControllerResultToHtml($result);
  1905. if ($html === null || trim($html) === '') {
  1906. return null;
  1907. }
  1908. Log::info('ExamPdfExportService: 本地渲染知识点讲解HTML成功', [
  1909. 'paper_id' => $paperId,
  1910. 'length' => strlen($html),
  1911. ]);
  1912. $html = $this->ensureUtf8Html($html);
  1913. return $this->renderKpExplainMarkdown($html);
  1914. } catch (\Throwable $e) {
  1915. Log::warning('ExamPdfExportService: 本地渲染知识点讲解HTML异常,将回退HTTP', [
  1916. 'paper_id' => $paperId,
  1917. 'error' => $e->getMessage(),
  1918. ]);
  1919. return null;
  1920. }
  1921. }
  1922. private function renderKpExplainMarkdown(string $html): string
  1923. {
  1924. return preg_replace_callback(
  1925. '/<div class="kp-markdown-source"[^>]*>([\s\S]*?)<\/div>\s*<div class="kp-markdown-container[^"]*"[^>]*><\/div>/i',
  1926. function ($matches) {
  1927. $markdown = html_entity_decode(trim($matches[1]), ENT_QUOTES, 'UTF-8');
  1928. $rendered = $this->renderKpMarkdownContent($markdown);
  1929. return '<div class="kp-markdown-container kp-markdown-content">'.$rendered.'</div>';
  1930. },
  1931. $html
  1932. );
  1933. }
  1934. private function renderExamHtml(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
  1935. {
  1936. // PDF worker 已经运行在 Laravel 进程内,优先直接渲染 Blade,避免 HTTP 自调用开销。
  1937. $html = $this->renderExamHtmlFromView($paperId, $includeAnswer, $useGradingView);
  1938. if ($html !== null) {
  1939. return $html;
  1940. }
  1941. try {
  1942. // 兜底:保留原 HTTP 路由渲染路径,避免特殊页面上下文下直接视图失败。
  1943. $routeName = $useGradingView
  1944. ? 'filament.admin.auth.intelligent-exam.grading'
  1945. : 'filament.admin.auth.intelligent-exam.pdf';
  1946. $url = route($routeName, ['paper_id' => $paperId, 'answer' => $includeAnswer ? 'true' : 'false']);
  1947. $response = Http::get($url);
  1948. if ($response->successful()) {
  1949. $html = $response->body();
  1950. if (! empty(trim($html))) {
  1951. return $this->ensureUtf8Html($html);
  1952. }
  1953. }
  1954. Log::warning('ExamPdfExportService: 通过HTTP获取试卷HTML失败', [
  1955. 'paper_id' => $paperId,
  1956. 'url' => $url,
  1957. ]);
  1958. } catch (\Exception $e) {
  1959. Log::warning('ExamPdfExportService: 通过HTTP获取试卷HTML异常', [
  1960. 'paper_id' => $paperId,
  1961. 'error' => $e->getMessage(),
  1962. ]);
  1963. }
  1964. return null;
  1965. }
  1966. /**
  1967. * 备用方案:直接渲染视图生成试卷HTML
  1968. */
  1969. private function renderExamHtmlFromView(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
  1970. {
  1971. try {
  1972. $request = Request::create(
  1973. $useGradingView
  1974. ? "/admin/intelligent-exam/grading/{$paperId}"
  1975. : "/admin/intelligent-exam/pdf/{$paperId}",
  1976. 'GET',
  1977. ['answer' => $includeAnswer ? 'true' : 'false']
  1978. );
  1979. $controller = app(ExamPdfController::class);
  1980. $result = $useGradingView
  1981. ? $controller->showGrading($request, $paperId)
  1982. : $controller->show($request, $paperId);
  1983. $html = $this->renderControllerResultToHtml($result);
  1984. if ($html === null || trim($html) === '') {
  1985. Log::error('ExamPdfExportService: 视图渲染结果为空', [
  1986. 'paper_id' => $paperId,
  1987. 'use_grading_view' => $useGradingView,
  1988. ]);
  1989. return null;
  1990. }
  1991. return $this->ensureUtf8Html($html);
  1992. } catch (\Exception $e) {
  1993. Log::error('ExamPdfExportService: 备用方案渲染失败', [
  1994. 'paper_id' => $paperId,
  1995. 'error' => $e->getMessage(),
  1996. 'trace' => $e->getTraceAsString(),
  1997. ]);
  1998. return null;
  1999. }
  2000. }
  2001. private function renderControllerResultToHtml(mixed $result): ?string
  2002. {
  2003. if (is_string($result)) {
  2004. return $result;
  2005. }
  2006. if (is_object($result) && method_exists($result, 'render')) {
  2007. return $result->render();
  2008. }
  2009. if (is_object($result) && method_exists($result, 'getContent')) {
  2010. return $result->getContent();
  2011. }
  2012. return null;
  2013. }
  2014. /**
  2015. * 构建分析数据(重构版)
  2016. * 优先使用本地MySQL数据,减少API依赖
  2017. */
  2018. private function buildAnalysisData(string $paperId, string $studentId): ?array
  2019. {
  2020. $paper = Paper::with(['questions' => function ($query) {
  2021. $query->orderBy('question_number')->orderBy('id');
  2022. }])->find($paperId);
  2023. if (! $paper) {
  2024. Log::warning('ExamPdfExportService: 未找到试卷,将尝试仅基于分析数据生成PDF', [
  2025. 'paper_id' => $paperId,
  2026. 'student_id' => $studentId,
  2027. ]);
  2028. // 【修复】即使试卷不存在,也尝试基于分析数据生成PDF
  2029. $paper = new \stdClass;
  2030. $paper->paper_id = $paperId;
  2031. $paper->paper_name = "学情分析报告_{$studentId}_{$paperId}";
  2032. $paper->question_count = 0;
  2033. $paper->total_score = 0;
  2034. $paper->created_at = now();
  2035. $paper->questions = collect();
  2036. }
  2037. $student = Student::find($studentId);
  2038. $studentInfo = [
  2039. 'id' => $student?->student_id ?? $studentId,
  2040. 'name' => $student?->name ?? $studentId,
  2041. 'grade' => $student?->grade ?? '未知年级',
  2042. 'class' => $student?->class_name ?? '未知班级',
  2043. ];
  2044. $teacherInfo = $this->getTeacherInfo((string) ($paper->teacher_id ?? ''));
  2045. $assembleType = ($paper->paper_type === null || $paper->paper_type === '')
  2046. ? null
  2047. : (int) $paper->paper_type;
  2048. try {
  2049. $assembleTypeLabel = $assembleType !== null ? PaperNaming::assembleTypeLabel($assembleType) : '未知类型';
  2050. } catch (\Throwable $e) {
  2051. $assembleTypeLabel = '未知类型';
  2052. }
  2053. // 【修改】直接从本地数据库获取分析数据(不再调用API)
  2054. $analysisData = [];
  2055. // 首先尝试从paper->analysis_id获取
  2056. if (! empty($paper->analysis_id)) {
  2057. $analysisRecord = \DB::table('exam_analysis_results')
  2058. ->where('id', $paper->analysis_id)
  2059. ->where('student_id', $studentId)
  2060. ->first();
  2061. if ($analysisRecord && ! empty($analysisRecord->analysis_data)) {
  2062. $analysisData = json_decode($analysisRecord->analysis_data, true);
  2063. } else {
  2064. Log::warning('ExamPdfExportService: 未找到本地分析数据,将尝试其他方式', [
  2065. 'paper_id' => $paperId,
  2066. 'student_id' => $studentId,
  2067. 'analysis_id' => $paper->analysis_id,
  2068. ]);
  2069. }
  2070. }
  2071. // 如果没有analysis_id或未找到数据,直接从exam_analysis_results表查询
  2072. if (empty($analysisData)) {
  2073. $analysisRecord = \DB::table('exam_analysis_results')
  2074. ->where('paper_id', $paperId)
  2075. ->where('student_id', $studentId)
  2076. ->orderByDesc('created_at')
  2077. ->first();
  2078. if ($analysisRecord && ! empty($analysisRecord->analysis_data)) {
  2079. $analysisData = json_decode($analysisRecord->analysis_data, true);
  2080. } else {
  2081. Log::warning('ExamPdfExportService: 未找到任何分析数据,将使用空数据', [
  2082. 'paper_id' => $paperId,
  2083. 'student_id' => $studentId,
  2084. ]);
  2085. }
  2086. }
  2087. // 【修复】优先使用analysisData中的knowledge_point_analysis数据
  2088. $masteryData = [];
  2089. $parentMasteryLevels = []; // 新增:父节点掌握度数据
  2090. $fullMasteryMap = [];
  2091. $snapshotMasteryData = [];
  2092. $snapshotCurrentMasteryMap = [];
  2093. if (! empty($analysisData['knowledge_point_analysis'])) {
  2094. // 将knowledge_point_analysis转换为buildMasterySummary期望的格式
  2095. foreach ($analysisData['knowledge_point_analysis'] as $kp) {
  2096. $masteryData[] = [
  2097. 'kp_code' => $kp['kp_id'] ?? null,
  2098. 'kp_name' => $kp['kp_id'] ?? '未知知识点',
  2099. 'mastery_level' => $kp['mastery_level'] ?? 0,
  2100. 'mastery_change' => $kp['change'] ?? null,
  2101. ];
  2102. }
  2103. // 【修复】基于所有兄弟节点历史数据计算父节点掌握度,并获取掌握度变化
  2104. try {
  2105. // 获取本次考试涉及的知识点代码列表
  2106. $examKpCodes = array_column($masteryData, 'kp_code');
  2107. // 获取最新快照的数据(mastery_data 内已包含 current_mastery 和 previous_mastery)
  2108. $lastSnapshot = DB::connection('mysql')
  2109. ->table('knowledge_point_mastery_snapshots')
  2110. ->where('student_id', $studentId)
  2111. ->where('paper_id', $paper->paper_id)
  2112. ->latest('snapshot_time')
  2113. ->first();
  2114. $previousMasteryData = [];
  2115. $snapshotMasteryData = [];
  2116. if ($lastSnapshot) {
  2117. $currentMasteryJson = json_decode((string) ($lastSnapshot->current_mastery ?? ''), true);
  2118. if (is_array($currentMasteryJson)) {
  2119. foreach ($currentMasteryJson as $kpCode => $level) {
  2120. $code = trim((string) $kpCode);
  2121. if ($code !== '' && is_numeric($level)) {
  2122. $snapshotCurrentMasteryMap[$code] = floatval($level);
  2123. }
  2124. }
  2125. }
  2126. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  2127. if (is_array($previousMasteryJson)) {
  2128. foreach ($previousMasteryJson as $kpCode => $data) {
  2129. if (! is_array($data)) {
  2130. continue;
  2131. }
  2132. $snapshotMasteryData[$kpCode] = [
  2133. 'current_mastery' => isset($data['current_mastery']) ? floatval($data['current_mastery']) : null,
  2134. 'previous_mastery' => isset($data['previous_mastery']) ? floatval($data['previous_mastery']) : null,
  2135. 'change' => isset($data['change']) ? floatval($data['change']) : null,
  2136. ];
  2137. $code = trim((string) $kpCode);
  2138. if (
  2139. $code !== ''
  2140. && ! array_key_exists($code, $snapshotCurrentMasteryMap)
  2141. && isset($data['current_mastery'])
  2142. && is_numeric($data['current_mastery'])
  2143. ) {
  2144. $snapshotCurrentMasteryMap[$code] = floatval($data['current_mastery']);
  2145. }
  2146. $previousMasteryData[$kpCode] = [
  2147. 'current_mastery' => $data['current_mastery'] ?? 0,
  2148. 'previous_mastery' => $data['previous_mastery'] ?? null,
  2149. ];
  2150. }
  2151. }
  2152. Log::info('ExamPdfExportService: 获取到上一次快照数据', [
  2153. 'snapshot_time' => $lastSnapshot->snapshot_time,
  2154. 'kp_count' => count($previousMasteryData),
  2155. 'current_mastery_count' => count($snapshotCurrentMasteryMap),
  2156. ]);
  2157. }
  2158. // 为当前知识点添加变化数据
  2159. foreach ($masteryData as &$item) {
  2160. $kpCode = $item['kp_code'];
  2161. if (isset($previousMasteryData[$kpCode]) && $previousMasteryData[$kpCode]['previous_mastery'] !== null) {
  2162. $previous = floatval($previousMasteryData[$kpCode]['previous_mastery']);
  2163. $current = floatval($item['mastery_level']);
  2164. $item['mastery_change'] = $current - $previous;
  2165. }
  2166. }
  2167. unset($item); // 解除引用
  2168. // 获取所有父节点掌握度
  2169. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  2170. $allParentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? [];
  2171. $overviewDetails = $masteryOverview['details'] ?? [];
  2172. foreach ($overviewDetails as $detail) {
  2173. if (is_object($detail)) {
  2174. $code = $detail->kp_code ?? null;
  2175. if ($code) {
  2176. $fullMasteryMap[$code] = floatval($detail->mastery_level ?? 0);
  2177. }
  2178. } elseif (is_array($detail)) {
  2179. $code = $detail['kp_code'] ?? null;
  2180. if ($code) {
  2181. $fullMasteryMap[$code] = floatval($detail['mastery_level'] ?? 0);
  2182. }
  2183. }
  2184. }
  2185. // 计算与本次考试相关的父节点掌握度(基于所有兄弟节点)
  2186. $parentMasteryLevels = [];
  2187. $parentCodes = array_values(array_unique(array_filter(array_map(static fn ($code) => trim((string) $code), array_keys($allParentMasteryLevels)))));
  2188. if ($parentCodes !== []) {
  2189. $childRows = DB::connection('mysql')
  2190. ->table('knowledge_points')
  2191. ->whereIn('parent_kp_code', $parentCodes)
  2192. ->select(['parent_kp_code', 'kp_code'])
  2193. ->get();
  2194. $childrenByParent = [];
  2195. foreach ($childRows as $row) {
  2196. $parentCode = trim((string) ($row->parent_kp_code ?? ''));
  2197. $childCode = trim((string) ($row->kp_code ?? ''));
  2198. if ($parentCode === '' || $childCode === '') {
  2199. continue;
  2200. }
  2201. $childrenByParent[$parentCode][] = $childCode;
  2202. }
  2203. $parentNameMap = DB::connection('mysql')
  2204. ->table('knowledge_points')
  2205. ->whereIn('kp_code', $parentCodes)
  2206. ->pluck('name', 'kp_code')
  2207. ->toArray();
  2208. foreach ($allParentMasteryLevels as $parentKpCode => $parentMastery) {
  2209. $parentKpCode = trim((string) $parentKpCode);
  2210. if ($parentKpCode === '') {
  2211. continue;
  2212. }
  2213. $childNodes = $childrenByParent[$parentKpCode] ?? [];
  2214. if ($childNodes === []) {
  2215. continue;
  2216. }
  2217. // 检查是否有子节点在本次考试中出现
  2218. $relevantChildren = array_intersect($examKpCodes, $childNodes);
  2219. if (empty($relevantChildren)) {
  2220. continue;
  2221. }
  2222. // 口径统一:父节点掌握度 = 全部直接子节点(含未命中,缺失按0)均值
  2223. $childCurrentLevels = [];
  2224. $childPreviousLevels = [];
  2225. foreach ($childNodes as $childKpCode) {
  2226. $currentChild = floatval($fullMasteryMap[$childKpCode] ?? 0);
  2227. $childCurrentLevels[] = $currentChild;
  2228. $prevFromSnapshot = $snapshotMasteryData[$childKpCode]['previous_mastery'] ?? null;
  2229. $currFromSnapshot = $snapshotMasteryData[$childKpCode]['current_mastery'] ?? null;
  2230. $previousChild = $prevFromSnapshot ?? $currFromSnapshot ?? $currentChild;
  2231. $childPreviousLevels[] = floatval($previousChild);
  2232. }
  2233. $finalParentMastery = ! empty($childCurrentLevels)
  2234. ? array_sum($childCurrentLevels) / count($childCurrentLevels)
  2235. : floatval($parentMastery);
  2236. $previousParentMastery = ! empty($childPreviousLevels)
  2237. ? array_sum($childPreviousLevels) / count($childPreviousLevels)
  2238. : $finalParentMastery;
  2239. $finalParentChange = $finalParentMastery - $previousParentMastery;
  2240. $parentMasteryLevels[$parentKpCode] = [
  2241. 'kp_code' => $parentKpCode,
  2242. 'kp_name' => $parentNameMap[$parentKpCode] ?? $parentKpCode,
  2243. 'mastery_level' => $finalParentMastery,
  2244. 'mastery_percentage' => round($finalParentMastery * 100, 1),
  2245. 'mastery_change' => $finalParentChange,
  2246. 'change_source' => 'children_all_average',
  2247. 'children' => $relevantChildren,
  2248. ];
  2249. }
  2250. }
  2251. } catch (\Exception $e) {
  2252. Log::warning('ExamPdfExportService: 获取父节点掌握度失败', [
  2253. 'error' => $e->getMessage(),
  2254. ]);
  2255. }
  2256. } else {
  2257. // 如果没有knowledge_point_analysis,使用MasteryCalculator获取多层级掌握度概览
  2258. try {
  2259. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  2260. $masteryData = $masteryOverview['details'] ?? [];
  2261. $parentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? []; // 获取父节点掌握度
  2262. // 【修复】将对象数组转换为关联数组(避免 stdClass 对象访问错误)
  2263. if (! empty($masteryData) && is_array($masteryData)) {
  2264. $masteryData = array_map(function ($item) {
  2265. if (is_object($item)) {
  2266. $kpCode = $item->kp_code ?? null;
  2267. return [
  2268. 'kp_code' => $kpCode,
  2269. 'kp_name' => $item->kp_name ?? null,
  2270. 'mastery_level' => floatval($item->mastery_level ?? 0),
  2271. 'mastery_change' => $item->mastery_change !== null ? floatval($item->mastery_change) : null,
  2272. ];
  2273. }
  2274. return $item;
  2275. }, $masteryData);
  2276. }
  2277. foreach ($masteryData as $m) {
  2278. $code = $m['kp_code'] ?? null;
  2279. if ($code) {
  2280. $fullMasteryMap[$code] = floatval($m['mastery_level'] ?? 0);
  2281. }
  2282. }
  2283. // 【修复】获取快照数据以计算掌握度变化
  2284. $lastSnapshot = DB::connection('mysql')
  2285. ->table('knowledge_point_mastery_snapshots')
  2286. ->where('student_id', $studentId)
  2287. ->latest('snapshot_time')
  2288. ->first();
  2289. if ($lastSnapshot) {
  2290. $currentMasteryJson = json_decode((string) ($lastSnapshot->current_mastery ?? ''), true);
  2291. if (is_array($currentMasteryJson)) {
  2292. foreach ($currentMasteryJson as $kpCode => $level) {
  2293. $code = trim((string) $kpCode);
  2294. if ($code !== '' && is_numeric($level)) {
  2295. $snapshotCurrentMasteryMap[$code] = floatval($level);
  2296. }
  2297. }
  2298. }
  2299. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  2300. if (is_array($previousMasteryJson)) {
  2301. foreach ($masteryData as &$item) {
  2302. $kpCode = $item['kp_code'];
  2303. if (isset($previousMasteryJson[$kpCode]) && is_array($previousMasteryJson[$kpCode])) {
  2304. $snapshotNode = $previousMasteryJson[$kpCode];
  2305. $code = trim((string) $kpCode);
  2306. if (
  2307. $code !== ''
  2308. && ! array_key_exists($code, $snapshotCurrentMasteryMap)
  2309. && isset($snapshotNode['current_mastery'])
  2310. && is_numeric($snapshotNode['current_mastery'])
  2311. ) {
  2312. $snapshotCurrentMasteryMap[$code] = floatval($snapshotNode['current_mastery']);
  2313. }
  2314. $previous = floatval($previousMasteryJson[$kpCode]['previous_mastery'] ?? 0);
  2315. $current = floatval($item['mastery_level']);
  2316. $item['mastery_change'] = $current - $previous;
  2317. }
  2318. }
  2319. unset($item);
  2320. }
  2321. }
  2322. } catch (\Exception $e) {
  2323. Log::error('ExamPdfExportService: 获取掌握度数据失败', [
  2324. 'student_id' => $studentId,
  2325. 'error' => $e->getMessage(),
  2326. ]);
  2327. }
  2328. }
  2329. // V3 PDF 会在 reduceTemplateDataForV3 中丢弃 recommendations,这里不再计算未展示的推荐数据。
  2330. $recommendations = [];
  2331. // 获取知识点名称映射
  2332. $kpNameMap = $this->buildKnowledgePointNameMap();
  2333. // 【修复】直接从MySQL数据库获取题目详情(不通过API)
  2334. // 只有当 $paper 是 Paper 模型时才查询题目详情
  2335. $questionDetails = ($paper instanceof \App\Models\Paper)
  2336. ? $this->getQuestionDetailsFromMySQL($paper)
  2337. : [];
  2338. // 处理题目数据
  2339. $questions = $this->processQuestionsForReport($paper, $questionDetails, $kpNameMap);
  2340. // 【关键调试】查看buildMasterySummary的返回结果
  2341. $masterySummary = $this->buildMasterySummary($masteryData, $kpNameMap);
  2342. // 构建当前学生掌握度映射,供父子影响分析展示使用
  2343. // 与 PC 端保持一致:优先使用当前报告/学案对应快照的 current_mastery。
  2344. $masteryMap = !empty($snapshotCurrentMasteryMap)
  2345. ? $snapshotCurrentMasteryMap
  2346. : (!empty($fullMasteryMap) ? $fullMasteryMap : []);
  2347. if (empty($masteryMap)) {
  2348. foreach ($masteryData as $m) {
  2349. $code = $m['kp_code'] ?? null;
  2350. if ($code) {
  2351. $masteryMap[$code] = floatval($m['mastery_level'] ?? 0);
  2352. }
  2353. }
  2354. }
  2355. // 本卷命中知识点:严格按“这套卷子题目关联知识点”计算
  2356. $examQuestionKpCodes = array_values(array_unique(array_filter(array_map(
  2357. fn ($q) => trim((string) ($q['knowledge_point'] ?? '')),
  2358. $questions
  2359. ))));
  2360. // 父节点列表:直接按“本卷命中子知识点”反查父节点,避免历史全集/补齐口径带偏
  2361. $processedParentMastery = $this->buildParentMasteryFromHitCodes(
  2362. $examQuestionKpCodes,
  2363. $kpNameMap,
  2364. $masteryMap,
  2365. $snapshotMasteryData
  2366. );
  2367. return [
  2368. 'paper' => [
  2369. 'id' => $paper->paper_id,
  2370. 'name' => $paper->paper_name,
  2371. 'paper_type' => $paper->paper_type,
  2372. 'difficulty_category' => $paper->difficulty_category,
  2373. 'assemble_type_label' => $assembleTypeLabel,
  2374. 'total_questions' => $paper->question_count,
  2375. 'total_score' => $paper->total_score,
  2376. 'created_at' => $paper->created_at,
  2377. ],
  2378. 'student' => $studentInfo,
  2379. 'teacher' => $teacherInfo,
  2380. 'questions' => $questions,
  2381. 'mastery' => $masterySummary,
  2382. 'exam_hit_kp_codes' => $examQuestionKpCodes,
  2383. 'parent_mastery_levels' => $processedParentMastery, // 【修复】使用处理后的父节点数据
  2384. 'insights' => $analysisData['question_analysis'] ?? [], // 使用question_analysis替代question_results
  2385. 'recommendations' => $recommendations,
  2386. 'analysis_data' => $analysisData,
  2387. 'mastery_map' => $masteryMap,
  2388. ];
  2389. }
  2390. /**
  2391. * 【修复】直接从PaperQuestion表获取题目详情(不通过API)
  2392. */
  2393. private function getQuestionDetailsFromMySQL(Paper $paper): array
  2394. {
  2395. $details = [];
  2396. Log::info('ExamPdfExportService: 从PaperQuestion表查询题目详情', [
  2397. 'paper_id' => $paper->paper_id,
  2398. 'question_count' => $paper->questions->count(),
  2399. ]);
  2400. foreach ($paper->questions as $pq) {
  2401. try {
  2402. // 【关键修复】直接从PaperQuestion对象获取solution和correct_answer
  2403. $detail = [
  2404. 'id' => $pq->question_id,
  2405. 'content' => $pq->question_text,
  2406. 'question_type' => $pq->question_type,
  2407. 'answer' => $pq->correct_answer ?? null, // 【修复】从PaperQuestion获取正确答案
  2408. 'solution' => $pq->solution ?? null, // 【修复】从PaperQuestion获取解题思路
  2409. ];
  2410. $details[(string) ($pq->question_id ?? $pq->id)] = $detail;
  2411. Log::debug('ExamPdfExportService: 成功获取题目详情', [
  2412. 'paper_question_id' => $pq->id,
  2413. 'question_id' => $pq->question_id,
  2414. 'has_answer' => ! empty($pq->correct_answer),
  2415. 'has_solution' => ! empty($pq->solution),
  2416. 'answer_preview' => $pq->correct_answer ? substr($pq->correct_answer, 0, 50) : null,
  2417. ]);
  2418. } catch (\Throwable $e) {
  2419. Log::error('ExamPdfExportService: 获取题目详情失败', [
  2420. 'paper_question_id' => $pq->id,
  2421. 'error' => $e->getMessage(),
  2422. ]);
  2423. }
  2424. }
  2425. return $details;
  2426. }
  2427. /**
  2428. * 将题库 options 转为 [A=>文本, B=>文本, ...],供学情报告展示
  2429. *
  2430. * @param mixed $raw questions.options(JSON/数组)
  2431. * @return array<string, string>
  2432. */
  2433. private function normalizeChoiceOptionsMap($raw): array
  2434. {
  2435. if ($raw === null || $raw === '') {
  2436. return [];
  2437. }
  2438. if (is_string($raw)) {
  2439. $decoded = json_decode($raw, true);
  2440. $raw = is_array($decoded) ? $decoded : [];
  2441. }
  2442. if (! is_array($raw)) {
  2443. return [];
  2444. }
  2445. $out = [];
  2446. foreach ($raw as $k => $v) {
  2447. if (is_string($k) && preg_match('/([A-H])/i', $k, $m)) {
  2448. $letter = strtoupper($m[1]);
  2449. $text = is_array($v)
  2450. ? (string) ($v['content'] ?? $v['text'] ?? $v['value'] ?? '')
  2451. : (string) $v;
  2452. $text = trim($text);
  2453. if ($text !== '') {
  2454. $out[$letter] = $text;
  2455. }
  2456. }
  2457. }
  2458. if (! empty($out)) {
  2459. return $out;
  2460. }
  2461. $letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
  2462. $i = 0;
  2463. foreach ($raw as $v) {
  2464. if ($i >= count($letters)) {
  2465. break;
  2466. }
  2467. $text = is_array($v)
  2468. ? (string) ($v['content'] ?? $v['text'] ?? $v['value'] ?? '')
  2469. : (string) $v;
  2470. $text = trim($text);
  2471. if ($text !== '') {
  2472. $out[$letters[$i]] = $text;
  2473. }
  2474. $i++;
  2475. }
  2476. return $out;
  2477. }
  2478. /**
  2479. * 从题干 HTML 中解析选项(与 ExamPdfController::extractOptions 口径一致,输出为字母=>文本)
  2480. *
  2481. * @return array<string, string>
  2482. */
  2483. private function extractChoiceOptionsFromStem(string $content): array
  2484. {
  2485. $out = [];
  2486. $contentWithoutSvg = preg_replace('/<svg[^>]*>.*?<\/svg>/is', '[SVG_PLACEHOLDER]', $content);
  2487. $pattern = '/(?:^|\s)([A-H])[\.、:.:]\s*(.+?)(?=(?:^|\s)[A-H][\.、:.:]|$)/su';
  2488. if (preg_match_all($pattern, $contentWithoutSvg, $matches, PREG_SET_ORDER)) {
  2489. foreach ($matches as $match) {
  2490. $letter = strtoupper($match[1]);
  2491. $optionText = trim($match[2]);
  2492. $optionText = preg_replace('/\s+$/', '', $optionText);
  2493. $optionText = preg_replace('/^\$\$\s*/', '', $optionText);
  2494. $optionText = preg_replace('/\s*\$\$$/', '', $optionText);
  2495. if ($optionText !== '') {
  2496. $out[$letter] = $optionText;
  2497. }
  2498. }
  2499. }
  2500. if (empty($out)) {
  2501. $lines = preg_split('/[\r\n]+/', $contentWithoutSvg);
  2502. foreach ($lines as $line) {
  2503. $line = trim($line);
  2504. if (preg_match('/^([A-H])[\.、:.:]\s*(.+)$/u', $line, $match)) {
  2505. $letter = strtoupper($match[1]);
  2506. $optionText = trim($match[2]);
  2507. if ($optionText !== '') {
  2508. $out[$letter] = $optionText;
  2509. }
  2510. }
  2511. }
  2512. }
  2513. return $out;
  2514. }
  2515. /**
  2516. * 处理题目数据(用于报告)
  2517. */
  2518. private function processQuestionsForReport($paper, array $questionDetails, array $kpNameMap): array
  2519. {
  2520. $grouped = [
  2521. 'choice' => [],
  2522. 'fill' => [],
  2523. 'answer' => [],
  2524. ];
  2525. // 【修复】处理空的试卷(questions可能不存在)
  2526. $questions = $paper->questions ?? collect();
  2527. if ($questions->isEmpty()) {
  2528. Log::info('ExamPdfExportService: 试卷没有题目,返回空数组');
  2529. return $grouped;
  2530. }
  2531. $sortedQuestions = $questions
  2532. ->sortBy(function ($q, int $idx) {
  2533. $number = $q->question_number ?? $idx + 1;
  2534. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  2535. });
  2536. $bankIds = $sortedQuestions->pluck('question_bank_id')->filter()->unique()->values()->all();
  2537. $optionsByBankId = [];
  2538. if (! empty($bankIds)) {
  2539. $optionsByBankId = Question::whereIn('id', $bankIds)
  2540. ->pluck('options', 'id')
  2541. ->toArray();
  2542. }
  2543. foreach ($sortedQuestions as $idx => $question) {
  2544. $kpCode = $question->knowledge_point ?? '';
  2545. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  2546. // 【修复】直接从PaperQuestion对象获取solution和correct_answer
  2547. $answer = $question->correct_answer ?? null; // 直接从PaperQuestion获取
  2548. $solution = $question->solution ?? null; // 直接从PaperQuestion获取
  2549. $detail = $questionDetails[(string) ($question->question_id ?? $question->id)] ?? [];
  2550. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  2551. $normalizedType = $this->normalizeQuestionType($typeRaw);
  2552. $number = $question->question_number ?? ($idx + 1);
  2553. // 处理题干文本
  2554. $questionText = is_array($question->question_text)
  2555. ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
  2556. : ($question->question_text ?? '');
  2557. $optionsFromBank = $question->question_bank_id
  2558. ? ($optionsByBankId[$question->question_bank_id] ?? null)
  2559. : null;
  2560. $choiceOptionsMap = $this->normalizeChoiceOptionsMap($optionsFromBank);
  2561. if (empty($choiceOptionsMap) && $normalizedType === 'choice') {
  2562. $choiceOptionsMap = $this->extractChoiceOptionsFromStem((string) $questionText);
  2563. }
  2564. $questionTextForPayload = $this->formatNewlines($questionText);
  2565. $questionTextPreprocessed = false;
  2566. if ($normalizedType === 'choice') {
  2567. $questionTextForPayload = GradingStyleQuestionStem::buildChoiceStemForReport(
  2568. (string) $questionTextForPayload
  2569. );
  2570. $questionTextPreprocessed = true;
  2571. }
  2572. $payload = [
  2573. 'question_id' => $question->question_id ?? null,
  2574. 'question_bank_id' => $question->question_bank_id ?? $question->question_id ?? null,
  2575. 'question_number' => $number,
  2576. 'question_text' => $questionTextForPayload,
  2577. 'question_text_preprocessed' => $questionTextPreprocessed,
  2578. 'question_type' => $normalizedType,
  2579. 'knowledge_point' => $kpCode,
  2580. 'knowledge_point_name' => $kpName,
  2581. 'difficulty' => isset($question->difficulty) ? (float) $question->difficulty : null,
  2582. 'score' => $question->score,
  2583. 'answer' => $this->formatNewlines($answer), // 格式化换行
  2584. 'solution' => $this->formatNewlines($solution), // 格式化换行
  2585. 'student_answer' => $this->formatNewlines($question->student_answer ?? null), // 格式化换行
  2586. 'correct_answer' => $this->formatNewlines($answer), // 格式化换行
  2587. 'is_correct' => $question->is_correct ?? null,
  2588. 'score_obtained' => $question->score_obtained ?? null,
  2589. 'options' => $choiceOptionsMap,
  2590. ];
  2591. $grouped[$normalizedType][] = $payload;
  2592. // 【调试】记录题目数据
  2593. Log::debug('ExamPdfExportService: 处理题目数据', [
  2594. 'paper_question_id' => $question->id,
  2595. 'question_id' => $question->question_id,
  2596. 'has_answer' => ! empty($answer),
  2597. 'has_solution' => ! empty($solution),
  2598. 'answer_preview' => $answer ? substr($answer, 0, 50) : null,
  2599. ]);
  2600. }
  2601. $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  2602. // 按卷面顺序重新编号
  2603. foreach ($ordered as $i => &$q) {
  2604. $q['display_number'] = $i + 1;
  2605. }
  2606. unset($q);
  2607. return $ordered;
  2608. }
  2609. /**
  2610. * 构建PDF
  2611. */
  2612. private function buildPdf(string $html, bool $applyWideImageSizing = false, bool $scopeToExamPart = false): ?string
  2613. {
  2614. $startedAt = microtime(true);
  2615. $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_').'.html';
  2616. $prepareStartedAt = microtime(true);
  2617. $utf8Html = $this->ensureUtf8Html($html);
  2618. if ($applyWideImageSizing) {
  2619. $utf8Html = $scopeToExamPart
  2620. ? $this->applyAdaptiveWideImageSizingToExamPart($utf8Html)
  2621. : $this->applyAdaptiveWideImageSizing($utf8Html);
  2622. }
  2623. $written = file_put_contents($tmpHtml, $utf8Html);
  2624. Log::info('ExamPdfExportService: PDF HTML准备完成', [
  2625. 'path' => $tmpHtml,
  2626. 'html_length' => strlen($utf8Html),
  2627. 'written_bytes' => $written,
  2628. 'elapsed_ms' => (int) round((microtime(true) - $prepareStartedAt) * 1000),
  2629. ]);
  2630. // 【调试】如果启用了HTML保存调试,复制HTML到storage用于分析
  2631. if (config('pdf.debug_save_html', false)) {
  2632. $debugPath = storage_path('app/debug_pdf_'.date('YmdHis').'.html');
  2633. @copy($tmpHtml, $debugPath);
  2634. $this->lastDebugHtmlPath = $debugPath;
  2635. Log::debug('ExamPdfExportService: [DEBUG] HTML副本已保存', ['path' => $debugPath]);
  2636. }
  2637. $pdf = $this->renderWithConfiguredBackend($tmpHtml);
  2638. @unlink($tmpHtml);
  2639. Log::info('ExamPdfExportService: buildPdf完成', [
  2640. 'success' => $pdf !== null,
  2641. 'pdf_size' => $pdf !== null ? strlen($pdf) : null,
  2642. 'elapsed_ms' => (int) round((microtime(true) - $startedAt) * 1000),
  2643. ]);
  2644. return $pdf;
  2645. }
  2646. /**
  2647. * 根据配置选择 PDF 渲染后端。
  2648. */
  2649. private function renderWithConfiguredBackend(string $htmlPath): ?string
  2650. {
  2651. $renderer = strtolower(trim((string) config('pdf.renderer', 'gotenberg')));
  2652. if ($renderer === 'gotenberg') {
  2653. $pdf = $this->renderWithGotenberg($htmlPath);
  2654. if ($pdf !== null) {
  2655. return $pdf;
  2656. }
  2657. if ($this->shouldFallbackToChrome()) {
  2658. Log::warning('ExamPdfExportService: Gotenberg 渲染失败,回退 Chrome CLI', [
  2659. 'html_path' => $htmlPath,
  2660. ]);
  2661. return $this->renderWithChrome($htmlPath);
  2662. }
  2663. Log::error('ExamPdfExportService: Gotenberg 渲染失败,配置禁止回退 Chrome', [
  2664. 'html_path' => $htmlPath,
  2665. ]);
  2666. return null;
  2667. }
  2668. if ($renderer === 'chrome') {
  2669. return $this->renderWithChrome($htmlPath);
  2670. }
  2671. Log::error('ExamPdfExportService: 未识别的 PDF_RENDERER,拒绝渲染', [
  2672. 'renderer' => $renderer,
  2673. 'html_path' => $htmlPath,
  2674. 'supported_renderers' => ['gotenberg', 'chrome'],
  2675. ]);
  2676. return null;
  2677. }
  2678. /**
  2679. * 通过 Gotenberg 常驻服务生成 PDF。
  2680. */
  2681. private function renderWithGotenberg(string $htmlPath): ?string
  2682. {
  2683. $startedAt = microtime(true);
  2684. $baseUrl = rtrim((string) config('pdf.gotenberg_url', 'http://gotenberg:3000'), '/');
  2685. $connectTimeout = max(1, (int) config('pdf.gotenberg_connect_timeout_seconds', 3));
  2686. $timeout = max(5, (int) config('pdf.gotenberg_timeout_seconds', 60));
  2687. $trace = 'exam-pdf-'.basename($htmlPath).'-'.str_replace('.', '', uniqid('', true));
  2688. if ($baseUrl === '') {
  2689. Log::error('ExamPdfExportService: Gotenberg URL 为空', [
  2690. 'html_path' => $htmlPath,
  2691. ]);
  2692. return null;
  2693. }
  2694. if (! is_file($htmlPath)) {
  2695. Log::error('ExamPdfExportService: Gotenberg 渲染失败,HTML文件不存在', [
  2696. 'html_path' => $htmlPath,
  2697. ]);
  2698. return null;
  2699. }
  2700. try {
  2701. $htmlContent = file_get_contents($htmlPath);
  2702. if ($htmlContent === false) {
  2703. Log::error('ExamPdfExportService: Gotenberg 渲染失败,HTML文件读取失败', [
  2704. 'trace' => $trace,
  2705. 'html_path' => $htmlPath,
  2706. ]);
  2707. return null;
  2708. }
  2709. $response = Http::timeout($timeout)
  2710. ->connectTimeout($connectTimeout)
  2711. ->withHeaders([
  2712. 'Gotenberg-Trace' => $trace,
  2713. 'Gotenberg-Output-Filename' => 'exam.pdf',
  2714. ])
  2715. ->attach('files', $htmlContent, 'index.html')
  2716. ->post($baseUrl.'/forms/chromium/convert/html', [
  2717. 'preferCssPageSize' => 'true',
  2718. 'printBackground' => 'true',
  2719. ]);
  2720. $body = $response->body();
  2721. $contentType = strtolower((string) $response->header('Content-Type', ''));
  2722. $isPdfContent = str_contains($contentType, 'application/pdf')
  2723. || str_starts_with($body, '%PDF-');
  2724. if ($response->successful() && $isPdfContent && $body !== '') {
  2725. Log::info('ExamPdfExportService: Gotenberg 渲染成功', [
  2726. 'trace' => $trace,
  2727. 'status' => $response->status(),
  2728. 'pdf_size' => strlen($body),
  2729. 'content_type' => $contentType,
  2730. 'elapsed_ms' => (int) round((microtime(true) - $startedAt) * 1000),
  2731. ]);
  2732. return $body;
  2733. }
  2734. Log::error('ExamPdfExportService: Gotenberg 渲染失败', [
  2735. 'trace' => $trace,
  2736. 'status' => $response->status(),
  2737. 'body_size' => strlen($body),
  2738. 'content_type' => $contentType,
  2739. 'is_pdf_content' => $isPdfContent,
  2740. 'body_preview' => mb_substr($body, 0, 500),
  2741. 'elapsed_ms' => (int) round((microtime(true) - $startedAt) * 1000),
  2742. ]);
  2743. } catch (\Throwable $e) {
  2744. Log::error('ExamPdfExportService: Gotenberg 请求异常', [
  2745. 'trace' => $trace,
  2746. 'url' => $baseUrl,
  2747. 'error' => $e->getMessage(),
  2748. 'connect_timeout_seconds' => $connectTimeout,
  2749. 'timeout_seconds' => $timeout,
  2750. 'elapsed_ms' => (int) round((microtime(true) - $startedAt) * 1000),
  2751. ]);
  2752. }
  2753. return null;
  2754. }
  2755. private function shouldFallbackToChrome(): bool
  2756. {
  2757. return (bool) config('pdf.fallback_to_chrome', true);
  2758. }
  2759. /**
  2760. * 对扁长/超扁长图片做全局自适应放大,普通图片不处理。
  2761. */
  2762. private function applyAdaptiveWideImageSizing(string $html): string
  2763. {
  2764. return (string) preg_replace_callback(
  2765. '/<img\b[^>]*\bsrc=(["\'])([^"\']+)\1[^>]*>/i',
  2766. function (array $m): string {
  2767. $fullTag = $m[0] ?? '';
  2768. $src = $m[2] ?? '';
  2769. if ($fullTag === '' || $src === '' || str_starts_with($src, 'data:')) {
  2770. return $fullTag;
  2771. }
  2772. // 选项区图片使用独立规则,不参与全局宽图放大,避免 4 列选项被撑出边界
  2773. if (stripos($fullTag, 'data-option-image="1"') !== false || stripos($fullTag, "data-option-image='1'") !== false) {
  2774. return $fullTag;
  2775. }
  2776. if (! $this->shouldApplyAdaptiveSizingToSrc($src)) {
  2777. return $fullTag;
  2778. }
  2779. $dim = $this->getPdfImageDimensions($src);
  2780. if (! $dim || ($dim['w'] ?? 0) <= 0 || ($dim['h'] ?? 0) <= 0) {
  2781. return $fullTag;
  2782. }
  2783. $ratio = $dim['w'] / max(1, $dim['h']);
  2784. if ($ratio < 2.8) {
  2785. return $fullTag;
  2786. }
  2787. $targetWidth = $ratio >= 3.5 ? self::PDF_IMAGE_WIDTH_VERY_WIDE_PX : self::PDF_IMAGE_WIDTH_WIDE_PX;
  2788. $targetWidth = min($targetWidth, $dim['w']);
  2789. $targetStyle = sprintf(
  2790. 'width:%dpx!important;max-width:%dpx!important;max-height:60mm!important;height:auto!important;object-fit:contain!important;',
  2791. $targetWidth,
  2792. $targetWidth
  2793. );
  2794. if (preg_match('/\sstyle=(["\'])(.*?)\1/i', $fullTag, $sm)) {
  2795. $originStyle = $sm[2] ?? '';
  2796. $originStyle = preg_replace('/\bmax-width\s*:[^;]+;?/i', '', $originStyle);
  2797. $originStyle = preg_replace('/\bmax-height\s*:[^;]+;?/i', '', $originStyle);
  2798. $originStyle = preg_replace('/\bwidth\s*:[^;]+;?/i', '', $originStyle);
  2799. $originStyle = preg_replace('/\bheight\s*:[^;]+;?/i', '', $originStyle);
  2800. $originStyle = preg_replace('/\bobject-fit\s*:[^;]+;?/i', '', $originStyle);
  2801. $newStyle = $targetStyle.trim((string) $originStyle);
  2802. return preg_replace(
  2803. '/\sstyle=(["\'])(.*?)\1/i',
  2804. ' style="'.$newStyle.'"',
  2805. $fullTag,
  2806. 1
  2807. ) ?? $fullTag;
  2808. }
  2809. return preg_replace('/<img\b/i', '<img style="'.$targetStyle.'"', $fullTag, 1) ?? $fullTag;
  2810. },
  2811. $html
  2812. );
  2813. }
  2814. /**
  2815. * 仅在 unified HTML 的试卷容器中应用扁图策略,避免影响判卷/知识点讲解部分。
  2816. */
  2817. private function applyAdaptiveWideImageSizingToExamPart(string $html): string
  2818. {
  2819. $startMarker = '<!-- EXAM_PART_START -->';
  2820. $endMarker = '<!-- EXAM_PART_END -->';
  2821. $startPos = strpos($html, $startMarker);
  2822. $endPos = strpos($html, $endMarker);
  2823. if ($startPos === false || $endPos === false || $endPos <= $startPos) {
  2824. return $html;
  2825. }
  2826. $contentStart = $startPos + strlen($startMarker);
  2827. $examContent = substr($html, $contentStart, $endPos - $contentStart);
  2828. if ($examContent === false || $examContent === '') {
  2829. return $html;
  2830. }
  2831. $processedExamContent = $this->applyAdaptiveWideImageSizing($examContent);
  2832. return substr($html, 0, $contentStart).$processedExamContent.substr($html, $endPos);
  2833. }
  2834. /**
  2835. * @return array{w:int,h:int}|null
  2836. */
  2837. private function getPdfImageDimensions(string $src): ?array
  2838. {
  2839. if (array_key_exists($src, $this->pdfImageDimensionCache)) {
  2840. return $this->pdfImageDimensionCache[$src];
  2841. }
  2842. try {
  2843. $persisted = $this->getPersistedPdfImageMetrics($src);
  2844. if ($persisted !== null) {
  2845. $this->pdfImageDimensionCache[$src] = $persisted;
  2846. return $persisted;
  2847. }
  2848. if (! str_starts_with($src, 'http://') && ! str_starts_with($src, 'https://')) {
  2849. $this->pdfImageDimensionCache[$src] = null;
  2850. return null;
  2851. }
  2852. $socketTimeoutBackup = null;
  2853. $imageProbeTimeout = max(1, (int) config('pdf.image_probe_timeout_seconds', 2));
  2854. if (str_starts_with($src, 'http://') || str_starts_with($src, 'https://')) {
  2855. // 远程图片探测加硬超时,避免首次命中慢图源拖慢整份 PDF 生成。
  2856. $socketTimeoutBackup = ini_get('default_socket_timeout');
  2857. @ini_set('default_socket_timeout', (string) $imageProbeTimeout);
  2858. }
  2859. $size = @getimagesize($src);
  2860. if ($socketTimeoutBackup !== null && $socketTimeoutBackup !== false) {
  2861. @ini_set('default_socket_timeout', (string) $socketTimeoutBackup);
  2862. }
  2863. if (is_array($size) && count($size) >= 2) {
  2864. $data = ['w' => (int) $size[0], 'h' => (int) $size[1]];
  2865. $this->persistPdfImageMetrics($src, $data);
  2866. $this->pdfImageDimensionCache[$src] = $data;
  2867. return $data;
  2868. }
  2869. $this->pdfImageDimensionCache[$src] = null;
  2870. return null;
  2871. } catch (\Throwable $e) {
  2872. Log::debug('ExamPdfExportService: 图片尺寸探测失败', ['src' => $src, 'error' => $e->getMessage()]);
  2873. $this->pdfImageDimensionCache[$src] = null;
  2874. return null;
  2875. }
  2876. }
  2877. /**
  2878. * @return array{w:int,h:int}|null
  2879. */
  2880. private function getPersistedPdfImageMetrics(string $src): ?array
  2881. {
  2882. if (! $this->isPdfImageMetricsTableReady()) {
  2883. return null;
  2884. }
  2885. $row = DB::table('pdf_image_metrics')
  2886. ->where('src', $src)
  2887. ->first(['width', 'height']);
  2888. if (! $row) {
  2889. return null;
  2890. }
  2891. $w = (int) ($row->width ?? 0);
  2892. $h = (int) ($row->height ?? 0);
  2893. if ($w <= 0 || $h <= 0) {
  2894. return null;
  2895. }
  2896. return ['w' => $w, 'h' => $h];
  2897. }
  2898. /**
  2899. * @param array{w:int,h:int} $data
  2900. */
  2901. private function persistPdfImageMetrics(string $src, array $data): void
  2902. {
  2903. if (! $this->isPdfImageMetricsTableReady()) {
  2904. return;
  2905. }
  2906. $w = (int) ($data['w'] ?? 0);
  2907. $h = (int) ($data['h'] ?? 0);
  2908. if ($w <= 0 || $h <= 0) {
  2909. return;
  2910. }
  2911. DB::table('pdf_image_metrics')->upsert([
  2912. [
  2913. 'src' => $src,
  2914. 'width' => $w,
  2915. 'height' => $h,
  2916. 'ratio' => round($w / max(1, $h), 4),
  2917. 'updated_at' => now(),
  2918. 'created_at' => now(),
  2919. ],
  2920. ], ['src'], ['width', 'height', 'ratio', 'updated_at']);
  2921. }
  2922. private function isPdfImageMetricsTableReady(): bool
  2923. {
  2924. if ($this->hasPdfImageMetricsTable !== null) {
  2925. return $this->hasPdfImageMetricsTable;
  2926. }
  2927. $this->hasPdfImageMetricsTable = Schema::hasTable('pdf_image_metrics');
  2928. return $this->hasPdfImageMetricsTable;
  2929. }
  2930. private function shouldApplyAdaptiveSizingToSrc(string $src): bool
  2931. {
  2932. $parts = parse_url($src);
  2933. if (! is_array($parts)) {
  2934. return false;
  2935. }
  2936. $host = strtolower((string) ($parts['host'] ?? ''));
  2937. $path = (string) ($parts['path'] ?? '');
  2938. if ($host !== 'file.chunsunqiuzhu.com') {
  2939. return false;
  2940. }
  2941. if (! str_contains($path, '/data/')) {
  2942. return false;
  2943. }
  2944. return (bool) preg_match('/\.(png|jpe?g|webp)$/i', $path);
  2945. }
  2946. /**
  2947. * 使用Chrome渲染PDF
  2948. */
  2949. private function renderWithChrome(string $htmlPath): ?string
  2950. {
  2951. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_').'.pdf';
  2952. $userDataDir = sys_get_temp_dir().'/chrome-profile-'.uniqid();
  2953. $chromeBinary = $this->findChromeBinary();
  2954. if (! $chromeBinary) {
  2955. Log::error('ExamPdfExportService: 未找到可用的Chrome/Chromium');
  2956. return null;
  2957. }
  2958. // 设置运行时目录
  2959. $runtimeHome = sys_get_temp_dir().'/chrome-home';
  2960. $runtimeXdg = sys_get_temp_dir().'/chrome-xdg';
  2961. if (! File::exists($runtimeHome)) {
  2962. @File::makeDirectory($runtimeHome, 0755, true);
  2963. }
  2964. if (! File::exists($runtimeXdg)) {
  2965. @File::makeDirectory($runtimeXdg, 0755, true);
  2966. }
  2967. $process = new Process([
  2968. $chromeBinary,
  2969. '--headless=new', // 【优化】使用新渲染引擎
  2970. '--disable-gpu',
  2971. '--no-sandbox',
  2972. '--disable-setuid-sandbox',
  2973. '--disable-dev-shm-usage',
  2974. '--disable-web-security',
  2975. '--disable-features=VizDisplayCompositor',
  2976. '--disable-extensions',
  2977. // '--disable-background-networking', // 注释掉,可能阻止必要的网络请求
  2978. '--disable-component-update',
  2979. '--disable-client-side-phishing-detection',
  2980. '--disable-default-apps',
  2981. '--disable-domain-reliability',
  2982. '--disable-sync',
  2983. '--no-first-run',
  2984. '--no-default-browser-check',
  2985. '--disable-crash-reporter',
  2986. '--disable-print-preview',
  2987. '--disable-features=TranslateUI',
  2988. '--disable-features=OptimizationHints',
  2989. '--disable-ipc-flooding-protection',
  2990. '--disable-background-timer-throttling',
  2991. '--disable-backgrounding-occluded-windows',
  2992. '--disable-renderer-backgrounding',
  2993. '--disable-features=AudioServiceOutOfProcess',
  2994. '--disable-gpu-sandbox',
  2995. '--disable-software-rasterizer',
  2996. '--disable-background-mode',
  2997. '--disable-extensions-http-throttling',
  2998. '--disable-ipc-flooding-protection',
  2999. '--disable-features=Dbus', // 禁用 dbus
  3000. // 【关键修复】添加虚拟时间预算,让Chrome有足够时间加载CDN资源和执行JS
  3001. '--virtual-time-budget=30000', // 30秒虚拟时间用于加载外部资源
  3002. '--run-all-compositor-stages-before-draw', // 确保所有渲染完成后再生成PDF
  3003. '--user-data-dir='.$userDataDir,
  3004. '--print-to-pdf='.$tmpPdf,
  3005. '--print-to-pdf-no-header',
  3006. '--allow-file-access-from-files',
  3007. '--font-render-hinting=none', // 【优化】禁用字体渲染提示
  3008. '--disable-font-antialiasing',
  3009. 'file://'.$htmlPath,
  3010. ], null, [
  3011. 'HOME' => $runtimeHome,
  3012. 'XDG_RUNTIME_DIR' => $runtimeXdg,
  3013. ]);
  3014. $process->setTimeout(180); // 复杂学情报告页允许更长渲染时间,降低超时失败率
  3015. $killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
  3016. Log::debug('ExamPdfExportService: [调试] Chrome命令准备执行', [
  3017. 'chrome_binary' => $chromeBinary,
  3018. 'html_path' => $htmlPath,
  3019. 'html_exists' => file_exists($htmlPath),
  3020. 'html_size' => file_exists($htmlPath) ? filesize($htmlPath) : 0,
  3021. 'pdf_path' => $tmpPdf,
  3022. 'user_data_dir' => $userDataDir,
  3023. ]);
  3024. try {
  3025. $startedAt = microtime(true);
  3026. $process->start();
  3027. $pdfGenerated = false;
  3028. // 轮询检测PDF是否生成
  3029. $pollStart = microtime(true);
  3030. $maxPollSeconds = max(10, (int) config('pdf.chrome_poll_timeout_seconds', 40));
  3031. while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
  3032. if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
  3033. $pdfGenerated = true;
  3034. Log::info('ExamPdfExportService: PDF生成成功,提前终止Chrome进程', [
  3035. 'elapsed' => round(microtime(true) - $startedAt, 2),
  3036. 'pdf_size' => filesize($tmpPdf),
  3037. ]);
  3038. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  3039. break;
  3040. }
  3041. usleep(100_000); // 【优化】从200ms减少到100ms
  3042. }
  3043. if ($process->isRunning()) {
  3044. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  3045. }
  3046. // 【优化】删除不必要的wait()调用,避免重复等待
  3047. // $process->wait();
  3048. } catch (ProcessTimedOutException|ProcessSignaledException $e) {
  3049. if ($process->isRunning()) {
  3050. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  3051. }
  3052. Log::warning('ExamPdfExportService: Chrome进程超时或被信号中断', [
  3053. 'elapsed' => round((microtime(true) - $startedAt), 2),
  3054. 'exception' => get_class($e),
  3055. ]);
  3056. $result = $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
  3057. if ($result !== null) {
  3058. return $result;
  3059. }
  3060. return $this->renderWithChromeMinimal($chromeBinary, $htmlPath);
  3061. } catch (\Throwable $e) {
  3062. if ($process->isRunning()) {
  3063. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  3064. }
  3065. Log::error('ExamPdfExportService: Chrome进程异常', [
  3066. 'elapsed' => round((microtime(true) - $startedAt), 2),
  3067. 'error' => $e->getMessage(),
  3068. ]);
  3069. $result = $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  3070. if ($result !== null) {
  3071. return $result;
  3072. }
  3073. return $this->renderWithChromeMinimal($chromeBinary, $htmlPath);
  3074. }
  3075. $result = $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  3076. if ($result !== null) {
  3077. return $result;
  3078. }
  3079. return $this->renderWithChromeMinimal($chromeBinary, $htmlPath);
  3080. }
  3081. /**
  3082. * 处理Chrome进程结果
  3083. */
  3084. private function handleChromeProcessResult(string $tmpPdf, string $userDataDir, Process $process, ?float $startedAt): ?string
  3085. {
  3086. $pdfExists = file_exists($tmpPdf);
  3087. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  3088. $elapsed = $startedAt ? round((microtime(true) - $startedAt), 2) : null;
  3089. // 【优化】即使进程未成功,只要PDF存在且大小合理就返回
  3090. if ($pdfExists && $pdfSize > 1000) { // 至少1KB
  3091. Log::info('ExamPdfExportService: PDF生成成功', [
  3092. 'elapsed' => $elapsed,
  3093. 'pdf_size' => $pdfSize,
  3094. 'exit_code' => $process->getExitCode(),
  3095. 'is_successful' => $process->isSuccessful(),
  3096. ]);
  3097. $pdfBinary = file_get_contents($tmpPdf);
  3098. @unlink($tmpPdf);
  3099. File::deleteDirectory($userDataDir);
  3100. return $pdfBinary;
  3101. }
  3102. // 如果PDF不存在或太小,记录错误
  3103. Log::error('ExamPdfExportService: Chrome渲染失败', [
  3104. 'elapsed' => $elapsed,
  3105. 'pdf_exists' => $pdfExists,
  3106. 'pdf_size' => $pdfSize,
  3107. 'exit_code' => $process->getExitCode(),
  3108. 'error' => $process->getErrorOutput(),
  3109. 'output' => $process->getOutput(),
  3110. ]);
  3111. @unlink($tmpPdf);
  3112. File::deleteDirectory($userDataDir);
  3113. return null;
  3114. }
  3115. /**
  3116. * Chrome主渲染失败时的最小参数兜底。
  3117. */
  3118. private function renderWithChromeMinimal(string $chromeBinary, string $htmlPath): ?string
  3119. {
  3120. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_fallback_').'.pdf';
  3121. $process = new Process([
  3122. $chromeBinary,
  3123. '--headless=new',
  3124. '--disable-gpu',
  3125. '--no-sandbox',
  3126. '--print-to-pdf='.$tmpPdf,
  3127. 'file://'.$htmlPath,
  3128. ]);
  3129. $process->setTimeout(180);
  3130. try {
  3131. $process->run();
  3132. if (file_exists($tmpPdf) && filesize($tmpPdf) > 1000) {
  3133. Log::warning('ExamPdfExportService: Chrome最小参数兜底成功', [
  3134. 'pdf_size' => filesize($tmpPdf),
  3135. 'exit_code' => $process->getExitCode(),
  3136. ]);
  3137. $pdfBinary = file_get_contents($tmpPdf);
  3138. @unlink($tmpPdf);
  3139. return $pdfBinary;
  3140. }
  3141. Log::error('ExamPdfExportService: Chrome最小参数兜底失败', [
  3142. 'exit_code' => $process->getExitCode(),
  3143. 'error' => $process->getErrorOutput(),
  3144. 'output' => $process->getOutput(),
  3145. ]);
  3146. } catch (\Throwable $e) {
  3147. Log::error('ExamPdfExportService: Chrome最小参数兜底异常', [
  3148. 'error' => $e->getMessage(),
  3149. ]);
  3150. }
  3151. @unlink($tmpPdf);
  3152. return null;
  3153. }
  3154. /**
  3155. * 查找Chrome二进制文件
  3156. */
  3157. private function findChromeBinary(): ?string
  3158. {
  3159. $candidates = [
  3160. env('PDF_CHROME_BINARY'),
  3161. env('CHROME_BIN'), // Docker Alpine 环境变量
  3162. '/usr/bin/chromium-browser', // Alpine Linux
  3163. '/usr/bin/chromium',
  3164. '/usr/bin/google-chrome-stable',
  3165. '/usr/bin/google-chrome',
  3166. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', // macOS
  3167. ];
  3168. foreach ($candidates as $path) {
  3169. if ($path && is_file($path) && is_executable($path)) {
  3170. return $path;
  3171. }
  3172. }
  3173. return null;
  3174. }
  3175. /**
  3176. * 确保HTML为UTF-8编码,并内联外部资源
  3177. */
  3178. private function ensureUtf8Html(string $html): string
  3179. {
  3180. $meta = '<meta charset="UTF-8">';
  3181. if (stripos($html, '<head>') !== false) {
  3182. $html = preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
  3183. } else {
  3184. $html = $meta.$html;
  3185. }
  3186. // 【关键修复】内联KaTeX CSS,避免Chrome在容器中加载CDN资源超时
  3187. $html = $this->inlineExternalResources($html);
  3188. return $html;
  3189. }
  3190. /**
  3191. * 将CDN资源替换为内联资源
  3192. * 【关键修复】避免Chrome在容器中加载CDN资源超时,同时支持本地路径
  3193. */
  3194. private function inlineExternalResources(string $html): string
  3195. {
  3196. // 检查是否包含 KaTeX 资源(CDN 或本地)
  3197. $hasKatexCdn = strpos($html, 'cdn.jsdelivr.net/npm/katex') !== false;
  3198. $hasKatexLocal = strpos($html, '/js/katex.min.js') !== false || strpos($html, '/css/katex/katex.min.css') !== false;
  3199. Log::debug('ExamPdfExportService: inlineExternalResources', [
  3200. 'html_length' => strlen($html),
  3201. 'has_katex_cdn' => $hasKatexCdn,
  3202. 'has_katex_local' => $hasKatexLocal,
  3203. ]);
  3204. // 如果既没有 CDN 也没有本地链接,仍尝试注入 KaTeX 关系符通用修复
  3205. if (! $hasKatexCdn && ! $hasKatexLocal) {
  3206. Log::debug('ExamPdfExportService: HTML 中没有 KaTeX 资源链接,跳过内联');
  3207. return $this->applyKatexRelationGlyphFixes($html);
  3208. }
  3209. try {
  3210. // 读取并内联 KaTeX CSS(无论 CDN 还是本地)
  3211. $katexCssPath = public_path('css/katex/katex.min.css');
  3212. if (file_exists($katexCssPath)) {
  3213. $katexCss = file_get_contents($katexCssPath);
  3214. // 修复字体路径:将相对路径改为 data URI
  3215. $fontsDir = public_path('css/katex/fonts');
  3216. $katexCss = preg_replace_callback(
  3217. '/url\(["\']?fonts\/([^"\')\s]+)["\']?\)/i',
  3218. function ($matches) use ($fontsDir) {
  3219. $fontFile = $fontsDir.'/'.$matches[1];
  3220. if (file_exists($fontFile)) {
  3221. $fontData = base64_encode(file_get_contents($fontFile));
  3222. $mimeType = str_ends_with($matches[1], '.woff2') ? 'font/woff2' : 'font/woff';
  3223. return 'url(data:'.$mimeType.';base64,'.$fontData.')';
  3224. }
  3225. return $matches[0];
  3226. },
  3227. $katexCss
  3228. );
  3229. // 替换 CDN CSS 链接
  3230. if ($hasKatexCdn) {
  3231. $html = preg_replace(
  3232. '/<link[^>]*href=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*katex\.min\.css["\'][^>]*>/i',
  3233. '<style type="text/css">'.$katexCss.'</style>',
  3234. $html
  3235. );
  3236. }
  3237. // 替换本地 CSS 链接
  3238. if ($hasKatexLocal) {
  3239. $html = preg_replace(
  3240. '/<link[^>]*href=["\']\/css\/katex\/katex\.min\.css["\'][^>]*>/i',
  3241. '<style type="text/css">'.$katexCss.'</style>',
  3242. $html
  3243. );
  3244. }
  3245. Log::info('ExamPdfExportService: KaTeX CSS 已内联(含字体 data URI)');
  3246. }
  3247. // 读取本地 KaTeX JS(用于移除)
  3248. $katexJsPath = public_path('js/katex.min.js');
  3249. $autoRenderJsPath = public_path('js/auto-render.min.js');
  3250. if (file_exists($katexJsPath)) {
  3251. $katexJs = file_get_contents($katexJsPath);
  3252. $html = preg_replace(
  3253. '/<script[^>]*src=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*katex\.min\.js["\'][^>]*><\/script>/i',
  3254. '<script type="text/javascript">'.$katexJs.'</script>',
  3255. $html
  3256. );
  3257. }
  3258. if (file_exists($autoRenderJsPath)) {
  3259. $autoRenderJs = file_get_contents($autoRenderJsPath);
  3260. $html = preg_replace(
  3261. '/<script[^>]*src=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*auto-render[^"\']*["\'][^>]*><\/script>/i',
  3262. '<script type="text/javascript">'.$autoRenderJs.'</script>',
  3263. $html
  3264. );
  3265. }
  3266. // 【关键修复】使用服务端预渲染,而不是依赖客户端 JavaScript
  3267. // Chrome headless 的 --print-to-pdf 不会等待 JS 执行完成
  3268. // 所以我们使用 Node.js KaTeX 在服务端预渲染所有公式
  3269. // 1. 移除所有 KaTeX JavaScript(不再需要,因为使用服务端渲染)
  3270. // 移除内联的 katex.min.js
  3271. $html = preg_replace(
  3272. '/<script[^>]*type=["\']text\/javascript["\'][^>]*>[\s\S]*?katex[\s\S]*?<\/script>/i',
  3273. '<!-- KaTeX JS removed, using server-side rendering -->',
  3274. $html
  3275. );
  3276. // 移除 DOMContentLoaded 监听器
  3277. $html = preg_replace(
  3278. '/<script[^>]*>[\s\S]*?document\.addEventListener[\s\S]*?DOMContentLoaded[\s\S]*?<\/script>/i',
  3279. '<!-- DOMContentLoaded removed -->',
  3280. $html
  3281. );
  3282. // 2. 使用 KatexRenderer 进行服务端预渲染
  3283. if ($this->katexRenderer) {
  3284. $beforeLength = strlen($html);
  3285. $html = $this->katexRenderer->renderHtml($html);
  3286. $afterLength = strlen($html);
  3287. Log::info('ExamPdfExportService: LaTeX 公式服务端预渲染完成', [
  3288. 'before_length' => $beforeLength,
  3289. 'after_length' => $afterLength,
  3290. 'size_change' => $afterLength - $beforeLength,
  3291. ]);
  3292. // 通用修复:统一优化 KaTeX 关系运算符(mrel)字形
  3293. // 覆盖平行、垂直、等于、不等于等关系符,避免出现“平行符像 ||”的问题
  3294. $html = $this->applyKatexRelationGlyphFixes($html);
  3295. } else {
  3296. Log::warning('ExamPdfExportService: KatexRenderer 未初始化,跳过预渲染');
  3297. }
  3298. // 【换行处理】将字面的 \n 转换为 <br> 标签(在 KaTeX 渲染后处理,避免破坏公式)
  3299. // 先替换所有 \n 为 <br>,然后合并连续的 <br>(最多保留2个)
  3300. $html = str_replace('\\n', '<br>', $html);
  3301. $html = preg_replace('/(<br>\s*){3,}/', '<br><br>', $html); // 3个以上合并为2个
  3302. } catch (\Exception $e) {
  3303. Log::warning('ExamPdfExportService: 内联资源处理失败,保留原始HTML', [
  3304. 'error' => $e->getMessage(),
  3305. ]);
  3306. }
  3307. return $this->applyKatexRelationGlyphFixes($html);
  3308. }
  3309. /**
  3310. * 应用 KaTeX 关系符通用修复(先标记,再注入样式)
  3311. */
  3312. private function applyKatexRelationGlyphFixes(string $html): string
  3313. {
  3314. $html = $this->tagKatexParallelRelationSpans($html);
  3315. return $this->injectKatexRelationGlyphStyle($html);
  3316. }
  3317. /**
  3318. * 标记 KaTeX 中的平行关系符(∥),便于使用字体无关样式兜底
  3319. */
  3320. private function tagKatexParallelRelationSpans(string $html): string
  3321. {
  3322. if (strpos($html, '∥') === false || strpos($html, 'mrel') === false) {
  3323. return $html;
  3324. }
  3325. $pattern = '/<span(?P<attrs>[^>]*)class=(["\'])(?P<class>[^"\']*\bmrel\b[^"\']*)\2(?P<tail>[^>]*)>\s*∥\s*<\/span>/u';
  3326. $replaced = preg_replace_callback($pattern, static function (array $matches): string {
  3327. $attrs = $matches['attrs'] ?? '';
  3328. $quote = $matches[2] ?? '"';
  3329. $class = trim($matches['class'] ?? '');
  3330. $tail = $matches['tail'] ?? '';
  3331. if ($class === '') {
  3332. $class = 'mrel katex-rel-parallel';
  3333. } elseif (! preg_match('/\bkatex-rel-parallel\b/', $class)) {
  3334. $class .= ' katex-rel-parallel';
  3335. }
  3336. return '<span'.$attrs.'class='.$quote.$class.$quote.$tail.'>∥</span>';
  3337. }, $html);
  3338. return $replaced ?? $html;
  3339. }
  3340. /**
  3341. * 注入 KaTeX 关系运算符统一字形样式(全局、通用)
  3342. */
  3343. private function injectKatexRelationGlyphStyle(string $html): string
  3344. {
  3345. if (strpos($html, 'class="katex"') === false && strpos($html, 'class="katex-html"') === false) {
  3346. return $html;
  3347. }
  3348. if (strpos($html, 'id="katex-relation-glyph-style"') !== false) {
  3349. return $html;
  3350. }
  3351. $style = '<style id="katex-relation-glyph-style">'
  3352. .'.katex .mrel{'
  3353. .'font-family:"KaTeX_AMS","KaTeX_Main","NotoSerifCJKsc-Regular","NotoSerifCJKsc-Bold","NotoSans-Regular","NotoSans-Bold","NotoSansMonoCJKjp-Regular",serif !important;'
  3354. .'letter-spacing:.04em;'
  3355. .'}'
  3356. .'.katex .mrel .mord{font-family:inherit !important;}'
  3357. .'.katex .mrel.katex-rel-parallel{'
  3358. .'display:inline-block;'
  3359. .'font-size:1.22em;'
  3360. .'line-height:1.28;'
  3361. .'letter-spacing:.04em;'
  3362. .'vertical-align:0;'
  3363. .'transform:skewX(-14deg) scaleY(1.42);'
  3364. .'transform-origin:center;'
  3365. .'}'
  3366. .'</style>';
  3367. if (stripos($html, '</head>') !== false) {
  3368. return preg_replace('/<\/head>/i', $style.'</head>', $html, 1) ?? ($html.$style);
  3369. }
  3370. return $html.$style;
  3371. }
  3372. /**
  3373. * 【新增】合并两个HTML页面,插入分页符
  3374. * 保留原始页面样式和结构,只在中间插入分页符
  3375. */
  3376. private function mergeHtmlWithPageBreak(string $examHtml, string $gradingHtml, ?string $kpExplainHtml = null): ?string
  3377. {
  3378. try {
  3379. // 确保HTML编码正确
  3380. $examHtml = $this->ensureUtf8Html($examHtml);
  3381. $gradingHtml = $this->ensureUtf8Html($gradingHtml);
  3382. if ($kpExplainHtml) {
  3383. $kpExplainHtml = $this->ensureUtf8Html($kpExplainHtml);
  3384. }
  3385. // 提取body内容
  3386. $examBody = $this->extractBodyContent($examHtml);
  3387. $gradingBody = $this->extractBodyContent($gradingHtml);
  3388. // 知识点讲解使用专门的提取方法,避免嵌套完整HTML结构
  3389. $kpExplainBody = $kpExplainHtml ? $this->extractKpExplainContent($kpExplainHtml) : null;
  3390. if (empty($examBody) || empty($gradingBody)) {
  3391. Log::error('ExamPdfExportService: HTML内容提取失败', [
  3392. 'exam_body_length' => strlen($examBody),
  3393. 'grading_body_length' => strlen($gradingBody),
  3394. ]);
  3395. return null;
  3396. }
  3397. // 提取head内容(保留原始样式和meta信息)
  3398. $examHead = $this->extractHeadContent($examHtml);
  3399. $gradingHead = $this->extractHeadContent($gradingHtml);
  3400. $kpExplainHead = $kpExplainHtml ? $this->extractHeadContent($kpExplainHtml) : null;
  3401. // 构建统一HTML文档(保留原始结构)
  3402. $unifiedHtml = $this->buildUnifiedHtmlWithOriginalStructure(
  3403. $examHead,
  3404. $examBody,
  3405. $gradingBody,
  3406. $gradingHead,
  3407. $kpExplainBody,
  3408. $kpExplainHead
  3409. );
  3410. Log::info('HTML合并成功(保留原始样式)', [
  3411. 'exam_length' => strlen($examBody),
  3412. 'grading_length' => strlen($gradingBody),
  3413. 'kp_explain_length' => $kpExplainBody ? strlen($kpExplainBody) : 0,
  3414. 'unified_length' => strlen($unifiedHtml),
  3415. 'head_length' => strlen($examHead),
  3416. 'has_kp_explain' => ! empty($kpExplainBody),
  3417. ]);
  3418. return $unifiedHtml;
  3419. } catch (\Throwable $e) {
  3420. Log::error('mergeHtmlWithPageBreak 失败', [
  3421. 'error' => $e->getMessage(),
  3422. 'trace' => $e->getTraceAsString(),
  3423. ]);
  3424. return null;
  3425. }
  3426. }
  3427. /**
  3428. * 【新增】提取HTML的body内容
  3429. */
  3430. private function extractBodyContent(string $html): string
  3431. {
  3432. // 匹配body标签内容
  3433. if (preg_match('/<body[^>]*>(.*)<\/body>/is', $html, $matches)) {
  3434. return $matches[1];
  3435. }
  3436. // 如果没有body标签,返回整个HTML
  3437. return $html;
  3438. }
  3439. /**
  3440. * 【新增】提取HTML的head内容
  3441. * 保留原始页面的样式和meta信息
  3442. */
  3443. private function extractHeadContent(string $html): string
  3444. {
  3445. // 匹配head标签内容
  3446. if (preg_match('/<head[^>]*>(.*)<\/head>/is', $html, $matches)) {
  3447. return $matches[1];
  3448. }
  3449. // 如果没有head标签,返回默认meta
  3450. return '<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">';
  3451. }
  3452. /**
  3453. * 【新增】提取知识点讲解的核心内容
  3454. * 只提取 kp-explain 容器内部的内容,避免嵌套完整的HTML结构
  3455. */
  3456. private function extractKpExplainContent(string $html): string
  3457. {
  3458. // 如果 HTML 中包含嵌套的 <html> 标签,提取嵌套内容
  3459. if (preg_match('/<html[^>]*>(.*)<\/html>/is', $html, $htmlMatches)) {
  3460. $html = $htmlMatches[1];
  3461. }
  3462. // 如果 HTML 中包含 <head> 标签,跳过 head
  3463. if (preg_match('/<head[^>]*>.*?<\/head>/is', $html, $headMatch)) {
  3464. $html = substr($html, strpos($html, '</head>') + 7);
  3465. }
  3466. // 如果 HTML 中包含 <body> 标签,提取 body 内容
  3467. if (preg_match('/<body[^>]*>(.*)<\/body>/is', $html, $bodyMatches)) {
  3468. $html = $bodyMatches[1];
  3469. }
  3470. // 移除可能存在的嵌套 <html>, <head>, <body> 标签
  3471. $html = preg_replace('/<\/?(html|head|body)[^>]*>/is', '', $html);
  3472. // 移除 script 标签和注释
  3473. $html = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $html);
  3474. $html = preg_replace('/<!--[^>]*-->/is', '', $html);
  3475. return trim($html);
  3476. }
  3477. /**
  3478. * 【优化重构】构建统一的HTML文档(容器结构 + 消除空白页)
  3479. * 使用容器结构替代空的 page-break div,避免中间出现空白页
  3480. */
  3481. private function buildUnifiedHtmlWithOriginalStructure(
  3482. string $examHead,
  3483. string $examBody,
  3484. string $gradingBody,
  3485. string $gradingHead,
  3486. ?string $kpExplainBody = null,
  3487. ?string $kpExplainHead = null
  3488. ): string
  3489. {
  3490. // 清洗内容:移除可能存在的分页符,避免双重分页
  3491. $examBody = $this->stripPageBreakElements($examBody);
  3492. $gradingBody = $this->stripPageBreakElements($gradingBody);
  3493. if ($kpExplainBody) {
  3494. $kpExplainBody = $this->stripPageBreakElements($kpExplainBody);
  3495. }
  3496. // 合并 head 内容:试卷 head + 判卷 head + 知识点讲解 head(去重)+ 分页控制样式
  3497. $mergedHead = $examHead;
  3498. // 按顺序合并其他 head 里的 <style>(避免重复)
  3499. foreach ([$gradingHead, $kpExplainHead] as $extraHead) {
  3500. if (! $extraHead) {
  3501. continue;
  3502. }
  3503. if (preg_match_all('/<style[^>]*>(.*?)<\/style>/is', $extraHead, $styleMatches)) {
  3504. foreach ($styleMatches[0] as $idx => $styleTag) {
  3505. if (! str_contains($mergedHead, $styleMatches[1][$idx])) {
  3506. $mergedHead .= "\n ".$styleTag;
  3507. }
  3508. }
  3509. }
  3510. }
  3511. // 添加分页控制样式
  3512. $headContent = $mergedHead.'
  3513. <style>
  3514. /* 容器基础样式 - 保持现有页面边距 */
  3515. .exam-part,
  3516. .grading-part,
  3517. .kp-explain-part {
  3518. width: 100%;
  3519. margin: 0;
  3520. padding: 0;
  3521. }
  3522. /* 试卷部分 - 只有在知识点讲解后才需要分页 */
  3523. .exam-part {
  3524. /* 如果有知识点讲解,需要在新页面开始(通过 kp-explain-part 的 break-after 控制) */
  3525. /* 如果没有知识点讲解,试卷从第一页开始,不需要分页 */
  3526. break-after: auto;
  3527. page-break-after: auto;
  3528. /* 确保顶部没有额外边距 */
  3529. margin-top: 0;
  3530. padding-top: 0;
  3531. }
  3532. /* 核心分页控制:只在 grading-part 上设置 */
  3533. .grading-part {
  3534. /* CSS3 新标准 */
  3535. break-before: page;
  3536. /* 兼容旧版 WebKit */
  3537. page-break-before: always;
  3538. /* 确保顶部没有额外边距 */
  3539. margin-top: 0;
  3540. padding-top: 0;
  3541. }
  3542. /* 知识点讲解部分末尾强制分页(确保试卷从新页面开始) */
  3543. .kp-explain-part {
  3544. break-after: page;
  3545. page-break-after: always;
  3546. }
  3547. /* 防止试卷部分末尾分页 */
  3548. .exam-part {
  3549. /* 确保试卷内容连续 */
  3550. break-after: auto;
  3551. page-break-after: auto;
  3552. }
  3553. /* 避免在关键元素中间分页 */
  3554. .exam-part h1, .exam-part h2,
  3555. .grading-part h1, .grading-part h2 {
  3556. break-after: avoid;
  3557. page-break-after: avoid;
  3558. }
  3559. .exam-part table, .exam-part .question-item,
  3560. .grading-part table, .grading-part .answer-item {
  3561. break-inside: avoid;
  3562. page-break-inside: avoid;
  3563. }
  3564. /* 防止孤儿行 */
  3565. .exam-part p, .exam-part li,
  3566. .grading-part p, .grading-part li {
  3567. orphans: 2;
  3568. widows: 2;
  3569. }
  3570. /* 数学公式优化 */
  3571. .katex {
  3572. break-inside: avoid;
  3573. page-break-inside: avoid;
  3574. }
  3575. </style>';
  3576. // 构建HTML内容
  3577. $bodyContent = '';
  3578. $mergedTitle = '试卷与判卷合并';
  3579. if (preg_match('/<title>(.*?)<\/title>/is', $examHead, $titleMatches)) {
  3580. $candidateTitle = trim(strip_tags($titleMatches[1]));
  3581. if ($candidateTitle !== '') {
  3582. $mergedTitle = $candidateTitle;
  3583. }
  3584. }
  3585. // 如果有知识点讲解,添加到最前面
  3586. if ($kpExplainBody) {
  3587. $bodyContent .= '
  3588. <!-- 知识点讲解部分 -->
  3589. <div class="kp-explain-part">
  3590. '.$kpExplainBody.'
  3591. </div>
  3592. ';
  3593. }
  3594. // 添加试卷部分
  3595. $bodyContent .= '
  3596. <!-- EXAM_PART_START -->
  3597. <!-- 试卷部分 - 连续显示 -->
  3598. <div class="exam-part">
  3599. '.$examBody.'
  3600. </div>
  3601. <!-- EXAM_PART_END -->
  3602. ';
  3603. // 添加判卷部分
  3604. $bodyContent .= '
  3605. <!-- 判卷部分 - 强制新页面开始 -->
  3606. <div class="grading-part">
  3607. '.$gradingBody.'
  3608. </div>
  3609. ';
  3610. return '<!DOCTYPE html>
  3611. <html lang="zh-CN">
  3612. <head>
  3613. <meta charset="UTF-8">
  3614. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  3615. <title>'.$mergedTitle.'</title>
  3616. '.$headContent.'
  3617. </head>
  3618. <body>
  3619. '.$bodyContent.'
  3620. </body>
  3621. </html>';
  3622. }
  3623. /**
  3624. * 【新增】清洗HTML内容中的分页符元素
  3625. * 移除可能存在的 page-break 元素,避免双重分页导致空白页
  3626. */
  3627. private function stripPageBreakElements(string $content): string
  3628. {
  3629. // 只移除空的 page-break div 元素(通常是 <div class="page-break"></div>)
  3630. // 使用更精确的正则,只匹配空内容或纯空白内容的 div
  3631. $patterns = [
  3632. '/<div[^>]*class="[^"]*page-break[^"]*"[^>]*>\s*<\/div>/si',
  3633. '/<div[^>]*style="[^"]*page-break[^"]*"[^>]*>\s*<\/div>/si',
  3634. ];
  3635. foreach ($patterns as $pattern) {
  3636. $content = preg_replace($pattern, '', $content);
  3637. }
  3638. return $content;
  3639. }
  3640. /**
  3641. * 【新增】获取PDF通用样式
  3642. */
  3643. private function getCommonPdfStyles(): string
  3644. {
  3645. return '
  3646. * {
  3647. margin: 0;
  3648. padding: 0;
  3649. box-sizing: border-box;
  3650. }
  3651. body {
  3652. font-family: "Microsoft YaHei", "SimHei", Arial, sans-serif;
  3653. font-size: 14px;
  3654. line-height: 1.6;
  3655. color: #333;
  3656. background: #fff;
  3657. }
  3658. .paper-container {
  3659. max-width: 210mm;
  3660. margin: 0 auto;
  3661. padding: 20mm;
  3662. background: white;
  3663. }
  3664. .paper-header {
  3665. text-align: center;
  3666. margin-bottom: 30px;
  3667. padding-bottom: 15px;
  3668. border-bottom: 2px solid #333;
  3669. }
  3670. .paper-title {
  3671. font-size: 24px;
  3672. font-weight: bold;
  3673. margin-bottom: 10px;
  3674. }
  3675. .paper-info {
  3676. font-size: 14px;
  3677. color: #666;
  3678. }
  3679. .question {
  3680. margin-bottom: 30px;
  3681. padding: 20px;
  3682. border: 1px solid #ddd;
  3683. border-radius: 5px;
  3684. }
  3685. .question-number {
  3686. font-weight: bold;
  3687. margin-bottom: 10px;
  3688. }
  3689. .question-stem {
  3690. margin-bottom: 15px;
  3691. }
  3692. .options {
  3693. list-style: none;
  3694. margin-left: 20px;
  3695. }
  3696. .options li {
  3697. margin-bottom: 8px;
  3698. }
  3699. .answer-section {
  3700. margin-top: 20px;
  3701. padding-top: 15px;
  3702. border-top: 1px solid #eee;
  3703. }
  3704. .answer-label {
  3705. font-weight: bold;
  3706. color: #d9534f;
  3707. }
  3708. .solution {
  3709. margin-top: 10px;
  3710. padding: 10px;
  3711. background: #f5f5f5;
  3712. border-left: 4px solid #5bc0de;
  3713. }
  3714. ';
  3715. }
  3716. /**
  3717. * 构建知识点名称映射
  3718. */
  3719. private function buildKnowledgePointNameMap(): array
  3720. {
  3721. try {
  3722. $options = $this->questionServiceApi->getKnowledgePointOptions();
  3723. return $options ?: [];
  3724. } catch (\Throwable $e) {
  3725. Log::warning('ExamPdfExportService: 获取知识点名称失败', [
  3726. 'error' => $e->getMessage(),
  3727. ]);
  3728. return [];
  3729. }
  3730. }
  3731. /**
  3732. * 构建掌握度摘要
  3733. */
  3734. private function buildMasterySummary(array $masteryData, array $kpNameMap): array
  3735. {
  3736. $items = [];
  3737. $total = 0;
  3738. $count = 0;
  3739. foreach ($masteryData as $row) {
  3740. $code = $row['kp_code'] ?? null;
  3741. // 【修复】使用kpNameMap转换名称为友好显示名
  3742. $name = $kpNameMap[$code] ?? $row['kp_name'] ?? $code ?: '未知知识点';
  3743. $level = (float) ($row['mastery_level'] ?? 0);
  3744. $delta = $row['mastery_change'] ?? null;
  3745. $items[] = [
  3746. 'kp_code' => $code,
  3747. 'kp_name' => $name,
  3748. 'mastery_level' => $level,
  3749. 'mastery_change' => $delta,
  3750. ];
  3751. $total += $level;
  3752. $count++;
  3753. }
  3754. $average = $count > 0 ? round($total / $count, 2) : null;
  3755. // 按掌握度从低到高排序
  3756. if (! empty($items)) {
  3757. usort($items, fn ($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  3758. }
  3759. $result = [
  3760. 'items' => $items,
  3761. 'average' => $average,
  3762. 'weak_list' => array_slice($items, 0, 5),
  3763. ];
  3764. return $result;
  3765. }
  3766. /**
  3767. * 标准化题型
  3768. */
  3769. private function normalizeQuestionType(string $type): string
  3770. {
  3771. $t = strtolower(trim($type));
  3772. return match (true) {
  3773. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  3774. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  3775. default => 'answer',
  3776. };
  3777. }
  3778. private function buildPaperNamePrefix(Paper $paper): string
  3779. {
  3780. $assembleType = ($paper->paper_type === null || $paper->paper_type === '')
  3781. ? null
  3782. : (int) $paper->paper_type;
  3783. $studentName = Student::query()
  3784. ->where('student_id', $paper->student_id)
  3785. ->value('name') ?? ($paper->student_id ?: '________');
  3786. try {
  3787. $assembleTypeLabel = $assembleType !== null ? PaperNaming::assembleTypeLabel($assembleType) : '未知类型';
  3788. } catch (\Throwable $e) {
  3789. $assembleTypeLabel = '未知类型';
  3790. }
  3791. return "{$studentName}_".PaperNaming::extractExamCode((string) $paper->paper_id)."_{$assembleTypeLabel}";
  3792. }
  3793. private function buildPaperDisplayTitle(Paper $paper): string
  3794. {
  3795. return $this->buildPaperNamePrefix($paper).'_'.now()->format('Ymd');
  3796. }
  3797. private function buildPdfFileName(Paper $paper, ?string $stamp = null): string
  3798. {
  3799. $basePrefix = $this->buildPaperNamePrefix($paper);
  3800. $stamp = $stamp ?: now()->format('YmdHis').strtoupper(Str::random(4));
  3801. $base = "{$basePrefix}_{$stamp}";
  3802. $safe = PaperNaming::toSafeFilename($base);
  3803. return "{$safe}.pdf";
  3804. }
  3805. private function extractUploadStamp(string $url): ?string
  3806. {
  3807. $path = parse_url($url, PHP_URL_PATH);
  3808. if (! is_string($path) || $path === '') {
  3809. return null;
  3810. }
  3811. $stem = pathinfo($path, PATHINFO_FILENAME);
  3812. if (! is_string($stem) || $stem === '') {
  3813. return null;
  3814. }
  3815. if (preg_match('/(\d{14}[A-Za-z0-9]{4})/', $stem, $matches)) {
  3816. return $matches[1];
  3817. }
  3818. return null;
  3819. }
  3820. /**
  3821. * 保存PDF URL到数据库
  3822. */
  3823. private function savePdfUrlToDatabase(string $paperId, string $field, string $url): void
  3824. {
  3825. try {
  3826. $paper = Paper::where('paper_id', $paperId)->first();
  3827. if ($paper) {
  3828. $paperDisplayTitle = $this->buildPaperDisplayTitle($paper);
  3829. $stamp = $this->extractUploadStamp($url);
  3830. if ($stamp) {
  3831. $paperDisplayTitle = $this->buildPaperNamePrefix($paper).'_'.$stamp;
  3832. }
  3833. $updatePayload = [
  3834. $field => $url,
  3835. 'paper_name' => $paperDisplayTitle,
  3836. ];
  3837. $paper->update($updatePayload);
  3838. Log::info('ExamPdfExportService: PDF URL已写入数据库', [
  3839. 'paper_id' => $paperId,
  3840. 'field' => $field,
  3841. 'url' => $url,
  3842. 'paper_name' => $paperDisplayTitle,
  3843. ]);
  3844. }
  3845. } catch (\Throwable $e) {
  3846. Log::error('ExamPdfExportService: 写入PDF URL失败', [
  3847. 'paper_id' => $paperId,
  3848. 'field' => $field,
  3849. 'error' => $e->getMessage(),
  3850. ]);
  3851. }
  3852. }
  3853. /**
  3854. * 保存学情分析PDF URL
  3855. */
  3856. private function saveAnalysisPdfUrl(string $paperId, string $studentId, ?string $recordId, string $url): void
  3857. {
  3858. try {
  3859. if ($recordId) {
  3860. // OCR记录
  3861. $ocrRecord = \App\Models\OCRRecord::find($recordId);
  3862. if ($ocrRecord) {
  3863. $ocrRecord->update(['analysis_pdf_url' => $url]);
  3864. Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
  3865. 'record_id' => $recordId,
  3866. 'paper_id' => $paperId,
  3867. 'student_id' => $studentId,
  3868. 'url' => $url,
  3869. ]);
  3870. }
  3871. if (! $ocrRecord) {
  3872. Log::warning('ExamPdfExportService: recordId未匹配OCR记录,回退写入学情分析PDF URL', [
  3873. 'record_id' => $recordId,
  3874. 'student_id' => $studentId,
  3875. 'paper_id' => $paperId,
  3876. ]);
  3877. }
  3878. }
  3879. // 【修复】同时更新 exam_analysis_results 表和分析报告表
  3880. $updated = \DB::connection('mysql')->table('exam_analysis_results')
  3881. ->where('student_id', $studentId)
  3882. ->where('paper_id', $paperId)
  3883. ->update([
  3884. 'analysis_pdf_url' => $url,
  3885. 'updated_at' => now(),
  3886. ]);
  3887. if ($updated) {
  3888. Log::info('ExamPdfExportService: 学情分析PDF URL已写入exam_analysis_results表', [
  3889. 'student_id' => $studentId,
  3890. 'paper_id' => $paperId,
  3891. 'url' => $url,
  3892. 'updated_rows' => $updated,
  3893. ]);
  3894. } else {
  3895. Log::warning('ExamPdfExportService: 未找到要更新的学情分析记录', [
  3896. 'student_id' => $studentId,
  3897. 'paper_id' => $paperId,
  3898. ]);
  3899. }
  3900. // 学生记录 - 使用新的 student_reports 表(备用)
  3901. \App\Models\StudentReport::updateOrCreate(
  3902. [
  3903. 'student_id' => $studentId,
  3904. 'report_type' => 'exam_analysis',
  3905. 'paper_id' => $paperId,
  3906. ],
  3907. [
  3908. 'pdf_url' => $url,
  3909. 'generation_status' => 'completed',
  3910. 'generated_at' => now(),
  3911. 'updated_at' => now(),
  3912. ]
  3913. );
  3914. Log::info('ExamPdfExportService: 学生学情报告PDF URL已保存到student_reports表(备用)', [
  3915. 'student_id' => $studentId,
  3916. 'paper_id' => $paperId,
  3917. 'url' => $url,
  3918. ]);
  3919. } catch (\Throwable $e) {
  3920. Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
  3921. 'paper_id' => $paperId,
  3922. 'student_id' => $studentId,
  3923. 'record_id' => $recordId,
  3924. 'error' => $e->getMessage(),
  3925. ]);
  3926. }
  3927. }
  3928. /**
  3929. * 【修复】处理父节点掌握度数据
  3930. * 1. 过滤掉掌握度为0或null的父节点
  3931. * 2. 将kp_code转换为友好的kp_name
  3932. * 3. 构建父子层级关系(只显示本次考试相关的子节点)
  3933. */
  3934. private function processParentMasteryLevels(
  3935. array $parentMasteryLevels,
  3936. array $kpNameMap,
  3937. array $examKpCodes = [],
  3938. array $masteryMap = [],
  3939. array $snapshotMasteryData = []
  3940. ): array
  3941. {
  3942. $processed = [];
  3943. foreach ($parentMasteryLevels as $kpCode => $masteryData) {
  3944. // 兼容不同数据结构:可能是数组或数字
  3945. $masteryLevel = is_array($masteryData) ? ($masteryData['mastery_level'] ?? 0) : $masteryData;
  3946. $masteryChange = is_array($masteryData) ? ($masteryData['mastery_change'] ?? null) : null;
  3947. $changeSource = is_array($masteryData) ? ($masteryData['change_source'] ?? null) : null;
  3948. // 获取友好名称
  3949. $kpName = $kpNameMap[$kpCode] ?? $kpCode;
  3950. // 构建父节点数据,包含子节点信息(只显示本次考试相关的)
  3951. $childrenData = $this->getChildKnowledgePoints($kpCode, $kpNameMap, $examKpCodes, $masteryMap);
  3952. $allChildren = $childrenData['all_children'] ?? [];
  3953. // 口径统一:优先使用全部直接子节点均值作为父节点掌握度
  3954. if (! empty($allChildren)) {
  3955. $allLevels = array_map(
  3956. fn ($c) => floatval($c['mastery_level'] ?? 0),
  3957. $allChildren
  3958. );
  3959. $masteryLevel = ! empty($allLevels)
  3960. ? array_sum($allLevels) / count($allLevels)
  3961. : floatval($masteryLevel);
  3962. if (! empty($snapshotMasteryData)) {
  3963. $prevLevels = [];
  3964. foreach ($allChildren as $child) {
  3965. $childCode = (string) ($child['kp_code'] ?? '');
  3966. if ($childCode === '') {
  3967. continue;
  3968. }
  3969. $currentChild = floatval($masteryMap[$childCode] ?? 0);
  3970. $prevFromSnapshot = $snapshotMasteryData[$childCode]['previous_mastery'] ?? null;
  3971. $currFromSnapshot = $snapshotMasteryData[$childCode]['current_mastery'] ?? null;
  3972. $previousChild = $prevFromSnapshot ?? $currFromSnapshot ?? $currentChild;
  3973. $prevLevels[] = floatval($previousChild);
  3974. }
  3975. if (! empty($prevLevels)) {
  3976. $masteryChange = $masteryLevel - (array_sum($prevLevels) / count($prevLevels));
  3977. $changeSource = 'children_all_average';
  3978. }
  3979. }
  3980. }
  3981. // 仅过滤空值;0 掌握度的命中父节点也要展示
  3982. if ($masteryLevel === null) {
  3983. continue;
  3984. }
  3985. $hitLevels = array_map(
  3986. fn ($c) => floatval($c['mastery_level'] ?? 0),
  3987. $childrenData['hit_children'] ?? []
  3988. );
  3989. $hitAvg = ! empty($hitLevels) ? array_sum($hitLevels) / count($hitLevels) : null;
  3990. $hitCount = count($childrenData['hit_children'] ?? []);
  3991. // 父节点仅展示“本卷命中知识点”对应的父节点
  3992. if ($hitCount <= 0) {
  3993. continue;
  3994. }
  3995. $processed[$kpCode] = [
  3996. 'kp_code' => $kpCode,
  3997. 'kp_name' => $kpName,
  3998. 'mastery_level' => round(floatval($masteryLevel), 4),
  3999. 'mastery_percentage' => round(floatval($masteryLevel) * 100, 2),
  4000. 'mastery_change' => $masteryChange !== null ? round(floatval($masteryChange), 4) : null,
  4001. 'change_source' => $changeSource,
  4002. // 兼容旧模板字段:仅命中子节点
  4003. 'children' => $childrenData['hit_children'] ?? [],
  4004. // 新增:全部直接子节点(含掌握度、是否命中)
  4005. 'children_all' => $childrenData['all_children'] ?? [],
  4006. 'children_hit_count' => $hitCount,
  4007. 'children_total_count' => count($childrenData['all_children'] ?? []),
  4008. 'children_hit_avg_mastery' => $hitAvg !== null ? round($hitAvg, 4) : null,
  4009. 'level' => $this->calculateKnowledgePointLevel($kpCode),
  4010. ];
  4011. }
  4012. // 按掌握度降序排序
  4013. uasort($processed, function ($a, $b) {
  4014. return $b['mastery_level'] <=> $a['mastery_level'];
  4015. });
  4016. return $processed;
  4017. }
  4018. /**
  4019. * 【修复】获取子知识点列表(只返回本次考试涉及的)
  4020. */
  4021. private function getChildKnowledgePoints(string $parentKpCode, array $kpNameMap, array $examKpCodes = [], array $masteryMap = []): array
  4022. {
  4023. $allChildren = [];
  4024. $hitChildren = [];
  4025. try {
  4026. $childCodes = DB::connection('mysql')
  4027. ->table('knowledge_points')
  4028. ->where('parent_kp_code', $parentKpCode)
  4029. ->pluck('kp_code')
  4030. ->toArray();
  4031. foreach ($childCodes as $childCode) {
  4032. $isHit = in_array($childCode, $examKpCodes);
  4033. $childData = [
  4034. 'kp_code' => $childCode,
  4035. 'kp_name' => $kpNameMap[$childCode] ?? $childCode,
  4036. 'mastery_level' => floatval($masteryMap[$childCode] ?? 0),
  4037. 'is_hit' => $isHit,
  4038. ];
  4039. $allChildren[] = $childData;
  4040. if ($isHit) {
  4041. $hitChildren[] = $childData;
  4042. }
  4043. }
  4044. } catch (\Exception $e) {
  4045. Log::warning('获取子知识点失败', [
  4046. 'parent_kp_code' => $parentKpCode,
  4047. 'error' => $e->getMessage(),
  4048. ]);
  4049. }
  4050. return [
  4051. 'all_children' => $allChildren,
  4052. 'hit_children' => $hitChildren,
  4053. ];
  4054. }
  4055. /**
  4056. * 当历史父节点概览缺失时,直接由“本卷命中知识点”反推出父节点并构建展示数据。
  4057. */
  4058. private function buildParentMasteryFromHitCodes(
  4059. array $examKpCodes,
  4060. array $kpNameMap,
  4061. array $masteryMap = [],
  4062. array $snapshotMasteryData = []
  4063. ): array {
  4064. $codes = array_values(array_unique(array_filter(array_map(fn ($c) => trim((string) $c), $examKpCodes))));
  4065. if (empty($codes)) {
  4066. return [];
  4067. }
  4068. $rows = DB::connection('mysql')
  4069. ->table('knowledge_points')
  4070. ->whereIn('kp_code', $codes)
  4071. ->whereNotNull('parent_kp_code')
  4072. ->where('parent_kp_code', '!=', '')
  4073. ->select('kp_code', 'parent_kp_code')
  4074. ->get();
  4075. $parentMap = [];
  4076. foreach ($rows as $r) {
  4077. $parentCode = trim((string) ($r->parent_kp_code ?? ''));
  4078. $childCode = trim((string) ($r->kp_code ?? ''));
  4079. if ($parentCode === '' || $childCode === '') {
  4080. continue;
  4081. }
  4082. $parentMap[$parentCode][] = $childCode;
  4083. }
  4084. if (empty($parentMap)) {
  4085. return [];
  4086. }
  4087. $parents = DB::connection('mysql')
  4088. ->table('knowledge_points')
  4089. ->whereIn('kp_code', array_keys($parentMap))
  4090. ->pluck('name', 'kp_code')
  4091. ->toArray();
  4092. $processed = [];
  4093. foreach ($parentMap as $parentCode => $hitChildrenCodes) {
  4094. $childrenData = $this->getChildKnowledgePoints($parentCode, $kpNameMap, $codes, $masteryMap);
  4095. $allChildren = $childrenData['all_children'] ?? [];
  4096. $hitChildren = $childrenData['hit_children'] ?? [];
  4097. $hitCount = count($hitChildren);
  4098. if ($hitCount <= 0) {
  4099. continue;
  4100. }
  4101. $allLevels = array_map(fn ($c) => floatval($c['mastery_level'] ?? 0), $allChildren);
  4102. $masteryLevel = !empty($allLevels) ? array_sum($allLevels) / count($allLevels) : 0.0;
  4103. $prevLevels = [];
  4104. foreach ($allChildren as $child) {
  4105. $childCode = (string) ($child['kp_code'] ?? '');
  4106. if ($childCode === '') {
  4107. continue;
  4108. }
  4109. $currentChild = floatval($masteryMap[$childCode] ?? 0);
  4110. $prevFromSnapshot = $snapshotMasteryData[$childCode]['previous_mastery'] ?? null;
  4111. $currFromSnapshot = $snapshotMasteryData[$childCode]['current_mastery'] ?? null;
  4112. $previousChild = $prevFromSnapshot ?? $currFromSnapshot ?? $currentChild;
  4113. $prevLevels[] = floatval($previousChild);
  4114. }
  4115. $masteryChange = !empty($prevLevels) ? ($masteryLevel - (array_sum($prevLevels) / count($prevLevels))) : null;
  4116. $hitLevels = array_map(fn ($c) => floatval($c['mastery_level'] ?? 0), $hitChildren);
  4117. $hitAvg = !empty($hitLevels) ? array_sum($hitLevels) / count($hitLevels) : null;
  4118. $processed[$parentCode] = [
  4119. 'kp_code' => $parentCode,
  4120. 'kp_name' => $parents[$parentCode] ?? ($kpNameMap[$parentCode] ?? $parentCode),
  4121. 'mastery_level' => round(floatval($masteryLevel), 4),
  4122. 'mastery_percentage' => round(floatval($masteryLevel) * 100, 2),
  4123. 'mastery_change' => $masteryChange !== null ? round(floatval($masteryChange), 4) : null,
  4124. 'change_source' => 'hit_kp_parent_fallback',
  4125. 'children' => $hitChildren,
  4126. 'children_all' => $allChildren,
  4127. 'children_hit_count' => $hitCount,
  4128. 'children_total_count' => count($allChildren),
  4129. 'children_hit_avg_mastery' => $hitAvg !== null ? round($hitAvg, 4) : null,
  4130. 'level' => $this->calculateKnowledgePointLevel($parentCode),
  4131. ];
  4132. }
  4133. uasort($processed, fn ($a, $b) => $b['mastery_level'] <=> $a['mastery_level']);
  4134. return $processed;
  4135. }
  4136. /**
  4137. * 计算知识点层级深度
  4138. */
  4139. private function calculateKnowledgePointLevel(string $kpCode): int
  4140. {
  4141. // 根据kp_code前缀判断层级深度
  4142. // 例如: M (1级) -> M01 (2级) -> M01A (3级)
  4143. if (preg_match('/^[A-Z]+$/', $kpCode)) {
  4144. return 1; // 一级分类,如 M, S, E, G
  4145. } elseif (preg_match('/^[A-Z]+\d+$/', $kpCode)) {
  4146. return 2; // 二级分类,如 M01, S02
  4147. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+$/', $kpCode)) {
  4148. return 3; // 三级分类,如 M01A, S02B
  4149. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+\d+$/', $kpCode)) {
  4150. return 4; // 四级分类,如 M01A1
  4151. }
  4152. return 1; // 默认一级
  4153. }
  4154. /**
  4155. * 构建题目数据(用于PDF生成)
  4156. */
  4157. private function buildQuestionsData(Paper $paper): array
  4158. {
  4159. $paperQuestions = $paper->questions()->orderBy('question_number')->get();
  4160. $questionsData = [];
  4161. foreach ($paperQuestions as $pq) {
  4162. $questionsData[] = [
  4163. 'id' => $pq->question_bank_id,
  4164. 'question_number' => $pq->question_number, // 传递原始题号,确保渲染时序号正确
  4165. 'kp_code' => $pq->knowledge_point,
  4166. 'question_type' => $pq->question_type ?? 'answer',
  4167. 'stem' => $pq->question_text ?? '题目内容缺失',
  4168. 'solution' => $pq->solution ?? '',
  4169. 'answer' => $pq->correct_answer ?? '',
  4170. 'difficulty' => $pq->difficulty ?? 0.5,
  4171. 'score' => $pq->score ?? 5,
  4172. 'tags' => '',
  4173. 'content' => $pq->question_text ?? '',
  4174. ];
  4175. }
  4176. // 获取完整题目详情
  4177. if (! empty($questionsData)) {
  4178. $questionIds = array_column($questionsData, 'id');
  4179. $questionsResponse = $this->questionServiceApi->getQuestionsByIds($questionIds);
  4180. $responseData = $questionsResponse['data'] ?? [];
  4181. if (! empty($responseData)) {
  4182. $responseDataMap = [];
  4183. foreach ($responseData as $respQ) {
  4184. $responseDataMap[$respQ['id']] = $respQ;
  4185. }
  4186. $questionsData = array_map(function ($q) use ($responseDataMap) {
  4187. if (isset($responseDataMap[$q['id']])) {
  4188. $apiData = $responseDataMap[$q['id']];
  4189. $q['stem'] = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  4190. $q['content'] = $q['stem'];
  4191. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  4192. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  4193. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  4194. $q['options'] = $apiData['options'] ?? [];
  4195. }
  4196. return $q;
  4197. }, $questionsData);
  4198. }
  4199. }
  4200. // 按题型分类
  4201. $classified = ['choice' => [], 'fill' => [], 'answer' => []];
  4202. foreach ($questionsData as $q) {
  4203. $type = $this->determineQuestionType($q);
  4204. $classified[$type][] = (object) $q;
  4205. }
  4206. // 【调试】记录题目分类情况
  4207. Log::debug('buildQuestionsData: 题目分类结果', [
  4208. 'total_questions' => count($questionsData),
  4209. 'choice_count' => count($classified['choice']),
  4210. 'fill_count' => count($classified['fill']),
  4211. 'answer_count' => count($classified['answer']),
  4212. 'choice_numbers' => array_map(fn ($q) => $q->question_number ?? 'N/A', $classified['choice']),
  4213. 'fill_numbers' => array_map(fn ($q) => $q->question_number ?? 'N/A', $classified['fill']),
  4214. 'answer_numbers' => array_map(fn ($q) => $q->question_number ?? 'N/A', $classified['answer']),
  4215. ]);
  4216. return $classified;
  4217. }
  4218. /**
  4219. * 获取学生信息
  4220. */
  4221. private function getStudentInfo(?string $studentId): array
  4222. {
  4223. if (! $studentId) {
  4224. return [
  4225. 'name' => '未知学生',
  4226. 'grade' => '未知年级',
  4227. 'class' => '未知班级',
  4228. ];
  4229. }
  4230. try {
  4231. $student = DB::table('students')
  4232. ->where('student_id', $studentId)
  4233. ->first();
  4234. if ($student) {
  4235. return [
  4236. 'name' => $student->name ?? $studentId,
  4237. 'grade' => $student->grade ?? '未知',
  4238. 'class' => $student->class ?? '未知',
  4239. ];
  4240. }
  4241. } catch (\Exception $e) {
  4242. Log::warning('获取学生信息失败', [
  4243. 'student_id' => $studentId,
  4244. 'error' => $e->getMessage(),
  4245. ]);
  4246. }
  4247. return [
  4248. 'name' => $studentId,
  4249. 'grade' => '未知',
  4250. 'class' => '未知',
  4251. ];
  4252. }
  4253. /**
  4254. * 获取教师信息
  4255. */
  4256. private function getTeacherInfo(?string $teacherId): array
  4257. {
  4258. if (! $teacherId) {
  4259. return [
  4260. 'name' => '未知老师',
  4261. 'subject' => '数学',
  4262. ];
  4263. }
  4264. try {
  4265. $query = DB::table('teachers')->where('teacher_id', $teacherId);
  4266. // 仅在列存在时追加,避免 Unknown column 'id'
  4267. if (Schema::hasColumn('teachers', 'id')) {
  4268. $query->orWhere('id', $teacherId);
  4269. }
  4270. $teacher = $query->first();
  4271. if ($teacher) {
  4272. return [
  4273. 'name' => $teacher->name ?? '________',
  4274. 'subject' => $teacher->subject ?? '数学',
  4275. ];
  4276. }
  4277. } catch (\Exception $e) {
  4278. Log::warning('获取教师信息失败', [
  4279. 'teacher_id' => $teacherId,
  4280. 'error' => $e->getMessage(),
  4281. ]);
  4282. }
  4283. return [
  4284. 'name' => '________',
  4285. 'subject' => '数学',
  4286. ];
  4287. }
  4288. /**
  4289. * 判断题目类型
  4290. * 【修复】优先使用 question_type 字段,避免选择题因含有()被误判为填空题
  4291. */
  4292. private function determineQuestionType(array $question): string
  4293. {
  4294. // 1. 【优先】根据已有类型字段判断(最可靠的来源)
  4295. if (! empty($question['question_type'])) {
  4296. $type = strtolower(trim($question['question_type']));
  4297. if (in_array($type, ['choice', '选择题'])) {
  4298. return 'choice';
  4299. }
  4300. if (in_array($type, ['fill', '填空题'])) {
  4301. return 'fill';
  4302. }
  4303. if (in_array($type, ['answer', '解答题'])) {
  4304. return 'answer';
  4305. }
  4306. }
  4307. // 2. 如果没有明确类型,则根据题干内容推断
  4308. $stem = $question['stem'] ?? $question['content'] ?? '';
  4309. if (is_string($stem)) {
  4310. // 检查是否有选项模式 A. B. C. D.
  4311. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  4312. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  4313. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  4314. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  4315. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0);
  4316. if ($optionCount >= 2) {
  4317. return 'choice';
  4318. }
  4319. // 检查是否有填空标记(但要排除选择题的括号)
  4320. if (preg_match('/(\s*)|\(\s*\)/', $stem)) {
  4321. return 'fill';
  4322. }
  4323. }
  4324. // 3. 默认返回解答题
  4325. return 'answer';
  4326. }
  4327. /**
  4328. * 格式化换行符:将字面的 \n 转换为 HTML <br> 标签
  4329. * 用于 PDF 渲染时正确显示换行
  4330. */
  4331. private function formatNewlines(?string $text): ?string
  4332. {
  4333. if ($text === null) {
  4334. return null;
  4335. }
  4336. // 【修复】替换 \n 为 <br>,但保护 LaTeX 命令如 \neq, \ne, \newline, \nu 等
  4337. // 使用负向前瞻 (?![a-zA-Z]) 避免误伤 LaTeX 命令
  4338. $text = preg_replace('/\\\\n(?![a-zA-Z])/', '<br>', $text);
  4339. // 合并连续的 <br>(最多保留2个)
  4340. return preg_replace('/(<br>\s*){3,}/', '<br><br>', $text);
  4341. }
  4342. /**
  4343. * 根据指定的题目生成PDF(新增方法)
  4344. *
  4345. * @param object $paper 虚拟试卷对象
  4346. * @param array $groupedQuestions 按题型分组的题目数据
  4347. * @param array $student 学生信息 ['name' => '', 'grade' => '']
  4348. * @param array $teacher 教师信息 ['name' => '']
  4349. * @param bool $includeGrading 是否包含判卷版本
  4350. * @return array 返回 ['pdf_url' => '...', 'grading_pdf_url' => '...']
  4351. */
  4352. public function generateByQuestions(
  4353. object $paper,
  4354. array $groupedQuestions,
  4355. array $student = [],
  4356. array $teacher = [],
  4357. bool $includeGrading = false
  4358. ): array {
  4359. Log::info('generateByQuestions 开始', [
  4360. 'paper_id' => $paper->paper_id,
  4361. 'question_counts' => [
  4362. 'choice' => count($groupedQuestions['choice'] ?? []),
  4363. 'fill' => count($groupedQuestions['fill'] ?? []),
  4364. 'answer' => count($groupedQuestions['answer'] ?? []),
  4365. ],
  4366. 'include_grading' => $includeGrading,
  4367. ]);
  4368. try {
  4369. $result = [];
  4370. // 1. 生成试卷PDF(不含答案)
  4371. $examHtml = $this->renderCustomExamHtml($paper, $groupedQuestions, $student, $teacher, false);
  4372. if ($examHtml) {
  4373. // 【修复】使用服务端 KaTeX 预渲染 LaTeX 公式
  4374. if ($this->katexRenderer) {
  4375. $examHtml = $this->katexRenderer->renderHtml($examHtml);
  4376. }
  4377. // 与学生卷 PDF 一致:扁长图走自适应宽度(与 renderAndStoreExamPdf 第二参语义对齐)
  4378. $examPdf = $this->buildPdf($examHtml, true);
  4379. if ($examPdf) {
  4380. $examPath = "custom_exams/{$paper->paper_id}_exam.pdf";
  4381. $examUrl = $this->pdfStorageService->put($examPath, $examPdf);
  4382. $result['pdf_url'] = $examUrl;
  4383. Log::info('试卷PDF生成成功', ['url' => $examUrl]);
  4384. }
  4385. }
  4386. // 2. 如果需要,生成判卷PDF(含答案)
  4387. if ($includeGrading) {
  4388. $gradingHtml = $this->renderCustomExamHtml($paper, $groupedQuestions, $student, $teacher, true);
  4389. if ($gradingHtml) {
  4390. // 【修复】使用服务端 KaTeX 预渲染 LaTeX 公式
  4391. if ($this->katexRenderer) {
  4392. $gradingHtml = $this->katexRenderer->renderHtml($gradingHtml);
  4393. }
  4394. $gradingPdf = $this->buildPdf($gradingHtml, true);
  4395. if ($gradingPdf) {
  4396. $gradingPath = "custom_exams/{$paper->paper_id}_grading.pdf";
  4397. $gradingUrl = $this->pdfStorageService->put($gradingPath, $gradingPdf);
  4398. $result['grading_pdf_url'] = $gradingUrl;
  4399. Log::info('判卷PDF生成成功', ['url' => $gradingUrl]);
  4400. }
  4401. }
  4402. }
  4403. return $result;
  4404. } catch (\Throwable $e) {
  4405. Log::error('generateByQuestions 失败', [
  4406. 'paper_id' => $paper->paper_id,
  4407. 'error' => $e->getMessage(),
  4408. 'trace' => $e->getTraceAsString(),
  4409. ]);
  4410. throw $e;
  4411. }
  4412. }
  4413. /**
  4414. * 题目质检专用 PDF:固定使用判题卡体系模板(答案详解 + 判题卡)。
  4415. * 不进入正常组卷流程,仅用于检查题干、答案、解题思路渲染效果。
  4416. *
  4417. * @return array{pdf_url?: string,grading_pdf_url?: string,local_path?: string}
  4418. */
  4419. public function generateQuestionCheckPdf(
  4420. object $paper,
  4421. array $groupedQuestions,
  4422. array $student = [],
  4423. array $teacher = [],
  4424. ?string $localOutputPath = null
  4425. ): array {
  4426. Log::info('generateQuestionCheckPdf 开始', [
  4427. 'paper_id' => $paper->paper_id ?? null,
  4428. 'question_counts' => [
  4429. 'choice' => count($groupedQuestions['choice'] ?? []),
  4430. 'fill' => count($groupedQuestions['fill'] ?? []),
  4431. 'answer' => count($groupedQuestions['answer'] ?? []),
  4432. ],
  4433. ]);
  4434. $studentName = $student['name'] ?? ($paper->student_id ?? '________');
  4435. $examCode = \App\Support\PaperNaming::extractExamCode((string) ($paper->paper_id ?? 'custom'));
  4436. $pdfMeta = [
  4437. 'student_name' => $studentName,
  4438. 'exam_code' => $examCode,
  4439. 'assemble_type_label' => '题目质检',
  4440. 'header_title' => $examCode,
  4441. 'exam_pdf_title' => '题目质检_'.$examCode,
  4442. 'grading_pdf_title' => '题目质检_'.$examCode,
  4443. 'knowledge_pdf_title' => '题目质检_'.$examCode,
  4444. ];
  4445. try {
  4446. // 固定走题目质检专用模板:题干+答案+解题思路 + 判题卡附页
  4447. $html = view('pdf.question-check', [
  4448. 'paper' => $paper,
  4449. 'questions' => $groupedQuestions,
  4450. 'student' => $student,
  4451. 'teacher' => $teacher,
  4452. 'pdfMeta' => $pdfMeta,
  4453. ])->render();
  4454. if (empty(trim($html))) {
  4455. Log::error('generateQuestionCheckPdf: HTML 渲染为空', [
  4456. 'paper_id' => $paper->paper_id ?? null,
  4457. ]);
  4458. return [];
  4459. }
  4460. if ($this->katexRenderer) {
  4461. $html = $this->katexRenderer->renderHtml($html);
  4462. }
  4463. // 与 renderAndStoreExamPdf 学生卷一致:启用扁长图自适应(buildPdf 第二参 true)
  4464. $pdfBinary = $this->buildPdf($this->ensureUtf8Html($html), true);
  4465. if (empty($pdfBinary)) {
  4466. Log::error('generateQuestionCheckPdf: buildPdf 失败', [
  4467. 'paper_id' => $paper->paper_id ?? null,
  4468. ]);
  4469. return [];
  4470. }
  4471. if ($localOutputPath !== null && $localOutputPath !== '') {
  4472. $dir = dirname($localOutputPath);
  4473. if ($dir !== '.' && $dir !== '' && ! is_dir($dir)) {
  4474. @mkdir($dir, 0775, true);
  4475. }
  4476. if (file_put_contents($localOutputPath, $pdfBinary) === false) {
  4477. Log::error('generateQuestionCheckPdf: 本地写入失败', [
  4478. 'paper_id' => $paper->paper_id ?? null,
  4479. 'local_path' => $localOutputPath,
  4480. ]);
  4481. return [];
  4482. }
  4483. Log::info('generateQuestionCheckPdf: 已写入本地', [
  4484. 'paper_id' => $paper->paper_id ?? null,
  4485. 'local_path' => $localOutputPath,
  4486. 'bytes' => strlen($pdfBinary),
  4487. ]);
  4488. return [
  4489. 'local_path' => $localOutputPath,
  4490. ];
  4491. }
  4492. $path = 'custom_exams/'.($paper->paper_id ?? ('custom_'.time())).'.pdf';
  4493. $url = $this->pdfStorageService->put($path, $pdfBinary);
  4494. if (! $url) {
  4495. Log::error('generateQuestionCheckPdf: 上传失败', [
  4496. 'paper_id' => $paper->paper_id ?? null,
  4497. 'path' => $path,
  4498. ]);
  4499. return [];
  4500. }
  4501. return [
  4502. 'pdf_url' => $url,
  4503. 'grading_pdf_url' => $url,
  4504. ];
  4505. } catch (\Throwable $e) {
  4506. Log::error('generateQuestionCheckPdf 失败', [
  4507. 'paper_id' => $paper->paper_id ?? null,
  4508. 'error' => $e->getMessage(),
  4509. 'trace' => $e->getTraceAsString(),
  4510. ]);
  4511. throw $e;
  4512. }
  4513. }
  4514. /**
  4515. * 渲染自定义题目的HTML
  4516. */
  4517. private function renderCustomExamHtml(
  4518. object $paper,
  4519. array $groupedQuestions,
  4520. array $student,
  4521. array $teacher,
  4522. bool $grading
  4523. ): ?string {
  4524. try {
  4525. $viewName = $this->resolveExamViewName($grading);
  4526. $html = view($viewName, [
  4527. 'paper' => $paper,
  4528. 'questions' => $groupedQuestions,
  4529. 'student' => $student,
  4530. 'teacher' => $teacher,
  4531. 'grading' => $grading,
  4532. 'includeAnswer' => false, // exam-paper 视图需要这个变量
  4533. ])->render();
  4534. if (empty(trim($html))) {
  4535. Log::error('renderCustomExamHtml: 视图渲染结果为空', [
  4536. 'paper_id' => $paper->paper_id,
  4537. 'view_name' => $viewName,
  4538. ]);
  4539. return null;
  4540. }
  4541. return $this->ensureUtf8Html($html);
  4542. } catch (\Exception $e) {
  4543. Log::error('renderCustomExamHtml 失败', [
  4544. 'paper_id' => $paper->paper_id,
  4545. 'error' => $e->getMessage(),
  4546. 'trace' => $e->getTraceAsString(),
  4547. ]);
  4548. return null;
  4549. }
  4550. }
  4551. private function resolveExamViewName(bool $useGradingView): string
  4552. {
  4553. if (! $useGradingView) {
  4554. return 'pdf.exam-paper';
  4555. }
  4556. return config('exam.pdf_grading_append_scan_sheet', false)
  4557. ? 'pdf.exam-answer-detail'
  4558. : 'pdf.exam-grading';
  4559. }
  4560. private function normalizeAnswerFieldForPdf(object $question): object
  4561. {
  4562. $normalizedQuestion = clone $question;
  4563. // 以 paper_questions.question_text 为标准题干字段,兼容旧链路 content。
  4564. $questionText = trim((string) ($normalizedQuestion->question_text ?? ''));
  4565. if ($questionText === '') {
  4566. $questionText = trim((string) ($normalizedQuestion->content ?? ''));
  4567. }
  4568. if ($questionText !== '') {
  4569. $normalizedQuestion->question_text = $questionText;
  4570. $normalizedQuestion->content = $questionText;
  4571. }
  4572. $answerText = trim((string) ($normalizedQuestion->answer ?? ''));
  4573. if ($answerText !== '') {
  4574. return $normalizedQuestion;
  4575. }
  4576. foreach (['correct_answer', 'standard_answer', 'reference_answer'] as $fallbackField) {
  4577. $candidate = trim((string) ($normalizedQuestion->{$fallbackField} ?? ''));
  4578. if ($candidate !== '') {
  4579. $normalizedQuestion->answer = $candidate;
  4580. break;
  4581. }
  4582. }
  4583. return $normalizedQuestion;
  4584. }
  4585. /**
  4586. * 生成预览 PDF(用于题目预览验证工具)
  4587. *
  4588. * @param array $questionData 题目数据 ['stem', 'options', 'answer', 'solution', 'question_type']
  4589. * @return array|null 返回 ['url' => '...'] 或 null
  4590. */
  4591. public function generatePreviewPdf(array $questionData): ?array
  4592. {
  4593. try {
  4594. Log::info('generatePreviewPdf 开始', ['question_data' => $questionData]);
  4595. // 渲染 HTML
  4596. $html = $this->renderPreviewHtml($questionData);
  4597. if (empty($html)) {
  4598. Log::error('generatePreviewPdf: HTML 渲染为空');
  4599. return null;
  4600. }
  4601. // 生成 PDF
  4602. $pdfContent = $this->buildPdf($html);
  4603. if (empty($pdfContent)) {
  4604. Log::error('generatePreviewPdf: PDF 生成为空');
  4605. return null;
  4606. }
  4607. // 保存到临时目录
  4608. $filename = 'preview_'.uniqid().'.pdf';
  4609. $path = "previews/{$filename}";
  4610. $url = $this->pdfStorageService->put($path, $pdfContent);
  4611. Log::info('generatePreviewPdf 成功', ['url' => $url]);
  4612. return ['url' => $url];
  4613. } catch (\Exception $e) {
  4614. Log::error('generatePreviewPdf 失败', [
  4615. 'error' => $e->getMessage(),
  4616. 'trace' => $e->getTraceAsString(),
  4617. ]);
  4618. return null;
  4619. }
  4620. }
  4621. /**
  4622. * 渲染预览 HTML
  4623. */
  4624. private function renderPreviewHtml(array $questionData): string
  4625. {
  4626. $stem = $questionData['stem'] ?? '';
  4627. $options = $questionData['options'] ?? null;
  4628. $answer = $questionData['answer'] ?? '';
  4629. $solution = $questionData['solution'] ?? '';
  4630. $questionType = $questionData['question_type'] ?? 'fill';
  4631. // 使用 MathFormulaProcessor 处理公式
  4632. $processedStem = MathFormulaProcessor::processFormulas($stem);
  4633. $processedAnswer = MathFormulaProcessor::processFormulas($answer);
  4634. $processedSolution = MathFormulaProcessor::processFormulas($this->formatNewlines($solution));
  4635. $processedOptions = null;
  4636. if ($options && is_array($options)) {
  4637. $processedOptions = [];
  4638. foreach ($options as $key => $value) {
  4639. $processedOptions[$key] = MathFormulaProcessor::processFormulas($value);
  4640. }
  4641. }
  4642. // 渲染 HTML
  4643. return view('pdf.question-preview', [
  4644. 'stem' => $processedStem,
  4645. 'options' => $processedOptions,
  4646. 'answer' => $processedAnswer,
  4647. 'solution' => $processedSolution,
  4648. 'questionType' => $questionType,
  4649. ])->render();
  4650. }
  4651. /**
  4652. * 批量获取知识点的讲解内容
  4653. *
  4654. * @param array $kpCodes 知识点代码数组
  4655. * @return array [kp_code => explanation]
  4656. */
  4657. public function buildExplanations(array $kpCodes): array
  4658. {
  4659. $result = [];
  4660. if (empty($kpCodes)) {
  4661. return $result;
  4662. }
  4663. try {
  4664. // 批量获取知识点讲解
  4665. $kps = \App\Models\KnowledgePoint::whereIn('kp_code', $kpCodes)->get()->keyBy('kp_code');
  4666. // 有多少算多少
  4667. foreach ($kpCodes as $kpCode) {
  4668. $kp = $kps->get($kpCode);
  4669. if ($kp && ! empty($kp->explanation)) {
  4670. $result[] = [
  4671. 'kp_code' => $kpCode,
  4672. 'kp_name' => $kp->name ?? $kpCode,
  4673. 'explanation' => $this->normalizeKpExplanation($kp->explanation),
  4674. ];
  4675. continue;
  4676. }
  4677. $result[] = [
  4678. 'kp_code' => $kpCode,
  4679. 'kp_name' => $kp->name ?? $kpCode,
  4680. 'explanation' => $this->normalizeKpExplanation(
  4681. $this->getDefaultExplanation($kpCode, $kp->name ?? $kpCode)
  4682. ),
  4683. ];
  4684. }
  4685. } catch (\Throwable $e) {
  4686. Log::warning('批量获取知识点讲解失败', [
  4687. 'kp_codes' => $kpCodes,
  4688. 'error' => $e->getMessage(),
  4689. ]);
  4690. // 失败时返回默认内容
  4691. foreach ($kpCodes as $kpCode) {
  4692. $result[] = [
  4693. 'kp_code' => $kpCode,
  4694. 'kp_name' => $kpCode,
  4695. 'explanation' => $this->normalizeKpExplanation(
  4696. $this->getDefaultExplanation($kpCode, $kpCode)
  4697. ),
  4698. ];
  4699. }
  4700. }
  4701. return $result;
  4702. }
  4703. /**
  4704. * 获取默认的知识点讲解内容
  4705. */
  4706. private function getDefaultExplanation(string $kpCode, string $kpName): string
  4707. {
  4708. // 默认讲解模板
  4709. // 注意:PHP HEREDOC 中 \e 会被解释为 ESC 字符,所以需要用 \\end 而非 \end
  4710. return <<<'MARKDOWN'
  4711. ## 知识点
  4712. (1) 核心定义:二元一次方程是含有两个未知数且每个未知数的次数都是 1 的方程,一般形式为 $ax + by = c$(其中 $a,b,c$ 为常数,且 $a,b$ 不同时为 0)。二元一次方程组是由两个(或两个以上)二元一次方程组成,常见为
  4713. $$
  4714. \begin{cases}
  4715. a_1x + b_1y = c_1\\
  4716. a_2x + b_2y = c_2
  4717. \end{cases}
  4718. $$
  4719. 方程组应用建模就是把题目中的数量关系翻译成方程组,通过求解得到实际问题的答案。
  4720. (2) 性质定理:方程组的解必须同时满足方程组中的每一个方程,因此解是两个方程公共的 $(x,y)$。常用解法有代入消元法与加减消元法:代入消元法适合某个方程易表示成 $x = \dots$ 或 $y = \dots$;加减消元法适合两个方程中某个未知数的系数相同或相反,便于相加或相减消去一个未知数。建模时常用关系包括:总量关系(如“总数 = 部分之和”)、单价数量总价关系(“$总价 = 单价 \times 数量$”)、路程速度时间关系($路程 = 速度 \times 时间$)等。
  4721. (3) 注意事项:设未知数要带单位与含义,例如“设甲买了 $x$ 支笔”;列方程要对应同一类量,别把“支数”和“元数”混在一条等式里;检查条件是否满足题意(如数量应为整数且 $> 0$);消元后别忘了回代求另一个未知数;最后答案要写清对象与单位,并可把解代回原式检验。
  4722. ## 知识点应用
  4723. - 典型例题:文具店买笔和本子。小明买了 2 支笔和 3 本本子共花 19 元;小红买了 3 支笔和 2 本本子共花 18 元。求每支笔和每本本子的单价。
  4724. - 关键步骤:
  4725. 1. 设未知数并写出含义:设每支笔单价为 $x$ 元,每本本子单价为 $y$ 元。
  4726. 2. 根据题意列方程组:由“$总价 = 单价 \times 数量$”得
  4727. $$
  4728. \begin{cases}
  4729. 2x + 3y = 19\\
  4730. 3x + 2y = 18
  4731. \end{cases}
  4732. $$
  4733. 3. 选择消元并求解:用加减消元。将第一式乘 3、第二式乘 2:
  4734. $$
  4735. \begin{cases}
  4736. 6x + 9y = 57\\
  4737. 6x + 4y = 36
  4738. \end{cases}
  4739. $$
  4740. 相减得 $5y = 21$,所以 $y = \dfrac{21}{5} = 4.2$。代入 $3x + 2y = 18$ 得 $3x + 8.4 = 18$,所以 $3x = 9.6$,$x = 3.2$。
  4741. - 结论:每支笔 3.2 元,每本本子 4.2 元(两者均 $> 0$,符合题意)。
  4742. MARKDOWN;
  4743. }
  4744. private function normalizeKpExplanation(string $content): string
  4745. {
  4746. $content = trim($content);
  4747. if ($content === '') {
  4748. return '';
  4749. }
  4750. if ($this->looksLikeRenderedKpHtml($content)) {
  4751. return $content;
  4752. }
  4753. if ($this->looksLikeHtml($content) && ! $this->looksLikeMarkdown($content)) {
  4754. return $content;
  4755. }
  4756. $markdown = html_entity_decode($content, ENT_QUOTES, 'UTF-8');
  4757. $rendered = $this->renderKpMarkdownContent($markdown);
  4758. return '<div class="kp-markdown-container kp-markdown-content">'.$rendered.'</div>';
  4759. }
  4760. private function renderKpMarkdownContent(string $markdown): string
  4761. {
  4762. if (class_exists(\Michelf\MarkdownExtra::class)) {
  4763. $parser = new \Michelf\MarkdownExtra;
  4764. [$protectedMarkdown, $mathPlaceholders] = $this->protectLatexBlocksForMarkdown($markdown);
  4765. $rendered = $parser->transform($protectedMarkdown);
  4766. return strtr($rendered, $mathPlaceholders);
  4767. }
  4768. return $this->renderBasicKpMarkdown($markdown);
  4769. }
  4770. private function renderBasicKpMarkdown(string $markdown): string
  4771. {
  4772. $lines = preg_split('/\R/u', trim($markdown));
  4773. if ($lines === false) {
  4774. $safe = htmlspecialchars($markdown, ENT_QUOTES, 'UTF-8');
  4775. return nl2br($safe);
  4776. }
  4777. $html = [];
  4778. $paragraph = [];
  4779. $listType = null;
  4780. $flushParagraph = function () use (&$html, &$paragraph): void {
  4781. if ($paragraph === []) {
  4782. return;
  4783. }
  4784. $html[] = '<p>'.implode('<br>', $paragraph).'</p>';
  4785. $paragraph = [];
  4786. };
  4787. $closeList = function () use (&$html, &$listType): void {
  4788. if ($listType === null) {
  4789. return;
  4790. }
  4791. $html[] = "</{$listType}>";
  4792. $listType = null;
  4793. };
  4794. $openList = function (string $type) use (&$html, &$listType, $closeList): void {
  4795. if ($listType === $type) {
  4796. return;
  4797. }
  4798. $closeList();
  4799. $html[] = "<{$type}>";
  4800. $listType = $type;
  4801. };
  4802. foreach ($lines as $line) {
  4803. $line = rtrim($line);
  4804. if ($line === '') {
  4805. $flushParagraph();
  4806. $closeList();
  4807. continue;
  4808. }
  4809. if (preg_match('/^(#{1,6})\s+(.+)$/u', $line, $match)) {
  4810. $flushParagraph();
  4811. $closeList();
  4812. $level = min(6, strlen($match[1]));
  4813. $html[] = sprintf('<h%d>%s</h%d>', $level, $this->escapeMarkdownLine($match[2]), $level);
  4814. continue;
  4815. }
  4816. if (preg_match('/^\s*[-*]\s+(.+)$/u', $line, $match)) {
  4817. $flushParagraph();
  4818. $openList('ul');
  4819. $html[] = '<li>'.$this->escapeMarkdownLine($match[1]).'</li>';
  4820. continue;
  4821. }
  4822. if (preg_match('/^\s*\d+\.\s+(.+)$/u', $line, $match)) {
  4823. $flushParagraph();
  4824. $openList('ol');
  4825. $html[] = '<li>'.$this->escapeMarkdownLine($match[1]).'</li>';
  4826. continue;
  4827. }
  4828. $paragraph[] = $this->escapeMarkdownLine($line);
  4829. }
  4830. $flushParagraph();
  4831. $closeList();
  4832. return implode("\n", $html);
  4833. }
  4834. private function escapeMarkdownLine(string $line): string
  4835. {
  4836. return htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  4837. }
  4838. /**
  4839. * 保护 Markdown 中的数学块,避免 MarkdownExtra 吃掉 LaTeX 反斜杠
  4840. */
  4841. private function protectLatexBlocksForMarkdown(string $markdown): array
  4842. {
  4843. $placeholders = [];
  4844. $index = 0;
  4845. $pattern = '/\$\$[\s\S]*?\$\$|\\\\\[[\s\S]*?\\\\\]|\\\\\([\s\S]*?\\\\\)|(?<!\$)\$[^$\n]+\$(?!\$)/';
  4846. $protected = preg_replace_callback($pattern, function (array $matches) use (&$placeholders, &$index) {
  4847. // 使用 markdown 安全占位符,避免被 __ 粗体语法吞掉
  4848. $token = "@@KPMATHBLOCK{$index}@@";
  4849. $placeholders[$token] = $matches[0];
  4850. $index++;
  4851. return $token;
  4852. }, $markdown);
  4853. return [$protected ?? $markdown, $placeholders];
  4854. }
  4855. private function looksLikeRenderedKpHtml(string $content): bool
  4856. {
  4857. if (stripos($content, 'kp-markdown-container') !== false ||
  4858. stripos($content, 'kp-markdown-content') !== false) {
  4859. return true;
  4860. }
  4861. return false;
  4862. }
  4863. private function looksLikeHtml(string $content): bool
  4864. {
  4865. return (bool) preg_match('/<\s*(p|div|h[1-6]|ul|ol|li|table|span|blockquote|pre|code|br)\b/i', $content);
  4866. }
  4867. private function looksLikeMarkdown(string $content): bool
  4868. {
  4869. return (bool) preg_match('/(^|\R)\s{0,3}#{1,6}\s+\S|(^|\R)\s{0,3}[-*]\s+\S|(^|\R)\s{0,3}\d+\.\s+\S/u', $content);
  4870. }
  4871. private function shouldUseDefaultExplanations(): bool
  4872. {
  4873. if (!Schema::hasTable('knowledge_points')) {
  4874. return true;
  4875. }
  4876. return !Schema::hasColumn('knowledge_points', 'explanation');
  4877. }
  4878. }