ExamPdfExportService.php 192 KB

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