ExamPdfExportService.php 195 KB

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