ExamPdfExportService.php 198 KB

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