ExamPdfExportService.php 199 KB

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