ExamPdfExportService.php 189 KB

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