ExamPdfExportService.php 212 KB

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