ExamPdfExportService.php 217 KB

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