ExamPdfExportService.php 194 KB

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