ExamPdfExportService.php 216 KB

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