ExamPdfExportService.php 200 KB

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