ExamPdfExportService.php 191 KB

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