ExamPdfExportService.php 206 KB

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