ExamPdfExportService.php 212 KB

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