ExamPdfExportService.php 142 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712
  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\Support\GradingStyleQuestionStem;
  9. use App\Support\PaperNaming;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\File;
  12. use Illuminate\Support\Facades\Http;
  13. use Illuminate\Support\Facades\Log;
  14. use Illuminate\Support\Facades\Schema;
  15. use Illuminate\Support\Facades\Storage;
  16. use Illuminate\Support\Facades\URL;
  17. use Illuminate\Support\Str;
  18. use Symfony\Component\Process\Exception\ProcessSignaledException;
  19. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  20. use Symfony\Component\Process\Process;
  21. /**
  22. * PDF导出服务(重构版)
  23. * 负责生成试卷PDF、判卷PDF和学情报告PDF
  24. */
  25. class ExamPdfExportService
  26. {
  27. private ?KatexRenderer $katexRenderer = null;
  28. private const PDF_IMAGE_WIDTH_WIDE_PX = 250;
  29. private const PDF_IMAGE_WIDTH_VERY_WIDE_PX = 330;
  30. /**
  31. * @var array<string, array{w:int,h:int}|null>
  32. */
  33. private array $pdfImageDimensionCache = [];
  34. private ?bool $hasPdfImageMetricsTable = null;
  35. public function __construct(
  36. private readonly LearningAnalyticsService $learningAnalyticsService,
  37. private readonly QuestionBankService $questionBankService,
  38. private readonly QuestionServiceApi $questionServiceApi,
  39. private readonly PdfStorageService $pdfStorageService,
  40. private readonly MasteryCalculator $masteryCalculator,
  41. private readonly PdfMerger $pdfMerger
  42. ) {
  43. // 延迟初始化 KatexRenderer(避免循环依赖)
  44. $this->katexRenderer = new KatexRenderer;
  45. }
  46. /**
  47. * 生成试卷 PDF(不含答案)
  48. */
  49. public function generateExamPdf(string $paperId): ?string
  50. {
  51. Log::info('generateExamPdf 开始:', ['paper_id' => $paperId]);
  52. $url = $this->renderAndStoreExamPdf($paperId, includeAnswer: false, suffix: 'exam');
  53. Log::info('generateExamPdf url 生成结果:', ['paper_id' => $paperId, 'url' => $url]);
  54. // 如果生成成功,将 URL 写入数据库
  55. if ($url) {
  56. $this->savePdfUrlToDatabase($paperId, 'exam_pdf_url', $url);
  57. }
  58. return $url;
  59. }
  60. /**
  61. * 生成判卷 PDF(含答案与解析)
  62. */
  63. public function generateGradingPdf(string $paperId): ?string
  64. {
  65. Log::info('generateGradingPdf 开始:', ['paper_id' => $paperId]);
  66. $url = $this->renderAndStoreExamPdf($paperId, includeAnswer: true, suffix: 'grading', useGradingView: true);
  67. Log::info('generateGradingPdf url 生成结果:', ['paper_id' => $paperId, 'url' => $url]);
  68. // 如果生成成功,将 URL 写入数据库
  69. if ($url) {
  70. $this->savePdfUrlToDatabase($paperId, 'grading_pdf_url', $url);
  71. }
  72. return $url;
  73. }
  74. /**
  75. * 渲染试卷 HTML → 生成 PDF → 上传存储(generateExamPdf / generateGradingPdf 共用)
  76. */
  77. private function renderAndStoreExamPdf(string $paperId, bool $includeAnswer, string $suffix, bool $useGradingView = false): ?string
  78. {
  79. $html = $this->renderExamHtml($paperId, $includeAnswer, $useGradingView);
  80. if ($html === null || trim($html) === '') {
  81. Log::error('renderAndStoreExamPdf: HTML 为空', [
  82. 'paper_id' => $paperId,
  83. 'suffix' => $suffix,
  84. ]);
  85. return null;
  86. }
  87. $pdfBinary = $this->buildPdf($html, ! $includeAnswer && ! $useGradingView);
  88. if ($pdfBinary === null || $pdfBinary === '') {
  89. Log::error('renderAndStoreExamPdf: buildPdf 失败', [
  90. 'paper_id' => $paperId,
  91. 'suffix' => $suffix,
  92. ]);
  93. return null;
  94. }
  95. $paper = Paper::query()->where('paper_id', $paperId)->first();
  96. if (! $paper) {
  97. Log::error('renderAndStoreExamPdf: 试卷不存在', ['paper_id' => $paperId]);
  98. return null;
  99. }
  100. $stamp = now()->format('YmdHis').strtoupper(Str::random(4));
  101. $base = $this->buildPaperNamePrefix($paper).'_'.$suffix.'_'.$stamp;
  102. $safe = PaperNaming::toSafeFilename($base).'.pdf';
  103. $path = 'exams/'.$safe;
  104. $url = $this->pdfStorageService->put($path, $pdfBinary);
  105. if (! $url) {
  106. Log::error('renderAndStoreExamPdf: 上传失败', ['paper_id' => $paperId, 'path' => $path]);
  107. return null;
  108. }
  109. Log::info('renderAndStoreExamPdf: 完成', [
  110. 'paper_id' => $paperId,
  111. 'suffix' => $suffix,
  112. 'url' => $url,
  113. ]);
  114. return $url;
  115. }
  116. /**
  117. * 【优化方案】生成统一PDF(卷子 + 判卷一页完成)
  118. * 效率提升40-50%,只需生成一次PDF
  119. *
  120. * @param string $paperId 试卷ID
  121. * @param bool|null $includeKpExplain 是否包含知识点讲解,null则使用配置文件默认值
  122. * @return string|null PDF URL
  123. */
  124. public function generateUnifiedPdf(string $paperId, ?bool $includeKpExplain = null): ?string
  125. {
  126. // 决定是否包含知识点讲解
  127. if ($includeKpExplain === null) {
  128. $includeKpExplain = config('pdf.include_kp_explain_default', false);
  129. }
  130. Log::info('generateUnifiedPdf 开始(终极优化版本,直接HTML合并生成PDF):', [
  131. 'paper_id' => $paperId,
  132. 'include_kp_explain' => $includeKpExplain,
  133. ]);
  134. try {
  135. // 步骤0:获取知识点讲解HTML(如需要)
  136. $kpExplainHtml = null;
  137. if ($includeKpExplain) {
  138. Log::info('generateUnifiedPdf: 开始获取知识点讲解HTML', ['paper_id' => $paperId]);
  139. $kpExplainHtml = $this->fetchKnowledgeExplanationHtml($paperId);
  140. if ($kpExplainHtml) {
  141. // 对知识点讲解HTML进行内联资源处理(与服务端公式渲染)
  142. $kpExplainHtml = $this->inlineExternalResources($kpExplainHtml);
  143. Log::info('generateUnifiedPdf: 知识点讲解HTML获取并处理成功', [
  144. 'paper_id' => $paperId,
  145. 'length' => strlen($kpExplainHtml),
  146. ]);
  147. } else {
  148. Log::warning('generateUnifiedPdf: 知识点讲解HTML获取失败,将跳过', ['paper_id' => $paperId]);
  149. }
  150. }
  151. // 步骤1:同时渲染两个页面的HTML
  152. Log::info('generateUnifiedPdf: 开始渲染试卷HTML', ['paper_id' => $paperId]);
  153. $examHtml = $this->renderExamHtml($paperId, includeAnswer: false, useGradingView: false);
  154. if (! $examHtml) {
  155. Log::error('ExamPdfExportService: 渲染卷子HTML失败', ['paper_id' => $paperId]);
  156. return null;
  157. }
  158. Log::info('generateUnifiedPdf: 试卷HTML渲染完成', ['paper_id' => $paperId, 'length' => strlen($examHtml)]);
  159. Log::info('generateUnifiedPdf: 开始渲染判卷HTML', ['paper_id' => $paperId]);
  160. $gradingHtml = $this->renderExamHtml($paperId, includeAnswer: true, useGradingView: true);
  161. if (! $gradingHtml) {
  162. Log::error('ExamPdfExportService: 渲染判卷HTML失败', ['paper_id' => $paperId]);
  163. return null;
  164. }
  165. Log::info('generateUnifiedPdf: 判卷HTML渲染完成', ['paper_id' => $paperId, 'length' => strlen($gradingHtml)]);
  166. // 步骤2:插入分页符,合并HTML
  167. Log::info('generateUnifiedPdf: 开始合并HTML(保留原始样式)', ['paper_id' => $paperId]);
  168. $unifiedHtml = $this->mergeHtmlWithPageBreak($examHtml, $gradingHtml, $kpExplainHtml);
  169. if (! $unifiedHtml) {
  170. Log::error('ExamPdfExportService: HTML合并失败', ['paper_id' => $paperId]);
  171. return null;
  172. }
  173. Log::info('generateUnifiedPdf: HTML合并完成(将直接生成PDF,不使用pdfunite)', [
  174. 'paper_id' => $paperId,
  175. 'length' => strlen($unifiedHtml),
  176. 'has_kp_explain' => ! empty($kpExplainHtml),
  177. ]);
  178. // 步骤3:一次性生成PDF(只需20-25秒,比原来节省10-25秒)
  179. Log::info('generateUnifiedPdf: 开始使用buildPdf直接生成PDF(不使用pdfunite)', ['paper_id' => $paperId]);
  180. $pdfBinary = $this->buildPdf($unifiedHtml, true, true);
  181. if (! $pdfBinary) {
  182. Log::error('ExamPdfExportService: 生成统一PDF失败', ['paper_id' => $paperId]);
  183. return null;
  184. }
  185. Log::info('generateUnifiedPdf: PDF生成完成', ['paper_id' => $paperId, 'pdf_size' => strlen($pdfBinary)]);
  186. // 步骤4:保存PDF
  187. $paper = Paper::where('paper_id', $paperId)->first();
  188. if (! $paper) {
  189. Log::error('ExamPdfExportService: 生成统一PDF失败,未找到试卷', ['paper_id' => $paperId]);
  190. return null;
  191. }
  192. $allPdfName = $this->buildPdfFileName($paper);
  193. $path = "exams/{$allPdfName}";
  194. Log::info('generateUnifiedPdf: 开始保存PDF到云存储', ['paper_id' => $paperId, 'path' => $path]);
  195. $url = $this->pdfStorageService->put($path, $pdfBinary);
  196. if (! $url) {
  197. Log::error('ExamPdfExportService: 保存统一PDF失败', ['path' => $path]);
  198. return null;
  199. }
  200. Log::info('generateUnifiedPdf: PDF保存完成', ['paper_id' => $paperId, 'url' => $url]);
  201. // 步骤5:保存URL到数据库(存储到all_pdf_url字段)
  202. Log::info('generateUnifiedPdf: 开始保存URL到数据库', ['paper_id' => $paperId, 'field' => 'all_pdf_url']);
  203. $this->savePdfUrlToDatabase($paperId, 'all_pdf_url', $url);
  204. Log::info('generateUnifiedPdf: URL保存完成', ['paper_id' => $paperId]);
  205. Log::info('generateUnifiedPdf 全部完成(终极优化:直接HTML合并生成一份PDF)', [
  206. 'paper_id' => $paperId,
  207. 'url' => $url,
  208. 'pdf_size' => strlen($pdfBinary),
  209. 'method' => 'direct HTML merge to PDF (no pdfunite)',
  210. ]);
  211. return $url;
  212. } catch (\Throwable $e) {
  213. Log::error('generateUnifiedPdf 失败', [
  214. 'paper_id' => $paperId,
  215. 'error' => $e->getMessage(),
  216. 'trace' => $e->getTraceAsString(),
  217. ]);
  218. return null;
  219. }
  220. }
  221. /**
  222. * 生成学情分析 PDF
  223. */
  224. public function generateAnalysisReportPdf(string $paperId, string $studentId, ?string $recordId = null): ?string
  225. {
  226. if (function_exists('set_time_limit')) {
  227. @set_time_limit(240);
  228. }
  229. try {
  230. Log::info('ExamPdfExportService: 开始生成学情分析PDF', [
  231. 'paper_id' => $paperId,
  232. 'student_id' => $studentId,
  233. 'record_id' => $recordId,
  234. ]);
  235. // 构建分析数据
  236. $analysisData = $this->buildAnalysisData($paperId, $studentId);
  237. if (! $analysisData) {
  238. Log::warning('ExamPdfExportService: buildAnalysisData返回空数据', [
  239. 'paper_id' => $paperId,
  240. 'student_id' => $studentId,
  241. ]);
  242. return null;
  243. }
  244. Log::info('ExamPdfExportService: buildAnalysisData返回数据', [
  245. 'paper_id' => $paperId,
  246. 'student_id' => $studentId,
  247. 'analysisData_keys' => array_keys($analysisData),
  248. 'mastery_count' => count($analysisData['mastery']['items'] ?? []),
  249. 'questions_count' => count($analysisData['questions'] ?? []),
  250. ]);
  251. // 创建DTO
  252. $dto = ExamAnalysisDataDto::fromArray($analysisData);
  253. $payloadDto = ReportPayloadDto::fromExamAnalysisDataDto($dto);
  254. // 打印传给模板的数据
  255. $templateData = $payloadDto->toArray();
  256. Log::info('ExamPdfExportService: 传给模板的数据', [
  257. 'paper' => $templateData['paper'] ?? null,
  258. 'student' => $templateData['student'] ?? null,
  259. 'mastery' => $templateData['mastery'] ?? null,
  260. 'parent_mastery_levels' => $templateData['parent_mastery_levels'] ?? null,
  261. 'questions_count' => count($templateData['questions'] ?? []),
  262. 'insights_count' => count($templateData['question_insights'] ?? []),
  263. 'recommendations_count' => count($templateData['recommendations'] ?? []),
  264. ]);
  265. // 【重要】处理题目数据中的图片标签和公式
  266. // 将 <image src="..."/> 转换为 <img src="..." />,并处理公式
  267. if (! empty($templateData['questions'])) {
  268. foreach ($templateData['questions'] as $idx => $question) {
  269. $templateData['questions'][$idx] = MathFormulaProcessor::processQuestionData($question);
  270. }
  271. }
  272. if (! empty($templateData['question_insights'])) {
  273. foreach ($templateData['question_insights'] as $idx => $insight) {
  274. $templateData['question_insights'][$idx] = MathFormulaProcessor::processQuestionData($insight);
  275. }
  276. }
  277. // 渲染HTML
  278. $html = view('exam-analysis.pdf-report', $templateData)->render();
  279. if (! $html) {
  280. Log::error('ExamPdfExportService: 渲染HTML为空', ['paper_id' => $paperId]);
  281. return null;
  282. }
  283. // 生成PDF
  284. $pdfBinary = $this->buildPdf($html);
  285. if (! $pdfBinary) {
  286. return null;
  287. }
  288. // 保存PDF(命名统一:姓名_分析报告_卷子id_卷子类型_时间戳)
  289. $studentName = (string) ($templateData['student']['name'] ?? $studentId);
  290. $paperCode = PaperNaming::extractExamCode((string) ($templateData['paper']['id'] ?? $paperId));
  291. $assembleTypeLabel = (string) ($templateData['paper']['assemble_type_label'] ?? '未知类型');
  292. $stamp = now()->format('YmdHis') . strtoupper(Str::random(4));
  293. $analysisBase = "{$studentName}_分析报告_{$paperCode}_{$assembleTypeLabel}_{$stamp}";
  294. $safeAnalysisFile = PaperNaming::toSafeFilename($analysisBase) . '.pdf';
  295. $path = "analysis_reports/{$safeAnalysisFile}";
  296. $url = $this->pdfStorageService->put($path, $pdfBinary);
  297. if (! $url) {
  298. Log::error('ExamPdfExportService: 保存学情PDF失败', ['path' => $path]);
  299. return null;
  300. }
  301. // 保存URL到数据库
  302. $this->saveAnalysisPdfUrl($paperId, $studentId, $recordId, $url);
  303. return $url;
  304. } catch (\Throwable $e) {
  305. Log::error('ExamPdfExportService: 生成学情分析PDF失败', [
  306. 'paper_id' => $paperId,
  307. 'student_id' => $studentId,
  308. 'record_id' => $recordId,
  309. 'error' => $e->getMessage(),
  310. 'exception' => get_class($e),
  311. 'trace' => $e->getTraceAsString(),
  312. ]);
  313. return null;
  314. }
  315. }
  316. /**
  317. * 生成合并PDF(试卷 + 判卷)
  318. * 先分别生成两个PDF,然后合并
  319. */
  320. public function generateMergedPdf(string $paperId): ?string
  321. {
  322. Log::info('generateMergedPdf 开始:', ['paper_id' => $paperId]);
  323. $tempDir = storage_path('app/temp');
  324. if (! is_dir($tempDir)) {
  325. mkdir($tempDir, 0755, true);
  326. }
  327. $examPdfPath = null;
  328. $gradingPdfPath = null;
  329. $mergedPdfPath = null;
  330. try {
  331. // 先生成试卷PDF
  332. $examPdfUrl = $this->generateExamPdf($paperId);
  333. if (! $examPdfUrl) {
  334. Log::error('ExamPdfExportService: 生成试卷PDF失败', ['paper_id' => $paperId]);
  335. return null;
  336. }
  337. // 再生成判卷PDF
  338. $gradingPdfUrl = $this->generateGradingPdf($paperId);
  339. if (! $gradingPdfUrl) {
  340. Log::error('ExamPdfExportService: 生成判卷PDF失败', ['paper_id' => $paperId]);
  341. return null;
  342. }
  343. // 【修复】下载PDF文件到本地临时目录
  344. Log::info('开始下载PDF文件到本地', [
  345. 'exam_url' => $examPdfUrl,
  346. 'grading_url' => $gradingPdfUrl,
  347. ]);
  348. $examPdfPath = $tempDir."/{$paperId}_exam.pdf";
  349. $gradingPdfPath = $tempDir."/{$paperId}_grading.pdf";
  350. // 下载试卷PDF
  351. $examContent = Http::get($examPdfUrl)->body();
  352. if (empty($examContent)) {
  353. Log::error('ExamPdfExportService: 下载试卷PDF失败', ['url' => $examPdfUrl]);
  354. return null;
  355. }
  356. file_put_contents($examPdfPath, $examContent);
  357. // 下载判卷PDF
  358. $gradingContent = Http::get($gradingPdfUrl)->body();
  359. if (empty($gradingContent)) {
  360. Log::error('ExamPdfExportService: 下载判卷PDF失败', ['url' => $gradingPdfUrl]);
  361. return null;
  362. }
  363. file_put_contents($gradingPdfPath, $gradingContent);
  364. Log::info('PDF文件下载完成', [
  365. 'exam_size' => filesize($examPdfPath),
  366. 'grading_size' => filesize($gradingPdfPath),
  367. ]);
  368. // 合并PDF文件
  369. $mergedPdfPath = $tempDir."/{$paperId}_merged.pdf";
  370. $merged = $this->pdfMerger->merge([$examPdfPath, $gradingPdfPath], $mergedPdfPath);
  371. if (! $merged) {
  372. Log::error('ExamPdfExportService: PDF文件合并失败', [
  373. 'tool' => $this->pdfMerger->getMergeTool(),
  374. ]);
  375. return null;
  376. }
  377. // 读取合并后的PDF内容并上传到云存储
  378. $mergedPdfContent = file_get_contents($mergedPdfPath);
  379. $paper = Paper::where('paper_id', $paperId)->first();
  380. if (! $paper) {
  381. Log::error('ExamPdfExportService: 合并PDF失败,未找到试卷', ['paper_id' => $paperId]);
  382. return null;
  383. }
  384. $allPdfName = $this->buildPdfFileName($paper);
  385. $path = "exams/{$allPdfName}";
  386. $mergedUrl = $this->pdfStorageService->put($path, $mergedPdfContent);
  387. if (! $mergedUrl) {
  388. Log::error('ExamPdfExportService: 保存合并PDF失败', ['path' => $path]);
  389. return null;
  390. }
  391. // 保存到数据库的all_pdf_url字段
  392. $this->saveAllPdfUrlToDatabase($paperId, $mergedUrl);
  393. Log::info('generateMergedPdf 完成:', [
  394. 'paper_id' => $paperId,
  395. 'url' => $mergedUrl,
  396. 'tool' => $this->pdfMerger->getMergeTool(),
  397. ]);
  398. return $mergedUrl;
  399. } catch (\Throwable $e) {
  400. Log::error('ExamPdfExportService: 生成合并PDF失败', [
  401. 'paper_id' => $paperId,
  402. 'error' => $e->getMessage(),
  403. 'trace' => $e->getTraceAsString(),
  404. ]);
  405. return null;
  406. } finally {
  407. // 【修复】清理临时文件
  408. $tempFiles = [$examPdfPath, $gradingPdfPath, $mergedPdfPath];
  409. foreach ($tempFiles as $file) {
  410. if ($file && file_exists($file)) {
  411. @unlink($file);
  412. }
  413. }
  414. Log::debug('清理临时文件完成');
  415. }
  416. }
  417. /**
  418. * 将URL转换为本地文件路径
  419. */
  420. private function convertUrlToPath(string $url): ?string
  421. {
  422. // 如果是本地存储,URL格式类似:/storage/exams/paper_id_exam.pdf
  423. // 需要转换为绝对路径
  424. if (strpos($url, '/storage/') === 0) {
  425. return public_path(ltrim($url, '/'));
  426. }
  427. // 如果是完整路径,直接返回
  428. if (strpos($url, '/') === 0 && file_exists($url)) {
  429. return $url;
  430. }
  431. // 如果是相对路径,转换为绝对路径
  432. $path = public_path($url);
  433. if (file_exists($path)) {
  434. return $path;
  435. }
  436. return null;
  437. }
  438. /**
  439. * 【新增】获取知识点讲解HTML
  440. */
  441. private function fetchKnowledgeExplanationHtml(string $paperId): ?string
  442. {
  443. try {
  444. $url = route('filament.admin.auth.intelligent-exam.knowledge-explanation', ['paper_id' => $paperId]);
  445. $response = Http::get($url);
  446. if ($response->successful()) {
  447. $html = $response->body();
  448. if (! empty(trim($html))) {
  449. Log::info('ExamPdfExportService: 成功获取知识点讲解HTML', [
  450. 'paper_id' => $paperId,
  451. 'length' => strlen($html),
  452. ]);
  453. $html = $this->ensureUtf8Html($html);
  454. $html = $this->renderKpExplainMarkdown($html);
  455. return $html;
  456. }
  457. }
  458. Log::warning('ExamPdfExportService: 获取知识点讲解HTML失败', [
  459. 'paper_id' => $paperId,
  460. 'url' => $url,
  461. ]);
  462. return null;
  463. } catch (\Exception $e) {
  464. Log::warning('ExamPdfExportService: 获取知识点讲解HTML异常', [
  465. 'paper_id' => $paperId,
  466. 'error' => $e->getMessage(),
  467. ]);
  468. return null;
  469. }
  470. }
  471. private function renderKpExplainMarkdown(string $html): string
  472. {
  473. if (! class_exists(\Michelf\MarkdownExtra::class)) {
  474. return $html;
  475. }
  476. $parser = new \Michelf\MarkdownExtra;
  477. return preg_replace_callback(
  478. '/<div class="kp-markdown-source"[^>]*>([\s\S]*?)<\/div>\s*<div class="kp-markdown-container[^"]*"[^>]*><\/div>/i',
  479. function ($matches) use ($parser) {
  480. $markdown = html_entity_decode(trim($matches[1]), ENT_QUOTES, 'UTF-8');
  481. $rendered = $parser->transform($markdown);
  482. return '<div class="kp-markdown-container kp-markdown-content">'.$rendered.'</div>';
  483. },
  484. $html
  485. );
  486. }
  487. /**
  488. * 【新增】渲染试卷HTML(通过HTTP调用路由)
  489. */
  490. private function renderExamHtml(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
  491. {
  492. // 判卷部分启用答案详情页时,优先本地渲染,避免跨进程配置不一致。
  493. if ($useGradingView && config('exam.pdf_grading_append_scan_sheet', false)) {
  494. return $this->renderExamHtmlFromView($paperId, $includeAnswer, $useGradingView);
  495. }
  496. try {
  497. // 通过HTTP客户端获取渲染后的HTML(与知识点讲解相同的逻辑)
  498. $routeName = $useGradingView
  499. ? 'filament.admin.auth.intelligent-exam.grading'
  500. : 'filament.admin.auth.intelligent-exam.pdf';
  501. $url = route($routeName, ['paper_id' => $paperId, 'answer' => $includeAnswer ? 'true' : 'false']);
  502. $response = Http::get($url);
  503. if ($response->successful()) {
  504. $html = $response->body();
  505. if (! empty(trim($html))) {
  506. return $this->ensureUtf8Html($html);
  507. }
  508. }
  509. Log::warning('ExamPdfExportService: 通过HTTP获取试卷HTML失败,使用备用方案', [
  510. 'paper_id' => $paperId,
  511. 'url' => $url,
  512. ]);
  513. } catch (\Exception $e) {
  514. Log::warning('ExamPdfExportService: 通过HTTP获取试卷HTML异常', [
  515. 'paper_id' => $paperId,
  516. 'error' => $e->getMessage(),
  517. ]);
  518. }
  519. // 备用方案:直接渲染视图
  520. return $this->renderExamHtmlFromView($paperId, $includeAnswer, $useGradingView);
  521. }
  522. /**
  523. * 备用方案:直接渲染视图生成试卷HTML
  524. */
  525. private function renderExamHtmlFromView(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
  526. {
  527. try {
  528. $paper = Paper::with('questions')->find($paperId);
  529. if (! $paper) {
  530. Log::error('ExamPdfExportService: 试卷不存在', ['paper_id' => $paperId]);
  531. return null;
  532. }
  533. if ($paper->questions->isEmpty()) {
  534. Log::error('ExamPdfExportService: 试卷没有题目数据', [
  535. 'paper_id' => $paperId,
  536. 'question_count' => 0,
  537. ]);
  538. return null;
  539. }
  540. $viewName = $this->resolveExamViewName($useGradingView);
  541. // 构造视图需要的变量
  542. $questions = ['choice' => [], 'fill' => [], 'answer' => []];
  543. foreach ($paper->questions as $pq) {
  544. $qType = $this->normalizeQuestionType($pq->question_type ?? 'answer');
  545. $questions[$qType][] = $this->normalizeAnswerFieldForPdf($pq);
  546. }
  547. $studentModel = \App\Models\Student::find($paper->student_id);
  548. $teacherModel = \App\Models\Teacher::find($paper->teacher_id);
  549. if (! $teacherModel && ! empty($paper->teacher_id)) {
  550. $teacherModel = \App\Models\Teacher::query()
  551. ->where('teacher_id', $paper->teacher_id)
  552. ->first();
  553. }
  554. $student = ['name' => $studentModel->name ?? ($paper->student_id ?? '________'), 'grade' => $studentModel->grade ?? '________'];
  555. $teacher = ['name' => $teacherModel->name ?? ($paper->teacher_id ?? '________')];
  556. $examCode = PaperNaming::extractExamCode((string) $paper->paper_id);
  557. try {
  558. $assembleTypeLabel = PaperNaming::assembleTypeLabel((int) $paper->paper_type);
  559. } catch (\Throwable $e) {
  560. $assembleTypeLabel = '未知类型';
  561. }
  562. $pdfMeta = [
  563. 'student_name' => $student['name'],
  564. 'exam_code' => $examCode,
  565. 'assemble_type_label' => $assembleTypeLabel,
  566. 'header_title' => $examCode,
  567. 'exam_pdf_title' => '试卷_'.$examCode,
  568. 'grading_pdf_title' => '判卷_'.$examCode,
  569. 'knowledge_pdf_title' => '知识点梳理_'.$examCode,
  570. ];
  571. $html = view($viewName, [
  572. 'paper' => $paper,
  573. 'questions' => $questions,
  574. 'includeAnswer' => $includeAnswer,
  575. 'student' => $student,
  576. 'teacher' => $teacher,
  577. 'pdfMeta' => $pdfMeta,
  578. ])->render();
  579. if (empty(trim($html))) {
  580. Log::error('ExamPdfExportService: 视图渲染结果为空', [
  581. 'paper_id' => $paperId,
  582. 'view_name' => $viewName,
  583. 'question_count' => $paper->questions->count(),
  584. ]);
  585. return null;
  586. }
  587. return $this->ensureUtf8Html($html);
  588. } catch (\Exception $e) {
  589. Log::error('ExamPdfExportService: 备用方案渲染失败', [
  590. 'paper_id' => $paperId,
  591. 'error' => $e->getMessage(),
  592. 'trace' => $e->getTraceAsString(),
  593. ]);
  594. return null;
  595. }
  596. }
  597. /**
  598. * 构建分析数据(重构版)
  599. * 优先使用本地MySQL数据,减少API依赖
  600. */
  601. private function buildAnalysisData(string $paperId, string $studentId): ?array
  602. {
  603. // 【关键调试】确认方法被调用
  604. Log::warning('ExamPdfExportService: buildAnalysisData方法被调用了!', [
  605. 'paper_id' => $paperId,
  606. 'student_id' => $studentId,
  607. 'timestamp' => now()->toISOString(),
  608. ]);
  609. $paper = Paper::with(['questions' => function ($query) {
  610. $query->orderBy('question_number')->orderBy('id');
  611. }])->find($paperId);
  612. if (! $paper) {
  613. Log::warning('ExamPdfExportService: 未找到试卷,将尝试仅基于分析数据生成PDF', [
  614. 'paper_id' => $paperId,
  615. 'student_id' => $studentId,
  616. ]);
  617. // 【修复】即使试卷不存在,也尝试基于分析数据生成PDF
  618. $paper = new \stdClass;
  619. $paper->paper_id = $paperId;
  620. $paper->paper_name = "学情分析报告_{$studentId}_{$paperId}";
  621. $paper->question_count = 0;
  622. $paper->total_score = 0;
  623. $paper->created_at = now();
  624. $paper->questions = collect();
  625. }
  626. $student = Student::find($studentId);
  627. $studentInfo = [
  628. 'id' => $student?->student_id ?? $studentId,
  629. 'name' => $student?->name ?? $studentId,
  630. 'grade' => $student?->grade ?? '未知年级',
  631. 'class' => $student?->class_name ?? '未知班级',
  632. ];
  633. $teacherInfo = $this->getTeacherInfo((string) ($paper->teacher_id ?? ''));
  634. $assembleType = ($paper->paper_type === null || $paper->paper_type === '')
  635. ? null
  636. : (int) $paper->paper_type;
  637. try {
  638. $assembleTypeLabel = $assembleType !== null ? PaperNaming::assembleTypeLabel($assembleType) : '未知类型';
  639. } catch (\Throwable $e) {
  640. $assembleTypeLabel = '未知类型';
  641. }
  642. // 【修改】直接从本地数据库获取分析数据(不再调用API)
  643. $analysisData = [];
  644. // 首先尝试从paper->analysis_id获取
  645. if (! empty($paper->analysis_id)) {
  646. Log::info('ExamPdfExportService: 从本地数据库获取试卷分析数据', [
  647. 'paper_id' => $paperId,
  648. 'student_id' => $studentId,
  649. 'analysis_id' => $paper->analysis_id,
  650. ]);
  651. $analysisRecord = \DB::table('exam_analysis_results')
  652. ->where('id', $paper->analysis_id)
  653. ->where('student_id', $studentId)
  654. ->first();
  655. if ($analysisRecord && ! empty($analysisRecord->analysis_data)) {
  656. $analysisData = json_decode($analysisRecord->analysis_data, true);
  657. Log::info('ExamPdfExportService: 成功获取本地分析数据(通过analysis_id)', [
  658. 'data_size' => strlen($analysisRecord->analysis_data),
  659. ]);
  660. } else {
  661. Log::warning('ExamPdfExportService: 未找到本地分析数据,将尝试其他方式', [
  662. 'paper_id' => $paperId,
  663. 'student_id' => $studentId,
  664. 'analysis_id' => $paper->analysis_id,
  665. ]);
  666. }
  667. }
  668. // 如果没有analysis_id或未找到数据,直接从exam_analysis_results表查询
  669. if (empty($analysisData)) {
  670. Log::info('ExamPdfExportService: 直接从exam_analysis_results表查询分析数据', [
  671. 'paper_id' => $paperId,
  672. 'student_id' => $studentId,
  673. ]);
  674. $analysisRecord = \DB::table('exam_analysis_results')
  675. ->where('paper_id', $paperId)
  676. ->where('student_id', $studentId)
  677. ->orderByDesc('created_at')
  678. ->first();
  679. if ($analysisRecord && ! empty($analysisRecord->analysis_data)) {
  680. $analysisData = json_decode($analysisRecord->analysis_data, true);
  681. Log::info('ExamPdfExportService: 成功获取本地分析数据(直接查询)', [
  682. 'data_size' => strlen($analysisRecord->analysis_data),
  683. 'question_count' => count($analysisData['question_analysis'] ?? []),
  684. ]);
  685. } else {
  686. Log::warning('ExamPdfExportService: 未找到任何分析数据,将使用空数据', [
  687. 'paper_id' => $paperId,
  688. 'student_id' => $studentId,
  689. ]);
  690. }
  691. }
  692. // 【修复】优先使用analysisData中的knowledge_point_analysis数据
  693. $masteryData = [];
  694. $parentMasteryLevels = []; // 新增:父节点掌握度数据
  695. Log::info('ExamPdfExportService: 开始处理掌握度数据', [
  696. 'student_id' => $studentId,
  697. 'analysisData_keys' => array_keys($analysisData),
  698. 'has_knowledge_point_analysis' => ! empty($analysisData['knowledge_point_analysis']),
  699. ]);
  700. $fullMasteryMap = [];
  701. $snapshotMasteryData = [];
  702. if (! empty($analysisData['knowledge_point_analysis'])) {
  703. // 将knowledge_point_analysis转换为buildMasterySummary期望的格式
  704. foreach ($analysisData['knowledge_point_analysis'] as $kp) {
  705. $masteryData[] = [
  706. 'kp_code' => $kp['kp_id'] ?? null,
  707. 'kp_name' => $kp['kp_id'] ?? '未知知识点',
  708. 'mastery_level' => $kp['mastery_level'] ?? 0,
  709. 'mastery_change' => $kp['change'] ?? null,
  710. ];
  711. }
  712. // 【修复】基于所有兄弟节点历史数据计算父节点掌握度,并获取掌握度变化
  713. try {
  714. // 获取本次考试涉及的知识点代码列表
  715. $examKpCodes = array_column($masteryData, 'kp_code');
  716. Log::info('ExamPdfExportService: 本次考试涉及的知识点', [
  717. 'count' => count($examKpCodes),
  718. 'kp_codes' => $examKpCodes,
  719. ]);
  720. // 获取最新快照的数据(mastery_data 内已包含 current_mastery 和 previous_mastery)
  721. $lastSnapshot = DB::connection('mysql')
  722. ->table('knowledge_point_mastery_snapshots')
  723. ->where('student_id', $studentId)
  724. ->where('paper_id', $paper->paper_id)
  725. ->latest('snapshot_time')
  726. ->first();
  727. $previousMasteryData = [];
  728. $snapshotMasteryData = [];
  729. if ($lastSnapshot) {
  730. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  731. foreach ($previousMasteryJson as $kpCode => $data) {
  732. $snapshotMasteryData[$kpCode] = [
  733. 'current_mastery' => isset($data['current_mastery']) ? floatval($data['current_mastery']) : null,
  734. 'previous_mastery' => isset($data['previous_mastery']) ? floatval($data['previous_mastery']) : null,
  735. 'change' => isset($data['change']) ? floatval($data['change']) : null,
  736. ];
  737. $previousMasteryData[$kpCode] = [
  738. 'current_mastery' => $data['current_mastery'] ?? 0,
  739. 'previous_mastery' => $data['previous_mastery'] ?? null,
  740. ];
  741. }
  742. Log::info('ExamPdfExportService: 获取到上一次快照数据', [
  743. 'snapshot_time' => $lastSnapshot->snapshot_time,
  744. 'kp_count' => count($previousMasteryData),
  745. ]);
  746. }
  747. // 为当前知识点添加变化数据
  748. foreach ($masteryData as &$item) {
  749. $kpCode = $item['kp_code'];
  750. if (isset($previousMasteryData[$kpCode]) && $previousMasteryData[$kpCode]['previous_mastery'] !== null) {
  751. $previous = floatval($previousMasteryData[$kpCode]['previous_mastery']);
  752. $current = floatval($item['mastery_level']);
  753. $item['mastery_change'] = $current - $previous;
  754. }
  755. }
  756. unset($item); // 解除引用
  757. // 获取所有父节点掌握度
  758. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  759. $allParentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? [];
  760. $overviewDetails = $masteryOverview['details'] ?? [];
  761. foreach ($overviewDetails as $detail) {
  762. if (is_object($detail)) {
  763. $code = $detail->kp_code ?? null;
  764. if ($code) {
  765. $fullMasteryMap[$code] = floatval($detail->mastery_level ?? 0);
  766. }
  767. } elseif (is_array($detail)) {
  768. $code = $detail['kp_code'] ?? null;
  769. if ($code) {
  770. $fullMasteryMap[$code] = floatval($detail['mastery_level'] ?? 0);
  771. }
  772. }
  773. }
  774. // 计算与本次考试相关的父节点掌握度(基于所有兄弟节点)
  775. $parentMasteryLevels = [];
  776. // 【修复】使用数据库查询正确匹配父子关系,而不是字符串前缀
  777. foreach ($allParentMasteryLevels as $parentKpCode => $parentMastery) {
  778. // 查询这个父节点的所有子节点
  779. $childNodes = DB::connection('mysql')
  780. ->table('knowledge_points')
  781. ->where('parent_kp_code', $parentKpCode)
  782. ->pluck('kp_code')
  783. ->toArray();
  784. // 检查是否有子节点在本次考试中出现
  785. $relevantChildren = array_intersect($examKpCodes, $childNodes);
  786. if (! empty($relevantChildren)) {
  787. // 口径统一:父节点掌握度 = 全部直接子节点(含未命中,缺失按0)均值
  788. $childCurrentLevels = [];
  789. $childPreviousLevels = [];
  790. foreach ($childNodes as $childKpCode) {
  791. $currentChild = floatval($fullMasteryMap[$childKpCode] ?? 0);
  792. $childCurrentLevels[] = $currentChild;
  793. $prevFromSnapshot = $snapshotMasteryData[$childKpCode]['previous_mastery'] ?? null;
  794. $currFromSnapshot = $snapshotMasteryData[$childKpCode]['current_mastery'] ?? null;
  795. $previousChild = $prevFromSnapshot ?? $currFromSnapshot ?? $currentChild;
  796. $childPreviousLevels[] = floatval($previousChild);
  797. }
  798. $finalParentMastery = ! empty($childCurrentLevels)
  799. ? array_sum($childCurrentLevels) / count($childCurrentLevels)
  800. : floatval($parentMastery);
  801. $previousParentMastery = ! empty($childPreviousLevels)
  802. ? array_sum($childPreviousLevels) / count($childPreviousLevels)
  803. : $finalParentMastery;
  804. $finalParentChange = $finalParentMastery - $previousParentMastery;
  805. // 获取父节点中文名称
  806. $parentKpInfo = DB::connection('mysql')
  807. ->table('knowledge_points')
  808. ->where('kp_code', $parentKpCode)
  809. ->first();
  810. $parentMasteryLevels[$parentKpCode] = [
  811. 'kp_code' => $parentKpCode,
  812. 'kp_name' => $parentKpInfo->name ?? $parentKpCode,
  813. 'mastery_level' => $finalParentMastery,
  814. 'mastery_percentage' => round($finalParentMastery * 100, 1),
  815. 'mastery_change' => $finalParentChange,
  816. 'change_source' => 'children_all_average',
  817. 'children' => $relevantChildren,
  818. ];
  819. }
  820. }
  821. Log::info('ExamPdfExportService: 过滤后的父节点掌握度', [
  822. 'all_parent_count' => count($allParentMasteryLevels),
  823. 'filtered_parent_count' => count($parentMasteryLevels),
  824. 'filtered_codes' => array_keys($parentMasteryLevels),
  825. ]);
  826. } catch (\Exception $e) {
  827. Log::warning('ExamPdfExportService: 获取父节点掌握度失败', [
  828. 'error' => $e->getMessage(),
  829. ]);
  830. }
  831. Log::info('ExamPdfExportService: 使用analysisData中的掌握度数据', [
  832. 'count' => count($masteryData),
  833. 'masteryData_sample' => ! empty($masteryData) ? array_slice($masteryData, 0, 2) : [],
  834. ]);
  835. } else {
  836. // 如果没有knowledge_point_analysis,使用MasteryCalculator获取多层级掌握度概览
  837. try {
  838. Log::info('ExamPdfExportService: 获取学生多层级掌握度概览', [
  839. 'student_id' => $studentId,
  840. ]);
  841. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  842. $masteryData = $masteryOverview['details'] ?? [];
  843. $parentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? []; // 获取父节点掌握度
  844. // 【修复】将对象数组转换为关联数组(避免 stdClass 对象访问错误)
  845. if (! empty($masteryData) && is_array($masteryData)) {
  846. $masteryData = array_map(function ($item) {
  847. if (is_object($item)) {
  848. $kpCode = $item->kp_code ?? null;
  849. return [
  850. 'kp_code' => $kpCode,
  851. 'kp_name' => $item->kp_name ?? null,
  852. 'mastery_level' => floatval($item->mastery_level ?? 0),
  853. 'mastery_change' => $item->mastery_change !== null ? floatval($item->mastery_change) : null,
  854. ];
  855. }
  856. return $item;
  857. }, $masteryData);
  858. }
  859. foreach ($masteryData as $m) {
  860. $code = $m['kp_code'] ?? null;
  861. if ($code) {
  862. $fullMasteryMap[$code] = floatval($m['mastery_level'] ?? 0);
  863. }
  864. }
  865. // 【修复】获取快照数据以计算掌握度变化
  866. $lastSnapshot = DB::connection('mysql')
  867. ->table('knowledge_point_mastery_snapshots')
  868. ->where('student_id', $studentId)
  869. ->latest('snapshot_time')
  870. ->first();
  871. if ($lastSnapshot) {
  872. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  873. foreach ($masteryData as &$item) {
  874. $kpCode = $item['kp_code'];
  875. if (isset($previousMasteryJson[$kpCode])) {
  876. $previous = floatval($previousMasteryJson[$kpCode]['previous_mastery'] ?? 0);
  877. $current = floatval($item['mastery_level']);
  878. $item['mastery_change'] = $current - $previous;
  879. }
  880. }
  881. unset($item);
  882. }
  883. Log::info('ExamPdfExportService: 成功获取多层级掌握度数据', [
  884. 'count' => count($masteryData),
  885. 'parent_count' => count($parentMasteryLevels),
  886. ]);
  887. } catch (\Exception $e) {
  888. Log::error('ExamPdfExportService: 获取掌握度数据失败', [
  889. 'student_id' => $studentId,
  890. 'error' => $e->getMessage(),
  891. ]);
  892. }
  893. }
  894. // 【修改】使用本地方法获取学习路径推荐(替代API调用)
  895. $recommendations = [];
  896. try {
  897. Log::info('ExamPdfExportService: 获取学习路径推荐', [
  898. 'student_id' => $studentId,
  899. ]);
  900. $learningPaths = $this->learningAnalyticsService->recommendLearningPaths($studentId, 3);
  901. $recommendations = $learningPaths['recommendations'] ?? [];
  902. Log::info('ExamPdfExportService: 成功获取学习路径推荐', [
  903. 'count' => count($recommendations),
  904. ]);
  905. } catch (\Exception $e) {
  906. Log::error('ExamPdfExportService: 获取学习路径推荐失败', [
  907. 'student_id' => $studentId,
  908. 'error' => $e->getMessage(),
  909. ]);
  910. }
  911. // 获取知识点名称映射
  912. $kpNameMap = $this->buildKnowledgePointNameMap();
  913. Log::info('ExamPdfExportService: 获取知识点名称映射', [
  914. 'kpNameMap_count' => count($kpNameMap),
  915. 'kpNameMap_keys_sample' => ! empty($kpNameMap) ? array_slice(array_keys($kpNameMap), 0, 5) : [],
  916. ]);
  917. // 【修复】直接从MySQL数据库获取题目详情(不通过API)
  918. // 只有当 $paper 是 Paper 模型时才查询题目详情
  919. $questionDetails = ($paper instanceof \App\Models\Paper)
  920. ? $this->getQuestionDetailsFromMySQL($paper)
  921. : [];
  922. // 处理题目数据
  923. $questions = $this->processQuestionsForReport($paper, $questionDetails, $kpNameMap);
  924. // 【关键调试】查看buildMasterySummary的返回结果
  925. $masterySummary = $this->buildMasterySummary($masteryData, $kpNameMap);
  926. Log::info('ExamPdfExportService: buildMasterySummary返回结果', [
  927. 'masteryData_count' => count($masteryData),
  928. 'kpNameMap_count' => count($kpNameMap),
  929. 'masterySummary_keys' => array_keys($masterySummary),
  930. 'masterySummary_items_count' => count($masterySummary['items'] ?? []),
  931. 'masterySummary_items_sample' => ! empty($masterySummary['items']) ? array_slice($masterySummary['items'], 0, 2) : [],
  932. ]);
  933. // 构建当前学生掌握度映射,供父子影响分析展示使用
  934. $masteryMap = !empty($fullMasteryMap) ? $fullMasteryMap : [];
  935. if (empty($masteryMap)) {
  936. foreach ($masteryData as $m) {
  937. $code = $m['kp_code'] ?? null;
  938. if ($code) {
  939. $masteryMap[$code] = floatval($m['mastery_level'] ?? 0);
  940. }
  941. }
  942. }
  943. // 本卷命中知识点:严格按“这套卷子题目关联知识点”计算
  944. $examQuestionKpCodes = array_values(array_unique(array_filter(array_map(
  945. fn ($q) => trim((string) ($q['knowledge_point'] ?? '')),
  946. $questions
  947. ))));
  948. // 父节点列表:直接按“本卷命中子知识点”反查父节点,避免历史全集/补齐口径带偏
  949. $processedParentMastery = $this->buildParentMasteryFromHitCodes(
  950. $examQuestionKpCodes,
  951. $kpNameMap,
  952. $masteryMap,
  953. $snapshotMasteryData
  954. );
  955. Log::info('ExamPdfExportService: 处理后的父节点掌握度', [
  956. 'raw_count' => count($parentMasteryLevels),
  957. 'processed_count' => count($processedParentMastery),
  958. 'processed_sample' => ! empty($processedParentMastery) ? array_slice($processedParentMastery, 0, 3) : [],
  959. ]);
  960. return [
  961. 'paper' => [
  962. 'id' => $paper->paper_id,
  963. 'name' => $paper->paper_name,
  964. 'paper_type' => $paper->paper_type,
  965. 'assemble_type_label' => $assembleTypeLabel,
  966. 'total_questions' => $paper->question_count,
  967. 'total_score' => $paper->total_score,
  968. 'created_at' => $paper->created_at,
  969. ],
  970. 'student' => $studentInfo,
  971. 'teacher' => $teacherInfo,
  972. 'questions' => $questions,
  973. 'mastery' => $masterySummary,
  974. 'exam_hit_kp_codes' => $examQuestionKpCodes,
  975. 'parent_mastery_levels' => $processedParentMastery, // 【修复】使用处理后的父节点数据
  976. 'insights' => $analysisData['question_analysis'] ?? [], // 使用question_analysis替代question_results
  977. 'recommendations' => $recommendations,
  978. 'analysis_data' => $analysisData,
  979. ];
  980. }
  981. /**
  982. * 【修复】直接从PaperQuestion表获取题目详情(不通过API)
  983. */
  984. private function getQuestionDetailsFromMySQL(Paper $paper): array
  985. {
  986. $details = [];
  987. Log::info('ExamPdfExportService: 从PaperQuestion表查询题目详情', [
  988. 'paper_id' => $paper->paper_id,
  989. 'question_count' => $paper->questions->count(),
  990. ]);
  991. foreach ($paper->questions as $pq) {
  992. try {
  993. // 【关键修复】直接从PaperQuestion对象获取solution和correct_answer
  994. $detail = [
  995. 'id' => $pq->question_id,
  996. 'content' => $pq->question_text,
  997. 'question_type' => $pq->question_type,
  998. 'answer' => $pq->correct_answer ?? null, // 【修复】从PaperQuestion获取正确答案
  999. 'solution' => $pq->solution ?? null, // 【修复】从PaperQuestion获取解题思路
  1000. ];
  1001. $details[(string) ($pq->question_id ?? $pq->id)] = $detail;
  1002. Log::debug('ExamPdfExportService: 成功获取题目详情', [
  1003. 'paper_question_id' => $pq->id,
  1004. 'question_id' => $pq->question_id,
  1005. 'has_answer' => ! empty($pq->correct_answer),
  1006. 'has_solution' => ! empty($pq->solution),
  1007. 'answer_preview' => $pq->correct_answer ? substr($pq->correct_answer, 0, 50) : null,
  1008. ]);
  1009. } catch (\Throwable $e) {
  1010. Log::error('ExamPdfExportService: 获取题目详情失败', [
  1011. 'paper_question_id' => $pq->id,
  1012. 'error' => $e->getMessage(),
  1013. ]);
  1014. }
  1015. }
  1016. return $details;
  1017. }
  1018. /**
  1019. * 将题库 options 转为 [A=>文本, B=>文本, ...],供学情报告展示
  1020. *
  1021. * @param mixed $raw questions.options(JSON/数组)
  1022. * @return array<string, string>
  1023. */
  1024. private function normalizeChoiceOptionsMap($raw): array
  1025. {
  1026. if ($raw === null || $raw === '') {
  1027. return [];
  1028. }
  1029. if (is_string($raw)) {
  1030. $decoded = json_decode($raw, true);
  1031. $raw = is_array($decoded) ? $decoded : [];
  1032. }
  1033. if (! is_array($raw)) {
  1034. return [];
  1035. }
  1036. $out = [];
  1037. foreach ($raw as $k => $v) {
  1038. if (is_string($k) && preg_match('/([A-H])/i', $k, $m)) {
  1039. $letter = strtoupper($m[1]);
  1040. $text = is_array($v)
  1041. ? (string) ($v['content'] ?? $v['text'] ?? $v['value'] ?? '')
  1042. : (string) $v;
  1043. $text = trim($text);
  1044. if ($text !== '') {
  1045. $out[$letter] = $text;
  1046. }
  1047. }
  1048. }
  1049. if (! empty($out)) {
  1050. return $out;
  1051. }
  1052. $letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
  1053. $i = 0;
  1054. foreach ($raw as $v) {
  1055. if ($i >= count($letters)) {
  1056. break;
  1057. }
  1058. $text = is_array($v)
  1059. ? (string) ($v['content'] ?? $v['text'] ?? $v['value'] ?? '')
  1060. : (string) $v;
  1061. $text = trim($text);
  1062. if ($text !== '') {
  1063. $out[$letters[$i]] = $text;
  1064. }
  1065. $i++;
  1066. }
  1067. return $out;
  1068. }
  1069. /**
  1070. * 从题干 HTML 中解析选项(与 ExamPdfController::extractOptions 口径一致,输出为字母=>文本)
  1071. *
  1072. * @return array<string, string>
  1073. */
  1074. private function extractChoiceOptionsFromStem(string $content): array
  1075. {
  1076. $out = [];
  1077. $contentWithoutSvg = preg_replace('/<svg[^>]*>.*?<\/svg>/is', '[SVG_PLACEHOLDER]', $content);
  1078. $pattern = '/(?:^|\s)([A-H])[\.、:.:]\s*(.+?)(?=(?:^|\s)[A-H][\.、:.:]|$)/su';
  1079. if (preg_match_all($pattern, $contentWithoutSvg, $matches, PREG_SET_ORDER)) {
  1080. foreach ($matches as $match) {
  1081. $letter = strtoupper($match[1]);
  1082. $optionText = trim($match[2]);
  1083. $optionText = preg_replace('/\s+$/', '', $optionText);
  1084. $optionText = preg_replace('/^\$\$\s*/', '', $optionText);
  1085. $optionText = preg_replace('/\s*\$\$$/', '', $optionText);
  1086. if ($optionText !== '') {
  1087. $out[$letter] = $optionText;
  1088. }
  1089. }
  1090. }
  1091. if (empty($out)) {
  1092. $lines = preg_split('/[\r\n]+/', $contentWithoutSvg);
  1093. foreach ($lines as $line) {
  1094. $line = trim($line);
  1095. if (preg_match('/^([A-H])[\.、:.:]\s*(.+)$/u', $line, $match)) {
  1096. $letter = strtoupper($match[1]);
  1097. $optionText = trim($match[2]);
  1098. if ($optionText !== '') {
  1099. $out[$letter] = $optionText;
  1100. }
  1101. }
  1102. }
  1103. }
  1104. return $out;
  1105. }
  1106. /**
  1107. * 处理题目数据(用于报告)
  1108. */
  1109. private function processQuestionsForReport($paper, array $questionDetails, array $kpNameMap): array
  1110. {
  1111. $grouped = [
  1112. 'choice' => [],
  1113. 'fill' => [],
  1114. 'answer' => [],
  1115. ];
  1116. // 【修复】处理空的试卷(questions可能不存在)
  1117. $questions = $paper->questions ?? collect();
  1118. if ($questions->isEmpty()) {
  1119. Log::info('ExamPdfExportService: 试卷没有题目,返回空数组');
  1120. return $grouped;
  1121. }
  1122. $sortedQuestions = $questions
  1123. ->sortBy(function ($q, int $idx) {
  1124. $number = $q->question_number ?? $idx + 1;
  1125. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  1126. });
  1127. $bankIds = $sortedQuestions->pluck('question_bank_id')->filter()->unique()->values()->all();
  1128. $optionsByBankId = [];
  1129. if (! empty($bankIds)) {
  1130. $optionsByBankId = Question::whereIn('id', $bankIds)
  1131. ->pluck('options', 'id')
  1132. ->toArray();
  1133. }
  1134. foreach ($sortedQuestions as $idx => $question) {
  1135. $kpCode = $question->knowledge_point ?? '';
  1136. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  1137. // 【修复】直接从PaperQuestion对象获取solution和correct_answer
  1138. $answer = $question->correct_answer ?? null; // 直接从PaperQuestion获取
  1139. $solution = $question->solution ?? null; // 直接从PaperQuestion获取
  1140. $detail = $questionDetails[(string) ($question->question_id ?? $question->id)] ?? [];
  1141. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  1142. $normalizedType = $this->normalizeQuestionType($typeRaw);
  1143. $number = $question->question_number ?? ($idx + 1);
  1144. // 处理题干文本
  1145. $questionText = is_array($question->question_text)
  1146. ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
  1147. : ($question->question_text ?? '');
  1148. $optionsFromBank = $question->question_bank_id
  1149. ? ($optionsByBankId[$question->question_bank_id] ?? null)
  1150. : null;
  1151. $choiceOptionsMap = $this->normalizeChoiceOptionsMap($optionsFromBank);
  1152. if (empty($choiceOptionsMap) && $normalizedType === 'choice') {
  1153. $choiceOptionsMap = $this->extractChoiceOptionsFromStem((string) $questionText);
  1154. }
  1155. $questionTextForPayload = $this->formatNewlines($questionText);
  1156. $questionTextPreprocessed = false;
  1157. if ($normalizedType === 'choice') {
  1158. $questionTextForPayload = GradingStyleQuestionStem::buildChoiceStemForReport(
  1159. (string) $questionTextForPayload
  1160. );
  1161. $questionTextPreprocessed = true;
  1162. }
  1163. $payload = [
  1164. 'question_id' => $question->question_id ?? null,
  1165. 'question_bank_id' => $question->question_bank_id ?? $question->question_id ?? null,
  1166. 'question_number' => $number,
  1167. 'question_text' => $questionTextForPayload,
  1168. 'question_text_preprocessed' => $questionTextPreprocessed,
  1169. 'question_type' => $normalizedType,
  1170. 'knowledge_point' => $kpCode,
  1171. 'knowledge_point_name' => $kpName,
  1172. 'score' => $question->score,
  1173. 'answer' => $this->formatNewlines($answer), // 格式化换行
  1174. 'solution' => $this->formatNewlines($solution), // 格式化换行
  1175. 'student_answer' => $this->formatNewlines($question->student_answer ?? null), // 格式化换行
  1176. 'correct_answer' => $this->formatNewlines($answer), // 格式化换行
  1177. 'is_correct' => $question->is_correct ?? null,
  1178. 'score_obtained' => $question->score_obtained ?? null,
  1179. 'options' => $choiceOptionsMap,
  1180. ];
  1181. $grouped[$normalizedType][] = $payload;
  1182. // 【调试】记录题目数据
  1183. Log::debug('ExamPdfExportService: 处理题目数据', [
  1184. 'paper_question_id' => $question->id,
  1185. 'question_id' => $question->question_id,
  1186. 'has_answer' => ! empty($answer),
  1187. 'has_solution' => ! empty($solution),
  1188. 'answer_preview' => $answer ? substr($answer, 0, 50) : null,
  1189. ]);
  1190. }
  1191. $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  1192. // 按卷面顺序重新编号
  1193. foreach ($ordered as $i => &$q) {
  1194. $q['display_number'] = $i + 1;
  1195. }
  1196. unset($q);
  1197. return $ordered;
  1198. }
  1199. /**
  1200. * 构建PDF
  1201. */
  1202. private function buildPdf(string $html, bool $applyWideImageSizing = false, bool $scopeToExamPart = false): ?string
  1203. {
  1204. $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_').'.html';
  1205. $utf8Html = $this->ensureUtf8Html($html);
  1206. if ($applyWideImageSizing) {
  1207. $utf8Html = $scopeToExamPart
  1208. ? $this->applyAdaptiveWideImageSizingToExamPart($utf8Html)
  1209. : $this->applyAdaptiveWideImageSizing($utf8Html);
  1210. }
  1211. $written = file_put_contents($tmpHtml, $utf8Html);
  1212. Log::debug('ExamPdfExportService: HTML文件已创建', [
  1213. 'path' => $tmpHtml,
  1214. 'html_length' => strlen($utf8Html),
  1215. 'written_bytes' => $written,
  1216. ]);
  1217. // 【调试】如果启用了HTML保存调试,复制HTML到storage用于分析
  1218. if (config('pdf.debug_save_html', false)) {
  1219. $debugPath = storage_path('app/debug_pdf_'.date('YmdHis').'.html');
  1220. @copy($tmpHtml, $debugPath);
  1221. Log::warning('ExamPdfExportService: [DEBUG] HTML副本已保存', ['path' => $debugPath]);
  1222. }
  1223. // 仅使用Chrome渲染
  1224. $chromePdf = $this->renderWithChrome($tmpHtml);
  1225. @unlink($tmpHtml);
  1226. return $chromePdf;
  1227. }
  1228. /**
  1229. * 对扁长/超扁长图片做全局自适应放大,普通图片不处理。
  1230. */
  1231. private function applyAdaptiveWideImageSizing(string $html): string
  1232. {
  1233. return (string) preg_replace_callback(
  1234. '/<img\b[^>]*\bsrc=(["\'])([^"\']+)\1[^>]*>/i',
  1235. function (array $m): string {
  1236. $fullTag = $m[0] ?? '';
  1237. $src = $m[2] ?? '';
  1238. if ($fullTag === '' || $src === '' || str_starts_with($src, 'data:')) {
  1239. return $fullTag;
  1240. }
  1241. if (! $this->shouldApplyAdaptiveSizingToSrc($src)) {
  1242. return $fullTag;
  1243. }
  1244. $dim = $this->getPdfImageDimensions($src);
  1245. if (! $dim || ($dim['w'] ?? 0) <= 0 || ($dim['h'] ?? 0) <= 0) {
  1246. return $fullTag;
  1247. }
  1248. $ratio = $dim['w'] / max(1, $dim['h']);
  1249. if ($ratio < 2.8) {
  1250. return $fullTag;
  1251. }
  1252. $targetWidth = $ratio >= 3.5 ? self::PDF_IMAGE_WIDTH_VERY_WIDE_PX : self::PDF_IMAGE_WIDTH_WIDE_PX;
  1253. $targetWidth = min($targetWidth, $dim['w']);
  1254. $targetStyle = sprintf(
  1255. 'width:%dpx!important;max-width:%dpx!important;max-height:60mm!important;height:auto!important;object-fit:contain!important;',
  1256. $targetWidth,
  1257. $targetWidth
  1258. );
  1259. if (preg_match('/\sstyle=(["\'])(.*?)\1/i', $fullTag, $sm)) {
  1260. $originStyle = $sm[2] ?? '';
  1261. $originStyle = preg_replace('/\bmax-width\s*:[^;]+;?/i', '', $originStyle);
  1262. $originStyle = preg_replace('/\bmax-height\s*:[^;]+;?/i', '', $originStyle);
  1263. $originStyle = preg_replace('/\bwidth\s*:[^;]+;?/i', '', $originStyle);
  1264. $originStyle = preg_replace('/\bheight\s*:[^;]+;?/i', '', $originStyle);
  1265. $originStyle = preg_replace('/\bobject-fit\s*:[^;]+;?/i', '', $originStyle);
  1266. $newStyle = $targetStyle.trim((string) $originStyle);
  1267. return preg_replace(
  1268. '/\sstyle=(["\'])(.*?)\1/i',
  1269. ' style="'.$newStyle.'"',
  1270. $fullTag,
  1271. 1
  1272. ) ?? $fullTag;
  1273. }
  1274. return preg_replace('/<img\b/i', '<img style="'.$targetStyle.'"', $fullTag, 1) ?? $fullTag;
  1275. },
  1276. $html
  1277. );
  1278. }
  1279. /**
  1280. * 仅在 unified HTML 的试卷容器中应用扁图策略,避免影响判卷/知识点讲解部分。
  1281. */
  1282. private function applyAdaptiveWideImageSizingToExamPart(string $html): string
  1283. {
  1284. $startMarker = '<!-- EXAM_PART_START -->';
  1285. $endMarker = '<!-- EXAM_PART_END -->';
  1286. $startPos = strpos($html, $startMarker);
  1287. $endPos = strpos($html, $endMarker);
  1288. if ($startPos === false || $endPos === false || $endPos <= $startPos) {
  1289. return $html;
  1290. }
  1291. $contentStart = $startPos + strlen($startMarker);
  1292. $examContent = substr($html, $contentStart, $endPos - $contentStart);
  1293. if ($examContent === false || $examContent === '') {
  1294. return $html;
  1295. }
  1296. $processedExamContent = $this->applyAdaptiveWideImageSizing($examContent);
  1297. return substr($html, 0, $contentStart).$processedExamContent.substr($html, $endPos);
  1298. }
  1299. /**
  1300. * @return array{w:int,h:int}|null
  1301. */
  1302. private function getPdfImageDimensions(string $src): ?array
  1303. {
  1304. if (array_key_exists($src, $this->pdfImageDimensionCache)) {
  1305. return $this->pdfImageDimensionCache[$src];
  1306. }
  1307. try {
  1308. $persisted = $this->getPersistedPdfImageMetrics($src);
  1309. if ($persisted !== null) {
  1310. $this->pdfImageDimensionCache[$src] = $persisted;
  1311. return $persisted;
  1312. }
  1313. if (! str_starts_with($src, 'http://') && ! str_starts_with($src, 'https://')) {
  1314. $this->pdfImageDimensionCache[$src] = null;
  1315. return null;
  1316. }
  1317. $size = @getimagesize($src);
  1318. if (is_array($size) && count($size) >= 2) {
  1319. $data = ['w' => (int) $size[0], 'h' => (int) $size[1]];
  1320. $this->persistPdfImageMetrics($src, $data);
  1321. $this->pdfImageDimensionCache[$src] = $data;
  1322. return $data;
  1323. }
  1324. $this->pdfImageDimensionCache[$src] = null;
  1325. return null;
  1326. } catch (\Throwable $e) {
  1327. Log::debug('ExamPdfExportService: 图片尺寸探测失败', ['src' => $src, 'error' => $e->getMessage()]);
  1328. $this->pdfImageDimensionCache[$src] = null;
  1329. return null;
  1330. }
  1331. }
  1332. /**
  1333. * @return array{w:int,h:int}|null
  1334. */
  1335. private function getPersistedPdfImageMetrics(string $src): ?array
  1336. {
  1337. if (! $this->isPdfImageMetricsTableReady()) {
  1338. return null;
  1339. }
  1340. $row = DB::table('pdf_image_metrics')
  1341. ->where('src', $src)
  1342. ->first(['width', 'height']);
  1343. if (! $row) {
  1344. return null;
  1345. }
  1346. $w = (int) ($row->width ?? 0);
  1347. $h = (int) ($row->height ?? 0);
  1348. if ($w <= 0 || $h <= 0) {
  1349. return null;
  1350. }
  1351. return ['w' => $w, 'h' => $h];
  1352. }
  1353. /**
  1354. * @param array{w:int,h:int} $data
  1355. */
  1356. private function persistPdfImageMetrics(string $src, array $data): void
  1357. {
  1358. if (! $this->isPdfImageMetricsTableReady()) {
  1359. return;
  1360. }
  1361. $w = (int) ($data['w'] ?? 0);
  1362. $h = (int) ($data['h'] ?? 0);
  1363. if ($w <= 0 || $h <= 0) {
  1364. return;
  1365. }
  1366. DB::table('pdf_image_metrics')->upsert([
  1367. [
  1368. 'src' => $src,
  1369. 'width' => $w,
  1370. 'height' => $h,
  1371. 'ratio' => round($w / max(1, $h), 4),
  1372. 'updated_at' => now(),
  1373. 'created_at' => now(),
  1374. ],
  1375. ], ['src'], ['width', 'height', 'ratio', 'updated_at']);
  1376. }
  1377. private function isPdfImageMetricsTableReady(): bool
  1378. {
  1379. if ($this->hasPdfImageMetricsTable !== null) {
  1380. return $this->hasPdfImageMetricsTable;
  1381. }
  1382. $this->hasPdfImageMetricsTable = Schema::hasTable('pdf_image_metrics');
  1383. return $this->hasPdfImageMetricsTable;
  1384. }
  1385. private function shouldApplyAdaptiveSizingToSrc(string $src): bool
  1386. {
  1387. $parts = parse_url($src);
  1388. if (! is_array($parts)) {
  1389. return false;
  1390. }
  1391. $host = strtolower((string) ($parts['host'] ?? ''));
  1392. $path = (string) ($parts['path'] ?? '');
  1393. if ($host !== 'file.chunsunqiuzhu.com') {
  1394. return false;
  1395. }
  1396. if (! str_contains($path, '/data/')) {
  1397. return false;
  1398. }
  1399. return (bool) preg_match('/\.(png|jpe?g|webp)$/i', $path);
  1400. }
  1401. /**
  1402. * 使用Chrome渲染PDF
  1403. */
  1404. private function renderWithChrome(string $htmlPath): ?string
  1405. {
  1406. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_').'.pdf';
  1407. $userDataDir = sys_get_temp_dir().'/chrome-profile-'.uniqid();
  1408. $chromeBinary = $this->findChromeBinary();
  1409. if (! $chromeBinary) {
  1410. Log::error('ExamPdfExportService: 未找到可用的Chrome/Chromium');
  1411. return null;
  1412. }
  1413. // 设置运行时目录
  1414. $runtimeHome = sys_get_temp_dir().'/chrome-home';
  1415. $runtimeXdg = sys_get_temp_dir().'/chrome-xdg';
  1416. if (! File::exists($runtimeHome)) {
  1417. @File::makeDirectory($runtimeHome, 0755, true);
  1418. }
  1419. if (! File::exists($runtimeXdg)) {
  1420. @File::makeDirectory($runtimeXdg, 0755, true);
  1421. }
  1422. $process = new Process([
  1423. $chromeBinary,
  1424. '--headless=new', // 【优化】使用新渲染引擎
  1425. '--disable-gpu',
  1426. '--no-sandbox',
  1427. '--disable-setuid-sandbox',
  1428. '--disable-dev-shm-usage',
  1429. '--disable-web-security',
  1430. '--disable-features=VizDisplayCompositor',
  1431. '--disable-extensions',
  1432. // '--disable-background-networking', // 注释掉,可能阻止必要的网络请求
  1433. '--disable-component-update',
  1434. '--disable-client-side-phishing-detection',
  1435. '--disable-default-apps',
  1436. '--disable-domain-reliability',
  1437. '--disable-sync',
  1438. '--no-first-run',
  1439. '--no-default-browser-check',
  1440. '--disable-crash-reporter',
  1441. '--disable-print-preview',
  1442. '--disable-features=TranslateUI',
  1443. '--disable-features=OptimizationHints',
  1444. '--disable-ipc-flooding-protection',
  1445. '--disable-background-timer-throttling',
  1446. '--disable-backgrounding-occluded-windows',
  1447. '--disable-renderer-backgrounding',
  1448. '--disable-features=AudioServiceOutOfProcess',
  1449. '--disable-gpu-sandbox',
  1450. '--disable-software-rasterizer',
  1451. '--disable-background-mode',
  1452. '--disable-extensions-http-throttling',
  1453. '--disable-ipc-flooding-protection',
  1454. '--disable-features=Dbus', // 禁用 dbus
  1455. // 【关键修复】添加虚拟时间预算,让Chrome有足够时间加载CDN资源和执行JS
  1456. '--virtual-time-budget=30000', // 30秒虚拟时间用于加载外部资源
  1457. '--run-all-compositor-stages-before-draw', // 确保所有渲染完成后再生成PDF
  1458. '--user-data-dir='.$userDataDir,
  1459. '--print-to-pdf='.$tmpPdf,
  1460. '--print-to-pdf-no-header',
  1461. '--allow-file-access-from-files',
  1462. '--font-render-hinting=none', // 【优化】禁用字体渲染提示
  1463. '--disable-font-antialiasing',
  1464. 'file://'.$htmlPath,
  1465. ], null, [
  1466. 'HOME' => $runtimeHome,
  1467. 'XDG_RUNTIME_DIR' => $runtimeXdg,
  1468. ]);
  1469. $process->setTimeout(180); // 复杂学情报告页允许更长渲染时间,降低超时失败率
  1470. $killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
  1471. Log::warning('ExamPdfExportService: [调试] Chrome命令准备执行', [
  1472. 'chrome_binary' => $chromeBinary,
  1473. 'html_path' => $htmlPath,
  1474. 'html_exists' => file_exists($htmlPath),
  1475. 'html_size' => file_exists($htmlPath) ? filesize($htmlPath) : 0,
  1476. 'pdf_path' => $tmpPdf,
  1477. 'user_data_dir' => $userDataDir,
  1478. ]);
  1479. try {
  1480. $startedAt = microtime(true);
  1481. $process->start();
  1482. $pdfGenerated = false;
  1483. // 轮询检测PDF是否生成
  1484. $pollStart = microtime(true);
  1485. $maxPollSeconds = 80; // 【修复】增加轮询超时到80秒
  1486. while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
  1487. if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
  1488. $pdfGenerated = true;
  1489. Log::info('ExamPdfExportService: PDF生成成功,提前终止Chrome进程', [
  1490. 'elapsed' => round(microtime(true) - $startedAt, 2),
  1491. 'pdf_size' => filesize($tmpPdf),
  1492. ]);
  1493. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1494. break;
  1495. }
  1496. usleep(100_000); // 【优化】从200ms减少到100ms
  1497. }
  1498. if ($process->isRunning()) {
  1499. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1500. }
  1501. // 【优化】删除不必要的wait()调用,避免重复等待
  1502. // $process->wait();
  1503. } catch (ProcessTimedOutException|ProcessSignaledException $e) {
  1504. if ($process->isRunning()) {
  1505. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1506. }
  1507. Log::warning('ExamPdfExportService: Chrome进程超时或被信号中断', [
  1508. 'elapsed' => round((microtime(true) - $startedAt), 2),
  1509. 'exception' => get_class($e),
  1510. ]);
  1511. $result = $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
  1512. if ($result !== null) {
  1513. return $result;
  1514. }
  1515. return $this->renderWithChromeMinimal($chromeBinary, $htmlPath);
  1516. } catch (\Throwable $e) {
  1517. if ($process->isRunning()) {
  1518. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1519. }
  1520. Log::error('ExamPdfExportService: Chrome进程异常', [
  1521. 'elapsed' => round((microtime(true) - $startedAt), 2),
  1522. 'error' => $e->getMessage(),
  1523. ]);
  1524. $result = $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  1525. if ($result !== null) {
  1526. return $result;
  1527. }
  1528. return $this->renderWithChromeMinimal($chromeBinary, $htmlPath);
  1529. }
  1530. $result = $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  1531. if ($result !== null) {
  1532. return $result;
  1533. }
  1534. return $this->renderWithChromeMinimal($chromeBinary, $htmlPath);
  1535. }
  1536. /**
  1537. * 处理Chrome进程结果
  1538. */
  1539. private function handleChromeProcessResult(string $tmpPdf, string $userDataDir, Process $process, ?float $startedAt): ?string
  1540. {
  1541. $pdfExists = file_exists($tmpPdf);
  1542. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  1543. $elapsed = $startedAt ? round((microtime(true) - $startedAt), 2) : null;
  1544. // 【优化】即使进程未成功,只要PDF存在且大小合理就返回
  1545. if ($pdfExists && $pdfSize > 1000) { // 至少1KB
  1546. Log::info('ExamPdfExportService: PDF生成成功', [
  1547. 'elapsed' => $elapsed,
  1548. 'pdf_size' => $pdfSize,
  1549. 'exit_code' => $process->getExitCode(),
  1550. 'is_successful' => $process->isSuccessful(),
  1551. ]);
  1552. $pdfBinary = file_get_contents($tmpPdf);
  1553. @unlink($tmpPdf);
  1554. File::deleteDirectory($userDataDir);
  1555. return $pdfBinary;
  1556. }
  1557. // 如果PDF不存在或太小,记录错误
  1558. Log::error('ExamPdfExportService: Chrome渲染失败', [
  1559. 'elapsed' => $elapsed,
  1560. 'pdf_exists' => $pdfExists,
  1561. 'pdf_size' => $pdfSize,
  1562. 'exit_code' => $process->getExitCode(),
  1563. 'error' => $process->getErrorOutput(),
  1564. 'output' => $process->getOutput(),
  1565. ]);
  1566. @unlink($tmpPdf);
  1567. File::deleteDirectory($userDataDir);
  1568. return null;
  1569. }
  1570. /**
  1571. * Chrome主渲染失败时的最小参数兜底。
  1572. */
  1573. private function renderWithChromeMinimal(string $chromeBinary, string $htmlPath): ?string
  1574. {
  1575. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_fallback_').'.pdf';
  1576. $process = new Process([
  1577. $chromeBinary,
  1578. '--headless=new',
  1579. '--disable-gpu',
  1580. '--no-sandbox',
  1581. '--print-to-pdf='.$tmpPdf,
  1582. 'file://'.$htmlPath,
  1583. ]);
  1584. $process->setTimeout(180);
  1585. try {
  1586. $process->run();
  1587. if (file_exists($tmpPdf) && filesize($tmpPdf) > 1000) {
  1588. Log::warning('ExamPdfExportService: Chrome最小参数兜底成功', [
  1589. 'pdf_size' => filesize($tmpPdf),
  1590. 'exit_code' => $process->getExitCode(),
  1591. ]);
  1592. $pdfBinary = file_get_contents($tmpPdf);
  1593. @unlink($tmpPdf);
  1594. return $pdfBinary;
  1595. }
  1596. Log::error('ExamPdfExportService: Chrome最小参数兜底失败', [
  1597. 'exit_code' => $process->getExitCode(),
  1598. 'error' => $process->getErrorOutput(),
  1599. 'output' => $process->getOutput(),
  1600. ]);
  1601. } catch (\Throwable $e) {
  1602. Log::error('ExamPdfExportService: Chrome最小参数兜底异常', [
  1603. 'error' => $e->getMessage(),
  1604. ]);
  1605. }
  1606. @unlink($tmpPdf);
  1607. return null;
  1608. }
  1609. /**
  1610. * 查找Chrome二进制文件
  1611. */
  1612. private function findChromeBinary(): ?string
  1613. {
  1614. $candidates = [
  1615. env('PDF_CHROME_BINARY'),
  1616. env('CHROME_BIN'), // Docker Alpine 环境变量
  1617. '/usr/bin/chromium-browser', // Alpine Linux
  1618. '/usr/bin/chromium',
  1619. '/usr/bin/google-chrome-stable',
  1620. '/usr/bin/google-chrome',
  1621. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', // macOS
  1622. ];
  1623. foreach ($candidates as $path) {
  1624. if ($path && is_file($path) && is_executable($path)) {
  1625. return $path;
  1626. }
  1627. }
  1628. return null;
  1629. }
  1630. /**
  1631. * 确保HTML为UTF-8编码,并内联外部资源
  1632. */
  1633. private function ensureUtf8Html(string $html): string
  1634. {
  1635. $meta = '<meta charset="UTF-8">';
  1636. if (stripos($html, '<head>') !== false) {
  1637. $html = preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
  1638. } else {
  1639. $html = $meta.$html;
  1640. }
  1641. // 【关键修复】内联KaTeX CSS,避免Chrome在容器中加载CDN资源超时
  1642. $html = $this->inlineExternalResources($html);
  1643. return $html;
  1644. }
  1645. /**
  1646. * 将CDN资源替换为内联资源
  1647. * 【关键修复】避免Chrome在容器中加载CDN资源超时,同时支持本地路径
  1648. */
  1649. private function inlineExternalResources(string $html): string
  1650. {
  1651. // 检查是否包含 KaTeX 资源(CDN 或本地)
  1652. $hasKatexCdn = strpos($html, 'cdn.jsdelivr.net/npm/katex') !== false;
  1653. $hasKatexLocal = strpos($html, '/js/katex.min.js') !== false || strpos($html, '/css/katex/katex.min.css') !== false;
  1654. // 【调试】记录HTML内容信息
  1655. Log::warning('ExamPdfExportService: inlineExternalResources', [
  1656. 'html_length' => strlen($html),
  1657. 'has_katex_cdn' => $hasKatexCdn,
  1658. 'has_katex_local' => $hasKatexLocal,
  1659. ]);
  1660. // 如果既没有 CDN 也没有本地链接,仍尝试注入 KaTeX 关系符通用修复
  1661. if (! $hasKatexCdn && ! $hasKatexLocal) {
  1662. Log::warning('ExamPdfExportService: HTML 中没有 KaTeX 资源链接,跳过内联');
  1663. return $this->applyKatexRelationGlyphFixes($html);
  1664. }
  1665. try {
  1666. // 读取并内联 KaTeX CSS(无论 CDN 还是本地)
  1667. $katexCssPath = public_path('css/katex/katex.min.css');
  1668. if (file_exists($katexCssPath)) {
  1669. $katexCss = file_get_contents($katexCssPath);
  1670. // 修复字体路径:将相对路径改为 data URI
  1671. $fontsDir = public_path('css/katex/fonts');
  1672. $katexCss = preg_replace_callback(
  1673. '/url\(["\']?fonts\/([^"\')\s]+)["\']?\)/i',
  1674. function ($matches) use ($fontsDir) {
  1675. $fontFile = $fontsDir.'/'.$matches[1];
  1676. if (file_exists($fontFile)) {
  1677. $fontData = base64_encode(file_get_contents($fontFile));
  1678. $mimeType = str_ends_with($matches[1], '.woff2') ? 'font/woff2' : 'font/woff';
  1679. return 'url(data:'.$mimeType.';base64,'.$fontData.')';
  1680. }
  1681. return $matches[0];
  1682. },
  1683. $katexCss
  1684. );
  1685. // 替换 CDN CSS 链接
  1686. if ($hasKatexCdn) {
  1687. $html = preg_replace(
  1688. '/<link[^>]*href=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*katex\.min\.css["\'][^>]*>/i',
  1689. '<style type="text/css">'.$katexCss.'</style>',
  1690. $html
  1691. );
  1692. }
  1693. // 替换本地 CSS 链接
  1694. if ($hasKatexLocal) {
  1695. $html = preg_replace(
  1696. '/<link[^>]*href=["\']\/css\/katex\/katex\.min\.css["\'][^>]*>/i',
  1697. '<style type="text/css">'.$katexCss.'</style>',
  1698. $html
  1699. );
  1700. }
  1701. Log::info('ExamPdfExportService: KaTeX CSS 已内联(含字体 data URI)');
  1702. }
  1703. // 读取本地 KaTeX JS(用于移除)
  1704. $katexJsPath = public_path('js/katex.min.js');
  1705. $autoRenderJsPath = public_path('js/auto-render.min.js');
  1706. if (file_exists($katexJsPath)) {
  1707. $katexJs = file_get_contents($katexJsPath);
  1708. $html = preg_replace(
  1709. '/<script[^>]*src=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*katex\.min\.js["\'][^>]*><\/script>/i',
  1710. '<script type="text/javascript">'.$katexJs.'</script>',
  1711. $html
  1712. );
  1713. }
  1714. if (file_exists($autoRenderJsPath)) {
  1715. $autoRenderJs = file_get_contents($autoRenderJsPath);
  1716. $html = preg_replace(
  1717. '/<script[^>]*src=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*auto-render[^"\']*["\'][^>]*><\/script>/i',
  1718. '<script type="text/javascript">'.$autoRenderJs.'</script>',
  1719. $html
  1720. );
  1721. }
  1722. // 【关键修复】使用服务端预渲染,而不是依赖客户端 JavaScript
  1723. // Chrome headless 的 --print-to-pdf 不会等待 JS 执行完成
  1724. // 所以我们使用 Node.js KaTeX 在服务端预渲染所有公式
  1725. // 1. 移除所有 KaTeX JavaScript(不再需要,因为使用服务端渲染)
  1726. // 移除内联的 katex.min.js
  1727. $html = preg_replace(
  1728. '/<script[^>]*type=["\']text\/javascript["\'][^>]*>[\s\S]*?katex[\s\S]*?<\/script>/i',
  1729. '<!-- KaTeX JS removed, using server-side rendering -->',
  1730. $html
  1731. );
  1732. // 移除 DOMContentLoaded 监听器
  1733. $html = preg_replace(
  1734. '/<script[^>]*>[\s\S]*?document\.addEventListener[\s\S]*?DOMContentLoaded[\s\S]*?<\/script>/i',
  1735. '<!-- DOMContentLoaded removed -->',
  1736. $html
  1737. );
  1738. // 2. 使用 KatexRenderer 进行服务端预渲染
  1739. if ($this->katexRenderer) {
  1740. $beforeLength = strlen($html);
  1741. $html = $this->katexRenderer->renderHtml($html);
  1742. $afterLength = strlen($html);
  1743. Log::info('ExamPdfExportService: LaTeX 公式服务端预渲染完成', [
  1744. 'before_length' => $beforeLength,
  1745. 'after_length' => $afterLength,
  1746. 'size_change' => $afterLength - $beforeLength,
  1747. ]);
  1748. // 通用修复:统一优化 KaTeX 关系运算符(mrel)字形
  1749. // 覆盖平行、垂直、等于、不等于等关系符,避免出现“平行符像 ||”的问题
  1750. $html = $this->applyKatexRelationGlyphFixes($html);
  1751. } else {
  1752. Log::warning('ExamPdfExportService: KatexRenderer 未初始化,跳过预渲染');
  1753. }
  1754. // 【换行处理】将字面的 \n 转换为 <br> 标签(在 KaTeX 渲染后处理,避免破坏公式)
  1755. // 先替换所有 \n 为 <br>,然后合并连续的 <br>(最多保留2个)
  1756. $html = str_replace('\\n', '<br>', $html);
  1757. $html = preg_replace('/(<br>\s*){3,}/', '<br><br>', $html); // 3个以上合并为2个
  1758. } catch (\Exception $e) {
  1759. Log::warning('ExamPdfExportService: 内联资源处理失败,保留原始HTML', [
  1760. 'error' => $e->getMessage(),
  1761. ]);
  1762. }
  1763. return $this->applyKatexRelationGlyphFixes($html);
  1764. }
  1765. /**
  1766. * 应用 KaTeX 关系符通用修复(先标记,再注入样式)
  1767. */
  1768. private function applyKatexRelationGlyphFixes(string $html): string
  1769. {
  1770. $html = $this->tagKatexParallelRelationSpans($html);
  1771. return $this->injectKatexRelationGlyphStyle($html);
  1772. }
  1773. /**
  1774. * 标记 KaTeX 中的平行关系符(∥),便于使用字体无关样式兜底
  1775. */
  1776. private function tagKatexParallelRelationSpans(string $html): string
  1777. {
  1778. if (strpos($html, '∥') === false || strpos($html, 'mrel') === false) {
  1779. return $html;
  1780. }
  1781. $pattern = '/<span(?P<attrs>[^>]*)class=(["\'])(?P<class>[^"\']*\bmrel\b[^"\']*)\2(?P<tail>[^>]*)>\s*∥\s*<\/span>/u';
  1782. $replaced = preg_replace_callback($pattern, static function (array $matches): string {
  1783. $attrs = $matches['attrs'] ?? '';
  1784. $quote = $matches[2] ?? '"';
  1785. $class = trim($matches['class'] ?? '');
  1786. $tail = $matches['tail'] ?? '';
  1787. if ($class === '') {
  1788. $class = 'mrel katex-rel-parallel';
  1789. } elseif (! preg_match('/\bkatex-rel-parallel\b/', $class)) {
  1790. $class .= ' katex-rel-parallel';
  1791. }
  1792. return '<span'.$attrs.'class='.$quote.$class.$quote.$tail.'>∥</span>';
  1793. }, $html);
  1794. return $replaced ?? $html;
  1795. }
  1796. /**
  1797. * 注入 KaTeX 关系运算符统一字形样式(全局、通用)
  1798. */
  1799. private function injectKatexRelationGlyphStyle(string $html): string
  1800. {
  1801. if (strpos($html, 'class="katex"') === false && strpos($html, 'class="katex-html"') === false) {
  1802. return $html;
  1803. }
  1804. if (strpos($html, 'id="katex-relation-glyph-style"') !== false) {
  1805. return $html;
  1806. }
  1807. $style = '<style id="katex-relation-glyph-style">'
  1808. .'.katex .mrel{'
  1809. .'font-family:"KaTeX_AMS","KaTeX_Main","NotoSerifCJKsc-Regular","NotoSerifCJKsc-Bold","NotoSans-Regular","NotoSans-Bold","NotoSansMonoCJKjp-Regular",serif !important;'
  1810. .'letter-spacing:.04em;'
  1811. .'}'
  1812. .'.katex .mrel .mord{font-family:inherit !important;}'
  1813. .'.katex .mrel.katex-rel-parallel{'
  1814. .'display:inline-block;'
  1815. .'font-size:1.22em;'
  1816. .'line-height:1.28;'
  1817. .'letter-spacing:.04em;'
  1818. .'vertical-align:0;'
  1819. .'transform:skewX(-14deg) scaleY(1.42);'
  1820. .'transform-origin:center;'
  1821. .'}'
  1822. .'</style>';
  1823. if (stripos($html, '</head>') !== false) {
  1824. return preg_replace('/<\/head>/i', $style.'</head>', $html, 1) ?? ($html.$style);
  1825. }
  1826. return $html.$style;
  1827. }
  1828. /**
  1829. * 【新增】合并两个HTML页面,插入分页符
  1830. * 保留原始页面样式和结构,只在中间插入分页符
  1831. */
  1832. private function mergeHtmlWithPageBreak(string $examHtml, string $gradingHtml, ?string $kpExplainHtml = null): ?string
  1833. {
  1834. try {
  1835. // 确保HTML编码正确
  1836. $examHtml = $this->ensureUtf8Html($examHtml);
  1837. $gradingHtml = $this->ensureUtf8Html($gradingHtml);
  1838. if ($kpExplainHtml) {
  1839. $kpExplainHtml = $this->ensureUtf8Html($kpExplainHtml);
  1840. }
  1841. // 提取body内容
  1842. $examBody = $this->extractBodyContent($examHtml);
  1843. $gradingBody = $this->extractBodyContent($gradingHtml);
  1844. // 知识点讲解使用专门的提取方法,避免嵌套完整HTML结构
  1845. $kpExplainBody = $kpExplainHtml ? $this->extractKpExplainContent($kpExplainHtml) : null;
  1846. if (empty($examBody) || empty($gradingBody)) {
  1847. Log::error('ExamPdfExportService: HTML内容提取失败', [
  1848. 'exam_body_length' => strlen($examBody),
  1849. 'grading_body_length' => strlen($gradingBody),
  1850. ]);
  1851. return null;
  1852. }
  1853. // 提取head内容(保留原始样式和meta信息)
  1854. $examHead = $this->extractHeadContent($examHtml);
  1855. $gradingHead = $this->extractHeadContent($gradingHtml);
  1856. $kpExplainHead = $kpExplainHtml ? $this->extractHeadContent($kpExplainHtml) : null;
  1857. // 构建统一HTML文档(保留原始结构)
  1858. $unifiedHtml = $this->buildUnifiedHtmlWithOriginalStructure(
  1859. $examHead,
  1860. $examBody,
  1861. $gradingBody,
  1862. $gradingHead,
  1863. $kpExplainBody,
  1864. $kpExplainHead
  1865. );
  1866. Log::info('HTML合并成功(保留原始样式)', [
  1867. 'exam_length' => strlen($examBody),
  1868. 'grading_length' => strlen($gradingBody),
  1869. 'kp_explain_length' => $kpExplainBody ? strlen($kpExplainBody) : 0,
  1870. 'unified_length' => strlen($unifiedHtml),
  1871. 'head_length' => strlen($examHead),
  1872. 'has_kp_explain' => ! empty($kpExplainBody),
  1873. ]);
  1874. return $unifiedHtml;
  1875. } catch (\Throwable $e) {
  1876. Log::error('mergeHtmlWithPageBreak 失败', [
  1877. 'error' => $e->getMessage(),
  1878. 'trace' => $e->getTraceAsString(),
  1879. ]);
  1880. return null;
  1881. }
  1882. }
  1883. /**
  1884. * 【新增】提取HTML的body内容
  1885. */
  1886. private function extractBodyContent(string $html): string
  1887. {
  1888. // 匹配body标签内容
  1889. if (preg_match('/<body[^>]*>(.*)<\/body>/is', $html, $matches)) {
  1890. return $matches[1];
  1891. }
  1892. // 如果没有body标签,返回整个HTML
  1893. return $html;
  1894. }
  1895. /**
  1896. * 【新增】提取HTML的head内容
  1897. * 保留原始页面的样式和meta信息
  1898. */
  1899. private function extractHeadContent(string $html): string
  1900. {
  1901. // 匹配head标签内容
  1902. if (preg_match('/<head[^>]*>(.*)<\/head>/is', $html, $matches)) {
  1903. return $matches[1];
  1904. }
  1905. // 如果没有head标签,返回默认meta
  1906. return '<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">';
  1907. }
  1908. /**
  1909. * 【新增】提取知识点讲解的核心内容
  1910. * 只提取 kp-explain 容器内部的内容,避免嵌套完整的HTML结构
  1911. */
  1912. private function extractKpExplainContent(string $html): string
  1913. {
  1914. // 如果 HTML 中包含嵌套的 <html> 标签,提取嵌套内容
  1915. if (preg_match('/<html[^>]*>(.*)<\/html>/is', $html, $htmlMatches)) {
  1916. $html = $htmlMatches[1];
  1917. }
  1918. // 如果 HTML 中包含 <head> 标签,跳过 head
  1919. if (preg_match('/<head[^>]*>.*?<\/head>/is', $html, $headMatch)) {
  1920. $html = substr($html, strpos($html, '</head>') + 7);
  1921. }
  1922. // 如果 HTML 中包含 <body> 标签,提取 body 内容
  1923. if (preg_match('/<body[^>]*>(.*)<\/body>/is', $html, $bodyMatches)) {
  1924. $html = $bodyMatches[1];
  1925. }
  1926. // 移除可能存在的嵌套 <html>, <head>, <body> 标签
  1927. $html = preg_replace('/<\/?(html|head|body)[^>]*>/is', '', $html);
  1928. // 移除 script 标签和注释
  1929. $html = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $html);
  1930. $html = preg_replace('/<!--[^>]*-->/is', '', $html);
  1931. return trim($html);
  1932. }
  1933. /**
  1934. * 【优化重构】构建统一的HTML文档(容器结构 + 消除空白页)
  1935. * 使用容器结构替代空的 page-break div,避免中间出现空白页
  1936. */
  1937. private function buildUnifiedHtmlWithOriginalStructure(
  1938. string $examHead,
  1939. string $examBody,
  1940. string $gradingBody,
  1941. string $gradingHead,
  1942. ?string $kpExplainBody = null,
  1943. ?string $kpExplainHead = null
  1944. ): string
  1945. {
  1946. // 清洗内容:移除可能存在的分页符,避免双重分页
  1947. $examBody = $this->stripPageBreakElements($examBody);
  1948. $gradingBody = $this->stripPageBreakElements($gradingBody);
  1949. if ($kpExplainBody) {
  1950. $kpExplainBody = $this->stripPageBreakElements($kpExplainBody);
  1951. }
  1952. // 合并 head 内容:试卷 head + 判卷 head + 知识点讲解 head(去重)+ 分页控制样式
  1953. $mergedHead = $examHead;
  1954. // 按顺序合并其他 head 里的 <style>(避免重复)
  1955. foreach ([$gradingHead, $kpExplainHead] as $extraHead) {
  1956. if (! $extraHead) {
  1957. continue;
  1958. }
  1959. if (preg_match_all('/<style[^>]*>(.*?)<\/style>/is', $extraHead, $styleMatches)) {
  1960. foreach ($styleMatches[0] as $idx => $styleTag) {
  1961. if (! str_contains($mergedHead, $styleMatches[1][$idx])) {
  1962. $mergedHead .= "\n ".$styleTag;
  1963. }
  1964. }
  1965. }
  1966. }
  1967. // 添加分页控制样式
  1968. $headContent = $mergedHead.'
  1969. <style>
  1970. /* 容器基础样式 - 保持现有页面边距 */
  1971. .exam-part,
  1972. .grading-part,
  1973. .kp-explain-part {
  1974. width: 100%;
  1975. margin: 0;
  1976. padding: 0;
  1977. }
  1978. /* 试卷部分 - 只有在知识点讲解后才需要分页 */
  1979. .exam-part {
  1980. /* 如果有知识点讲解,需要在新页面开始(通过 kp-explain-part 的 break-after 控制) */
  1981. /* 如果没有知识点讲解,试卷从第一页开始,不需要分页 */
  1982. break-after: auto;
  1983. page-break-after: auto;
  1984. /* 确保顶部没有额外边距 */
  1985. margin-top: 0;
  1986. padding-top: 0;
  1987. }
  1988. /* 核心分页控制:只在 grading-part 上设置 */
  1989. .grading-part {
  1990. /* CSS3 新标准 */
  1991. break-before: page;
  1992. /* 兼容旧版 WebKit */
  1993. page-break-before: always;
  1994. /* 确保顶部没有额外边距 */
  1995. margin-top: 0;
  1996. padding-top: 0;
  1997. }
  1998. /* 知识点讲解部分末尾强制分页(确保试卷从新页面开始) */
  1999. .kp-explain-part {
  2000. break-after: page;
  2001. page-break-after: always;
  2002. }
  2003. /* 防止试卷部分末尾分页 */
  2004. .exam-part {
  2005. /* 确保试卷内容连续 */
  2006. break-after: auto;
  2007. page-break-after: auto;
  2008. }
  2009. /* 避免在关键元素中间分页 */
  2010. .exam-part h1, .exam-part h2,
  2011. .grading-part h1, .grading-part h2 {
  2012. break-after: avoid;
  2013. page-break-after: avoid;
  2014. }
  2015. .exam-part table, .exam-part .question-item,
  2016. .grading-part table, .grading-part .answer-item {
  2017. break-inside: avoid;
  2018. page-break-inside: avoid;
  2019. }
  2020. /* 防止孤儿行 */
  2021. .exam-part p, .exam-part li,
  2022. .grading-part p, .grading-part li {
  2023. orphans: 2;
  2024. widows: 2;
  2025. }
  2026. /* 数学公式优化 */
  2027. .katex {
  2028. break-inside: avoid;
  2029. page-break-inside: avoid;
  2030. }
  2031. </style>';
  2032. // 构建HTML内容
  2033. $bodyContent = '';
  2034. $mergedTitle = '试卷与判卷合并';
  2035. if (preg_match('/<title>(.*?)<\/title>/is', $examHead, $titleMatches)) {
  2036. $candidateTitle = trim(strip_tags($titleMatches[1]));
  2037. if ($candidateTitle !== '') {
  2038. $mergedTitle = $candidateTitle;
  2039. }
  2040. }
  2041. // 如果有知识点讲解,添加到最前面
  2042. if ($kpExplainBody) {
  2043. $bodyContent .= '
  2044. <!-- 知识点讲解部分 -->
  2045. <div class="kp-explain-part">
  2046. '.$kpExplainBody.'
  2047. </div>
  2048. ';
  2049. }
  2050. // 添加试卷部分
  2051. $bodyContent .= '
  2052. <!-- EXAM_PART_START -->
  2053. <!-- 试卷部分 - 连续显示 -->
  2054. <div class="exam-part">
  2055. '.$examBody.'
  2056. </div>
  2057. <!-- EXAM_PART_END -->
  2058. ';
  2059. // 添加判卷部分
  2060. $bodyContent .= '
  2061. <!-- 判卷部分 - 强制新页面开始 -->
  2062. <div class="grading-part">
  2063. '.$gradingBody.'
  2064. </div>
  2065. ';
  2066. return '<!DOCTYPE html>
  2067. <html lang="zh-CN">
  2068. <head>
  2069. <meta charset="UTF-8">
  2070. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  2071. <title>'.$mergedTitle.'</title>
  2072. '.$headContent.'
  2073. </head>
  2074. <body>
  2075. '.$bodyContent.'
  2076. </body>
  2077. </html>';
  2078. }
  2079. /**
  2080. * 【新增】清洗HTML内容中的分页符元素
  2081. * 移除可能存在的 page-break 元素,避免双重分页导致空白页
  2082. */
  2083. private function stripPageBreakElements(string $content): string
  2084. {
  2085. // 只移除空的 page-break div 元素(通常是 <div class="page-break"></div>)
  2086. // 使用更精确的正则,只匹配空内容或纯空白内容的 div
  2087. $patterns = [
  2088. '/<div[^>]*class="[^"]*page-break[^"]*"[^>]*>\s*<\/div>/si',
  2089. '/<div[^>]*style="[^"]*page-break[^"]*"[^>]*>\s*<\/div>/si',
  2090. ];
  2091. foreach ($patterns as $pattern) {
  2092. $content = preg_replace($pattern, '', $content);
  2093. }
  2094. return $content;
  2095. }
  2096. /**
  2097. * 【新增】获取PDF通用样式
  2098. */
  2099. private function getCommonPdfStyles(): string
  2100. {
  2101. return '
  2102. * {
  2103. margin: 0;
  2104. padding: 0;
  2105. box-sizing: border-box;
  2106. }
  2107. body {
  2108. font-family: "Microsoft YaHei", "SimHei", Arial, sans-serif;
  2109. font-size: 14px;
  2110. line-height: 1.6;
  2111. color: #333;
  2112. background: #fff;
  2113. }
  2114. .paper-container {
  2115. max-width: 210mm;
  2116. margin: 0 auto;
  2117. padding: 20mm;
  2118. background: white;
  2119. }
  2120. .paper-header {
  2121. text-align: center;
  2122. margin-bottom: 30px;
  2123. padding-bottom: 15px;
  2124. border-bottom: 2px solid #333;
  2125. }
  2126. .paper-title {
  2127. font-size: 24px;
  2128. font-weight: bold;
  2129. margin-bottom: 10px;
  2130. }
  2131. .paper-info {
  2132. font-size: 14px;
  2133. color: #666;
  2134. }
  2135. .question {
  2136. margin-bottom: 30px;
  2137. padding: 20px;
  2138. border: 1px solid #ddd;
  2139. border-radius: 5px;
  2140. }
  2141. .question-number {
  2142. font-weight: bold;
  2143. margin-bottom: 10px;
  2144. }
  2145. .question-stem {
  2146. margin-bottom: 15px;
  2147. }
  2148. .options {
  2149. list-style: none;
  2150. margin-left: 20px;
  2151. }
  2152. .options li {
  2153. margin-bottom: 8px;
  2154. }
  2155. .answer-section {
  2156. margin-top: 20px;
  2157. padding-top: 15px;
  2158. border-top: 1px solid #eee;
  2159. }
  2160. .answer-label {
  2161. font-weight: bold;
  2162. color: #d9534f;
  2163. }
  2164. .solution {
  2165. margin-top: 10px;
  2166. padding: 10px;
  2167. background: #f5f5f5;
  2168. border-left: 4px solid #5bc0de;
  2169. }
  2170. ';
  2171. }
  2172. /**
  2173. * 构建知识点名称映射
  2174. */
  2175. private function buildKnowledgePointNameMap(): array
  2176. {
  2177. try {
  2178. $options = $this->questionServiceApi->getKnowledgePointOptions();
  2179. return $options ?: [];
  2180. } catch (\Throwable $e) {
  2181. Log::warning('ExamPdfExportService: 获取知识点名称失败', [
  2182. 'error' => $e->getMessage(),
  2183. ]);
  2184. return [];
  2185. }
  2186. }
  2187. /**
  2188. * 构建掌握度摘要
  2189. */
  2190. private function buildMasterySummary(array $masteryData, array $kpNameMap): array
  2191. {
  2192. Log::info('ExamPdfExportService: buildMasterySummary开始处理', [
  2193. 'masteryData_count' => count($masteryData),
  2194. 'kpNameMap_count' => count($kpNameMap),
  2195. ]);
  2196. $items = [];
  2197. $total = 0;
  2198. $count = 0;
  2199. foreach ($masteryData as $row) {
  2200. $code = $row['kp_code'] ?? null;
  2201. // 【修复】使用kpNameMap转换名称为友好显示名
  2202. $name = $kpNameMap[$code] ?? $row['kp_name'] ?? $code ?: '未知知识点';
  2203. $level = (float) ($row['mastery_level'] ?? 0);
  2204. $delta = $row['mastery_change'] ?? null;
  2205. $items[] = [
  2206. 'kp_code' => $code,
  2207. 'kp_name' => $name,
  2208. 'mastery_level' => $level,
  2209. 'mastery_change' => $delta,
  2210. ];
  2211. $total += $level;
  2212. $count++;
  2213. }
  2214. $average = $count > 0 ? round($total / $count, 2) : null;
  2215. // 按掌握度从低到高排序
  2216. if (! empty($items)) {
  2217. usort($items, fn ($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  2218. }
  2219. $result = [
  2220. 'items' => $items,
  2221. 'average' => $average,
  2222. 'weak_list' => array_slice($items, 0, 5),
  2223. ];
  2224. Log::info('ExamPdfExportService: buildMasterySummary完成', [
  2225. 'total_count' => $count,
  2226. 'items_count' => count($items),
  2227. ]);
  2228. return $result;
  2229. }
  2230. /**
  2231. * 标准化题型
  2232. */
  2233. private function normalizeQuestionType(string $type): string
  2234. {
  2235. $t = strtolower(trim($type));
  2236. return match (true) {
  2237. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  2238. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  2239. default => 'answer',
  2240. };
  2241. }
  2242. private function buildPaperNamePrefix(Paper $paper): string
  2243. {
  2244. $assembleType = ($paper->paper_type === null || $paper->paper_type === '')
  2245. ? null
  2246. : (int) $paper->paper_type;
  2247. $studentName = Student::query()
  2248. ->where('student_id', $paper->student_id)
  2249. ->value('name') ?? ($paper->student_id ?: '________');
  2250. try {
  2251. $assembleTypeLabel = $assembleType !== null ? PaperNaming::assembleTypeLabel($assembleType) : '未知类型';
  2252. } catch (\Throwable $e) {
  2253. $assembleTypeLabel = '未知类型';
  2254. }
  2255. return "{$studentName}_".PaperNaming::extractExamCode((string) $paper->paper_id)."_{$assembleTypeLabel}";
  2256. }
  2257. private function buildPaperDisplayTitle(Paper $paper): string
  2258. {
  2259. return $this->buildPaperNamePrefix($paper).'_'.now()->format('Ymd');
  2260. }
  2261. private function buildPdfFileName(Paper $paper, ?string $stamp = null): string
  2262. {
  2263. $basePrefix = $this->buildPaperNamePrefix($paper);
  2264. $stamp = $stamp ?: now()->format('YmdHis').strtoupper(Str::random(4));
  2265. $base = "{$basePrefix}_{$stamp}";
  2266. $safe = PaperNaming::toSafeFilename($base);
  2267. return "{$safe}.pdf";
  2268. }
  2269. private function extractUploadStamp(string $url): ?string
  2270. {
  2271. $path = parse_url($url, PHP_URL_PATH);
  2272. if (! is_string($path) || $path === '') {
  2273. return null;
  2274. }
  2275. $stem = pathinfo($path, PATHINFO_FILENAME);
  2276. if (! is_string($stem) || $stem === '') {
  2277. return null;
  2278. }
  2279. if (preg_match('/(\d{14}[A-Za-z0-9]{4})/', $stem, $matches)) {
  2280. return $matches[1];
  2281. }
  2282. return null;
  2283. }
  2284. /**
  2285. * 保存PDF URL到数据库
  2286. */
  2287. private function savePdfUrlToDatabase(string $paperId, string $field, string $url): void
  2288. {
  2289. try {
  2290. $paper = Paper::where('paper_id', $paperId)->first();
  2291. if ($paper) {
  2292. $paperDisplayTitle = $this->buildPaperDisplayTitle($paper);
  2293. $stamp = $this->extractUploadStamp($url);
  2294. if ($stamp) {
  2295. $paperDisplayTitle = $this->buildPaperNamePrefix($paper).'_'.$stamp;
  2296. }
  2297. $updatePayload = [
  2298. $field => $url,
  2299. 'paper_name' => $paperDisplayTitle,
  2300. ];
  2301. $paper->update($updatePayload);
  2302. Log::info('ExamPdfExportService: PDF URL已写入数据库', [
  2303. 'paper_id' => $paperId,
  2304. 'field' => $field,
  2305. 'url' => $url,
  2306. 'paper_name' => $paperDisplayTitle,
  2307. ]);
  2308. }
  2309. } catch (\Throwable $e) {
  2310. Log::error('ExamPdfExportService: 写入PDF URL失败', [
  2311. 'paper_id' => $paperId,
  2312. 'field' => $field,
  2313. 'error' => $e->getMessage(),
  2314. ]);
  2315. }
  2316. }
  2317. /**
  2318. * 保存学情分析PDF URL
  2319. */
  2320. private function saveAnalysisPdfUrl(string $paperId, string $studentId, ?string $recordId, string $url): void
  2321. {
  2322. try {
  2323. if ($recordId) {
  2324. // OCR记录
  2325. $ocrRecord = \App\Models\OCRRecord::find($recordId);
  2326. if ($ocrRecord) {
  2327. $ocrRecord->update(['analysis_pdf_url' => $url]);
  2328. Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
  2329. 'record_id' => $recordId,
  2330. 'paper_id' => $paperId,
  2331. 'student_id' => $studentId,
  2332. 'url' => $url,
  2333. ]);
  2334. }
  2335. } else {
  2336. // 【修复】同时更新 exam_analysis_results 表和分析报告表
  2337. $updated = \DB::connection('mysql')->table('exam_analysis_results')
  2338. ->where('student_id', $studentId)
  2339. ->where('paper_id', $paperId)
  2340. ->update([
  2341. 'analysis_pdf_url' => $url,
  2342. 'updated_at' => now(),
  2343. ]);
  2344. if ($updated) {
  2345. Log::info('ExamPdfExportService: 学情分析PDF URL已写入exam_analysis_results表', [
  2346. 'student_id' => $studentId,
  2347. 'paper_id' => $paperId,
  2348. 'url' => $url,
  2349. 'updated_rows' => $updated,
  2350. ]);
  2351. } else {
  2352. Log::warning('ExamPdfExportService: 未找到要更新的学情分析记录', [
  2353. 'student_id' => $studentId,
  2354. 'paper_id' => $paperId,
  2355. ]);
  2356. }
  2357. // 学生记录 - 使用新的 student_reports 表(备用)
  2358. \App\Models\StudentReport::updateOrCreate(
  2359. [
  2360. 'student_id' => $studentId,
  2361. 'report_type' => 'exam_analysis',
  2362. 'paper_id' => $paperId,
  2363. ],
  2364. [
  2365. 'pdf_url' => $url,
  2366. 'generation_status' => 'completed',
  2367. 'generated_at' => now(),
  2368. 'updated_at' => now(),
  2369. ]
  2370. );
  2371. Log::info('ExamPdfExportService: 学生学情报告PDF URL已保存到student_reports表(备用)', [
  2372. 'student_id' => $studentId,
  2373. 'paper_id' => $paperId,
  2374. 'url' => $url,
  2375. ]);
  2376. }
  2377. } catch (\Throwable $e) {
  2378. Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
  2379. 'paper_id' => $paperId,
  2380. 'student_id' => $studentId,
  2381. 'record_id' => $recordId,
  2382. 'error' => $e->getMessage(),
  2383. ]);
  2384. }
  2385. }
  2386. /**
  2387. * 【修复】处理父节点掌握度数据
  2388. * 1. 过滤掉掌握度为0或null的父节点
  2389. * 2. 将kp_code转换为友好的kp_name
  2390. * 3. 构建父子层级关系(只显示本次考试相关的子节点)
  2391. */
  2392. private function processParentMasteryLevels(
  2393. array $parentMasteryLevels,
  2394. array $kpNameMap,
  2395. array $examKpCodes = [],
  2396. array $masteryMap = [],
  2397. array $snapshotMasteryData = []
  2398. ): array
  2399. {
  2400. $processed = [];
  2401. foreach ($parentMasteryLevels as $kpCode => $masteryData) {
  2402. // 兼容不同数据结构:可能是数组或数字
  2403. $masteryLevel = is_array($masteryData) ? ($masteryData['mastery_level'] ?? 0) : $masteryData;
  2404. $masteryChange = is_array($masteryData) ? ($masteryData['mastery_change'] ?? null) : null;
  2405. $changeSource = is_array($masteryData) ? ($masteryData['change_source'] ?? null) : null;
  2406. // 获取友好名称
  2407. $kpName = $kpNameMap[$kpCode] ?? $kpCode;
  2408. // 构建父节点数据,包含子节点信息(只显示本次考试相关的)
  2409. $childrenData = $this->getChildKnowledgePoints($kpCode, $kpNameMap, $examKpCodes, $masteryMap);
  2410. $allChildren = $childrenData['all_children'] ?? [];
  2411. // 口径统一:优先使用全部直接子节点均值作为父节点掌握度
  2412. if (! empty($allChildren)) {
  2413. $allLevels = array_map(
  2414. fn ($c) => floatval($c['mastery_level'] ?? 0),
  2415. $allChildren
  2416. );
  2417. $masteryLevel = ! empty($allLevels)
  2418. ? array_sum($allLevels) / count($allLevels)
  2419. : floatval($masteryLevel);
  2420. if (! empty($snapshotMasteryData)) {
  2421. $prevLevels = [];
  2422. foreach ($allChildren as $child) {
  2423. $childCode = (string) ($child['kp_code'] ?? '');
  2424. if ($childCode === '') {
  2425. continue;
  2426. }
  2427. $currentChild = floatval($masteryMap[$childCode] ?? 0);
  2428. $prevFromSnapshot = $snapshotMasteryData[$childCode]['previous_mastery'] ?? null;
  2429. $currFromSnapshot = $snapshotMasteryData[$childCode]['current_mastery'] ?? null;
  2430. $previousChild = $prevFromSnapshot ?? $currFromSnapshot ?? $currentChild;
  2431. $prevLevels[] = floatval($previousChild);
  2432. }
  2433. if (! empty($prevLevels)) {
  2434. $masteryChange = $masteryLevel - (array_sum($prevLevels) / count($prevLevels));
  2435. $changeSource = 'children_all_average';
  2436. }
  2437. }
  2438. }
  2439. // 仅过滤空值;0 掌握度的命中父节点也要展示
  2440. if ($masteryLevel === null) {
  2441. continue;
  2442. }
  2443. $hitLevels = array_map(
  2444. fn ($c) => floatval($c['mastery_level'] ?? 0),
  2445. $childrenData['hit_children'] ?? []
  2446. );
  2447. $hitAvg = ! empty($hitLevels) ? array_sum($hitLevels) / count($hitLevels) : null;
  2448. $hitCount = count($childrenData['hit_children'] ?? []);
  2449. // 父节点仅展示“本卷命中知识点”对应的父节点
  2450. if ($hitCount <= 0) {
  2451. continue;
  2452. }
  2453. $processed[$kpCode] = [
  2454. 'kp_code' => $kpCode,
  2455. 'kp_name' => $kpName,
  2456. 'mastery_level' => round(floatval($masteryLevel), 4),
  2457. 'mastery_percentage' => round(floatval($masteryLevel) * 100, 2),
  2458. 'mastery_change' => $masteryChange !== null ? round(floatval($masteryChange), 4) : null,
  2459. 'change_source' => $changeSource,
  2460. // 兼容旧模板字段:仅命中子节点
  2461. 'children' => $childrenData['hit_children'] ?? [],
  2462. // 新增:全部直接子节点(含掌握度、是否命中)
  2463. 'children_all' => $childrenData['all_children'] ?? [],
  2464. 'children_hit_count' => $hitCount,
  2465. 'children_total_count' => count($childrenData['all_children'] ?? []),
  2466. 'children_hit_avg_mastery' => $hitAvg !== null ? round($hitAvg, 4) : null,
  2467. 'level' => $this->calculateKnowledgePointLevel($kpCode),
  2468. ];
  2469. }
  2470. // 按掌握度降序排序
  2471. uasort($processed, function ($a, $b) {
  2472. return $b['mastery_level'] <=> $a['mastery_level'];
  2473. });
  2474. return $processed;
  2475. }
  2476. /**
  2477. * 【修复】获取子知识点列表(只返回本次考试涉及的)
  2478. */
  2479. private function getChildKnowledgePoints(string $parentKpCode, array $kpNameMap, array $examKpCodes = [], array $masteryMap = []): array
  2480. {
  2481. $allChildren = [];
  2482. $hitChildren = [];
  2483. try {
  2484. $childCodes = DB::connection('mysql')
  2485. ->table('knowledge_points')
  2486. ->where('parent_kp_code', $parentKpCode)
  2487. ->pluck('kp_code')
  2488. ->toArray();
  2489. foreach ($childCodes as $childCode) {
  2490. $isHit = in_array($childCode, $examKpCodes);
  2491. $childData = [
  2492. 'kp_code' => $childCode,
  2493. 'kp_name' => $kpNameMap[$childCode] ?? $childCode,
  2494. 'mastery_level' => floatval($masteryMap[$childCode] ?? 0),
  2495. 'is_hit' => $isHit,
  2496. ];
  2497. $allChildren[] = $childData;
  2498. if ($isHit) {
  2499. $hitChildren[] = $childData;
  2500. }
  2501. }
  2502. } catch (\Exception $e) {
  2503. Log::warning('获取子知识点失败', [
  2504. 'parent_kp_code' => $parentKpCode,
  2505. 'error' => $e->getMessage(),
  2506. ]);
  2507. }
  2508. return [
  2509. 'all_children' => $allChildren,
  2510. 'hit_children' => $hitChildren,
  2511. ];
  2512. }
  2513. /**
  2514. * 当历史父节点概览缺失时,直接由“本卷命中知识点”反推出父节点并构建展示数据。
  2515. */
  2516. private function buildParentMasteryFromHitCodes(
  2517. array $examKpCodes,
  2518. array $kpNameMap,
  2519. array $masteryMap = [],
  2520. array $snapshotMasteryData = []
  2521. ): array {
  2522. $codes = array_values(array_unique(array_filter(array_map(fn ($c) => trim((string) $c), $examKpCodes))));
  2523. if (empty($codes)) {
  2524. return [];
  2525. }
  2526. $rows = DB::connection('mysql')
  2527. ->table('knowledge_points')
  2528. ->whereIn('kp_code', $codes)
  2529. ->whereNotNull('parent_kp_code')
  2530. ->where('parent_kp_code', '!=', '')
  2531. ->select('kp_code', 'parent_kp_code')
  2532. ->get();
  2533. $parentMap = [];
  2534. foreach ($rows as $r) {
  2535. $parentCode = trim((string) ($r->parent_kp_code ?? ''));
  2536. $childCode = trim((string) ($r->kp_code ?? ''));
  2537. if ($parentCode === '' || $childCode === '') {
  2538. continue;
  2539. }
  2540. $parentMap[$parentCode][] = $childCode;
  2541. }
  2542. if (empty($parentMap)) {
  2543. return [];
  2544. }
  2545. $parents = DB::connection('mysql')
  2546. ->table('knowledge_points')
  2547. ->whereIn('kp_code', array_keys($parentMap))
  2548. ->pluck('name', 'kp_code')
  2549. ->toArray();
  2550. $processed = [];
  2551. foreach ($parentMap as $parentCode => $hitChildrenCodes) {
  2552. $childrenData = $this->getChildKnowledgePoints($parentCode, $kpNameMap, $codes, $masteryMap);
  2553. $allChildren = $childrenData['all_children'] ?? [];
  2554. $hitChildren = $childrenData['hit_children'] ?? [];
  2555. $hitCount = count($hitChildren);
  2556. if ($hitCount <= 0) {
  2557. continue;
  2558. }
  2559. $allLevels = array_map(fn ($c) => floatval($c['mastery_level'] ?? 0), $allChildren);
  2560. $masteryLevel = !empty($allLevels) ? array_sum($allLevels) / count($allLevels) : 0.0;
  2561. $prevLevels = [];
  2562. foreach ($allChildren as $child) {
  2563. $childCode = (string) ($child['kp_code'] ?? '');
  2564. if ($childCode === '') {
  2565. continue;
  2566. }
  2567. $currentChild = floatval($masteryMap[$childCode] ?? 0);
  2568. $prevFromSnapshot = $snapshotMasteryData[$childCode]['previous_mastery'] ?? null;
  2569. $currFromSnapshot = $snapshotMasteryData[$childCode]['current_mastery'] ?? null;
  2570. $previousChild = $prevFromSnapshot ?? $currFromSnapshot ?? $currentChild;
  2571. $prevLevels[] = floatval($previousChild);
  2572. }
  2573. $masteryChange = !empty($prevLevels) ? ($masteryLevel - (array_sum($prevLevels) / count($prevLevels))) : null;
  2574. $hitLevels = array_map(fn ($c) => floatval($c['mastery_level'] ?? 0), $hitChildren);
  2575. $hitAvg = !empty($hitLevels) ? array_sum($hitLevels) / count($hitLevels) : null;
  2576. $processed[$parentCode] = [
  2577. 'kp_code' => $parentCode,
  2578. 'kp_name' => $parents[$parentCode] ?? ($kpNameMap[$parentCode] ?? $parentCode),
  2579. 'mastery_level' => round(floatval($masteryLevel), 4),
  2580. 'mastery_percentage' => round(floatval($masteryLevel) * 100, 2),
  2581. 'mastery_change' => $masteryChange !== null ? round(floatval($masteryChange), 4) : null,
  2582. 'change_source' => 'hit_kp_parent_fallback',
  2583. 'children' => $hitChildren,
  2584. 'children_all' => $allChildren,
  2585. 'children_hit_count' => $hitCount,
  2586. 'children_total_count' => count($allChildren),
  2587. 'children_hit_avg_mastery' => $hitAvg !== null ? round($hitAvg, 4) : null,
  2588. 'level' => $this->calculateKnowledgePointLevel($parentCode),
  2589. ];
  2590. }
  2591. uasort($processed, fn ($a, $b) => $b['mastery_level'] <=> $a['mastery_level']);
  2592. return $processed;
  2593. }
  2594. /**
  2595. * 计算知识点层级深度
  2596. */
  2597. private function calculateKnowledgePointLevel(string $kpCode): int
  2598. {
  2599. // 根据kp_code前缀判断层级深度
  2600. // 例如: M (1级) -> M01 (2级) -> M01A (3级)
  2601. if (preg_match('/^[A-Z]+$/', $kpCode)) {
  2602. return 1; // 一级分类,如 M, S, E, G
  2603. } elseif (preg_match('/^[A-Z]+\d+$/', $kpCode)) {
  2604. return 2; // 二级分类,如 M01, S02
  2605. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+$/', $kpCode)) {
  2606. return 3; // 三级分类,如 M01A, S02B
  2607. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+\d+$/', $kpCode)) {
  2608. return 4; // 四级分类,如 M01A1
  2609. }
  2610. return 1; // 默认一级
  2611. }
  2612. /**
  2613. * 构建题目数据(用于PDF生成)
  2614. */
  2615. private function buildQuestionsData(Paper $paper): array
  2616. {
  2617. $paperQuestions = $paper->questions()->orderBy('question_number')->get();
  2618. $questionsData = [];
  2619. foreach ($paperQuestions as $pq) {
  2620. $questionsData[] = [
  2621. 'id' => $pq->question_bank_id,
  2622. 'question_number' => $pq->question_number, // 传递原始题号,确保渲染时序号正确
  2623. 'kp_code' => $pq->knowledge_point,
  2624. 'question_type' => $pq->question_type ?? 'answer',
  2625. 'stem' => $pq->question_text ?? '题目内容缺失',
  2626. 'solution' => $pq->solution ?? '',
  2627. 'answer' => $pq->correct_answer ?? '',
  2628. 'difficulty' => $pq->difficulty ?? 0.5,
  2629. 'score' => $pq->score ?? 5,
  2630. 'tags' => '',
  2631. 'content' => $pq->question_text ?? '',
  2632. ];
  2633. }
  2634. // 获取完整题目详情
  2635. if (! empty($questionsData)) {
  2636. $questionIds = array_column($questionsData, 'id');
  2637. $questionsResponse = $this->questionServiceApi->getQuestionsByIds($questionIds);
  2638. $responseData = $questionsResponse['data'] ?? [];
  2639. if (! empty($responseData)) {
  2640. $responseDataMap = [];
  2641. foreach ($responseData as $respQ) {
  2642. $responseDataMap[$respQ['id']] = $respQ;
  2643. }
  2644. $questionsData = array_map(function ($q) use ($responseDataMap) {
  2645. if (isset($responseDataMap[$q['id']])) {
  2646. $apiData = $responseDataMap[$q['id']];
  2647. $q['stem'] = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  2648. $q['content'] = $q['stem'];
  2649. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  2650. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  2651. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  2652. $q['options'] = $apiData['options'] ?? [];
  2653. }
  2654. return $q;
  2655. }, $questionsData);
  2656. }
  2657. }
  2658. // 按题型分类
  2659. $classified = ['choice' => [], 'fill' => [], 'answer' => []];
  2660. foreach ($questionsData as $q) {
  2661. $type = $this->determineQuestionType($q);
  2662. $classified[$type][] = (object) $q;
  2663. }
  2664. // 【调试】记录题目分类情况
  2665. Log::debug('buildQuestionsData: 题目分类结果', [
  2666. 'total_questions' => count($questionsData),
  2667. 'choice_count' => count($classified['choice']),
  2668. 'fill_count' => count($classified['fill']),
  2669. 'answer_count' => count($classified['answer']),
  2670. 'choice_numbers' => array_map(fn ($q) => $q->question_number ?? 'N/A', $classified['choice']),
  2671. 'fill_numbers' => array_map(fn ($q) => $q->question_number ?? 'N/A', $classified['fill']),
  2672. 'answer_numbers' => array_map(fn ($q) => $q->question_number ?? 'N/A', $classified['answer']),
  2673. ]);
  2674. return $classified;
  2675. }
  2676. /**
  2677. * 获取学生信息
  2678. */
  2679. private function getStudentInfo(?string $studentId): array
  2680. {
  2681. if (! $studentId) {
  2682. return [
  2683. 'name' => '未知学生',
  2684. 'grade' => '未知年级',
  2685. 'class' => '未知班级',
  2686. ];
  2687. }
  2688. try {
  2689. $student = DB::table('students')
  2690. ->where('student_id', $studentId)
  2691. ->first();
  2692. if ($student) {
  2693. return [
  2694. 'name' => $student->name ?? $studentId,
  2695. 'grade' => $student->grade ?? '未知',
  2696. 'class' => $student->class ?? '未知',
  2697. ];
  2698. }
  2699. } catch (\Exception $e) {
  2700. Log::warning('获取学生信息失败', [
  2701. 'student_id' => $studentId,
  2702. 'error' => $e->getMessage(),
  2703. ]);
  2704. }
  2705. return [
  2706. 'name' => $studentId,
  2707. 'grade' => '未知',
  2708. 'class' => '未知',
  2709. ];
  2710. }
  2711. /**
  2712. * 获取教师信息
  2713. */
  2714. private function getTeacherInfo(?string $teacherId): array
  2715. {
  2716. if (! $teacherId) {
  2717. return [
  2718. 'name' => '未知老师',
  2719. 'subject' => '数学',
  2720. ];
  2721. }
  2722. try {
  2723. $query = DB::table('teachers')->where('teacher_id', $teacherId);
  2724. // 仅在列存在时追加,避免 Unknown column 'id'
  2725. if (Schema::hasColumn('teachers', 'id')) {
  2726. $query->orWhere('id', $teacherId);
  2727. }
  2728. $teacher = $query->first();
  2729. if ($teacher) {
  2730. return [
  2731. 'name' => $teacher->name ?? '________',
  2732. 'subject' => $teacher->subject ?? '数学',
  2733. ];
  2734. }
  2735. } catch (\Exception $e) {
  2736. Log::warning('获取教师信息失败', [
  2737. 'teacher_id' => $teacherId,
  2738. 'error' => $e->getMessage(),
  2739. ]);
  2740. }
  2741. return [
  2742. 'name' => '________',
  2743. 'subject' => '数学',
  2744. ];
  2745. }
  2746. /**
  2747. * 判断题目类型
  2748. * 【修复】优先使用 question_type 字段,避免选择题因含有()被误判为填空题
  2749. */
  2750. private function determineQuestionType(array $question): string
  2751. {
  2752. // 1. 【优先】根据已有类型字段判断(最可靠的来源)
  2753. if (! empty($question['question_type'])) {
  2754. $type = strtolower(trim($question['question_type']));
  2755. if (in_array($type, ['choice', '选择题'])) {
  2756. return 'choice';
  2757. }
  2758. if (in_array($type, ['fill', '填空题'])) {
  2759. return 'fill';
  2760. }
  2761. if (in_array($type, ['answer', '解答题'])) {
  2762. return 'answer';
  2763. }
  2764. }
  2765. // 2. 如果没有明确类型,则根据题干内容推断
  2766. $stem = $question['stem'] ?? $question['content'] ?? '';
  2767. if (is_string($stem)) {
  2768. // 检查是否有选项模式 A. B. C. D.
  2769. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  2770. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  2771. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  2772. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  2773. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0);
  2774. if ($optionCount >= 2) {
  2775. return 'choice';
  2776. }
  2777. // 检查是否有填空标记(但要排除选择题的括号)
  2778. if (preg_match('/(\s*)|\(\s*\)/', $stem)) {
  2779. return 'fill';
  2780. }
  2781. }
  2782. // 3. 默认返回解答题
  2783. return 'answer';
  2784. }
  2785. /**
  2786. * 格式化换行符:将字面的 \n 转换为 HTML <br> 标签
  2787. * 用于 PDF 渲染时正确显示换行
  2788. */
  2789. private function formatNewlines(?string $text): ?string
  2790. {
  2791. if ($text === null) {
  2792. return null;
  2793. }
  2794. // 【修复】替换 \n 为 <br>,但保护 LaTeX 命令如 \neq, \ne, \newline, \nu 等
  2795. // 使用负向前瞻 (?![a-zA-Z]) 避免误伤 LaTeX 命令
  2796. $text = preg_replace('/\\\\n(?![a-zA-Z])/', '<br>', $text);
  2797. // 合并连续的 <br>(最多保留2个)
  2798. return preg_replace('/(<br>\s*){3,}/', '<br><br>', $text);
  2799. }
  2800. /**
  2801. * 根据指定的题目生成PDF(新增方法)
  2802. *
  2803. * @param object $paper 虚拟试卷对象
  2804. * @param array $groupedQuestions 按题型分组的题目数据
  2805. * @param array $student 学生信息 ['name' => '', 'grade' => '']
  2806. * @param array $teacher 教师信息 ['name' => '']
  2807. * @param bool $includeGrading 是否包含判卷版本
  2808. * @return array 返回 ['pdf_url' => '...', 'grading_pdf_url' => '...']
  2809. */
  2810. public function generateByQuestions(
  2811. object $paper,
  2812. array $groupedQuestions,
  2813. array $student = [],
  2814. array $teacher = [],
  2815. bool $includeGrading = false
  2816. ): array {
  2817. Log::info('generateByQuestions 开始', [
  2818. 'paper_id' => $paper->paper_id,
  2819. 'question_counts' => [
  2820. 'choice' => count($groupedQuestions['choice'] ?? []),
  2821. 'fill' => count($groupedQuestions['fill'] ?? []),
  2822. 'answer' => count($groupedQuestions['answer'] ?? []),
  2823. ],
  2824. 'include_grading' => $includeGrading,
  2825. ]);
  2826. try {
  2827. $result = [];
  2828. // 1. 生成试卷PDF(不含答案)
  2829. $examHtml = $this->renderCustomExamHtml($paper, $groupedQuestions, $student, $teacher, false);
  2830. if ($examHtml) {
  2831. // 【修复】使用服务端 KaTeX 预渲染 LaTeX 公式
  2832. if ($this->katexRenderer) {
  2833. $examHtml = $this->katexRenderer->renderHtml($examHtml);
  2834. }
  2835. $examPdf = $this->buildPdf($examHtml);
  2836. if ($examPdf) {
  2837. $examPath = "custom_exams/{$paper->paper_id}_exam.pdf";
  2838. $examUrl = $this->pdfStorageService->put($examPath, $examPdf);
  2839. $result['pdf_url'] = $examUrl;
  2840. Log::info('试卷PDF生成成功', ['url' => $examUrl]);
  2841. }
  2842. }
  2843. // 2. 如果需要,生成判卷PDF(含答案)
  2844. if ($includeGrading) {
  2845. $gradingHtml = $this->renderCustomExamHtml($paper, $groupedQuestions, $student, $teacher, true);
  2846. if ($gradingHtml) {
  2847. // 【修复】使用服务端 KaTeX 预渲染 LaTeX 公式
  2848. if ($this->katexRenderer) {
  2849. $gradingHtml = $this->katexRenderer->renderHtml($gradingHtml);
  2850. }
  2851. $gradingPdf = $this->buildPdf($gradingHtml);
  2852. if ($gradingPdf) {
  2853. $gradingPath = "custom_exams/{$paper->paper_id}_grading.pdf";
  2854. $gradingUrl = $this->pdfStorageService->put($gradingPath, $gradingPdf);
  2855. $result['grading_pdf_url'] = $gradingUrl;
  2856. Log::info('判卷PDF生成成功', ['url' => $gradingUrl]);
  2857. }
  2858. }
  2859. }
  2860. return $result;
  2861. } catch (\Throwable $e) {
  2862. Log::error('generateByQuestions 失败', [
  2863. 'paper_id' => $paper->paper_id,
  2864. 'error' => $e->getMessage(),
  2865. 'trace' => $e->getTraceAsString(),
  2866. ]);
  2867. throw $e;
  2868. }
  2869. }
  2870. /**
  2871. * 题目质检专用 PDF:固定使用判题卡体系模板(答案详解 + 判题卡)。
  2872. * 不进入正常组卷流程,仅用于检查题干、答案、解题思路渲染效果。
  2873. *
  2874. * @return array{pdf_url?: string}
  2875. */
  2876. public function generateQuestionCheckPdf(
  2877. object $paper,
  2878. array $groupedQuestions,
  2879. array $student = [],
  2880. array $teacher = []
  2881. ): array {
  2882. Log::info('generateQuestionCheckPdf 开始', [
  2883. 'paper_id' => $paper->paper_id ?? null,
  2884. 'question_counts' => [
  2885. 'choice' => count($groupedQuestions['choice'] ?? []),
  2886. 'fill' => count($groupedQuestions['fill'] ?? []),
  2887. 'answer' => count($groupedQuestions['answer'] ?? []),
  2888. ],
  2889. ]);
  2890. $studentName = $student['name'] ?? ($paper->student_id ?? '________');
  2891. $examCode = \App\Support\PaperNaming::extractExamCode((string) ($paper->paper_id ?? 'custom'));
  2892. $pdfMeta = [
  2893. 'student_name' => $studentName,
  2894. 'exam_code' => $examCode,
  2895. 'assemble_type_label' => '题目质检',
  2896. 'header_title' => $examCode,
  2897. 'exam_pdf_title' => '题目质检_'.$examCode,
  2898. 'grading_pdf_title' => '题目质检_'.$examCode,
  2899. 'knowledge_pdf_title' => '题目质检_'.$examCode,
  2900. ];
  2901. try {
  2902. // 固定走题目质检专用模板:题干+答案+解题思路 + 判题卡附页
  2903. $html = view('pdf.question-check', [
  2904. 'paper' => $paper,
  2905. 'questions' => $groupedQuestions,
  2906. 'student' => $student,
  2907. 'teacher' => $teacher,
  2908. 'pdfMeta' => $pdfMeta,
  2909. ])->render();
  2910. if (empty(trim($html))) {
  2911. Log::error('generateQuestionCheckPdf: HTML 渲染为空', [
  2912. 'paper_id' => $paper->paper_id ?? null,
  2913. ]);
  2914. return [];
  2915. }
  2916. if ($this->katexRenderer) {
  2917. $html = $this->katexRenderer->renderHtml($html);
  2918. }
  2919. $pdfBinary = $this->buildPdf($this->ensureUtf8Html($html));
  2920. if (empty($pdfBinary)) {
  2921. Log::error('generateQuestionCheckPdf: buildPdf 失败', [
  2922. 'paper_id' => $paper->paper_id ?? null,
  2923. ]);
  2924. return [];
  2925. }
  2926. $path = 'custom_exams/'.($paper->paper_id ?? ('custom_'.time())).'.pdf';
  2927. $url = $this->pdfStorageService->put($path, $pdfBinary);
  2928. if (! $url) {
  2929. Log::error('generateQuestionCheckPdf: 上传失败', [
  2930. 'paper_id' => $paper->paper_id ?? null,
  2931. 'path' => $path,
  2932. ]);
  2933. return [];
  2934. }
  2935. return [
  2936. 'pdf_url' => $url,
  2937. 'grading_pdf_url' => $url,
  2938. ];
  2939. } catch (\Throwable $e) {
  2940. Log::error('generateQuestionCheckPdf 失败', [
  2941. 'paper_id' => $paper->paper_id ?? null,
  2942. 'error' => $e->getMessage(),
  2943. 'trace' => $e->getTraceAsString(),
  2944. ]);
  2945. throw $e;
  2946. }
  2947. }
  2948. /**
  2949. * 渲染自定义题目的HTML
  2950. */
  2951. private function renderCustomExamHtml(
  2952. object $paper,
  2953. array $groupedQuestions,
  2954. array $student,
  2955. array $teacher,
  2956. bool $grading
  2957. ): ?string {
  2958. try {
  2959. $viewName = $this->resolveExamViewName($grading);
  2960. $html = view($viewName, [
  2961. 'paper' => $paper,
  2962. 'questions' => $groupedQuestions,
  2963. 'student' => $student,
  2964. 'teacher' => $teacher,
  2965. 'grading' => $grading,
  2966. 'includeAnswer' => false, // exam-paper 视图需要这个变量
  2967. ])->render();
  2968. if (empty(trim($html))) {
  2969. Log::error('renderCustomExamHtml: 视图渲染结果为空', [
  2970. 'paper_id' => $paper->paper_id,
  2971. 'view_name' => $viewName,
  2972. ]);
  2973. return null;
  2974. }
  2975. return $this->ensureUtf8Html($html);
  2976. } catch (\Exception $e) {
  2977. Log::error('renderCustomExamHtml 失败', [
  2978. 'paper_id' => $paper->paper_id,
  2979. 'error' => $e->getMessage(),
  2980. 'trace' => $e->getTraceAsString(),
  2981. ]);
  2982. return null;
  2983. }
  2984. }
  2985. private function resolveExamViewName(bool $useGradingView): string
  2986. {
  2987. if (! $useGradingView) {
  2988. return 'pdf.exam-paper';
  2989. }
  2990. return config('exam.pdf_grading_append_scan_sheet', false)
  2991. ? 'pdf.exam-answer-detail'
  2992. : 'pdf.exam-grading';
  2993. }
  2994. private function normalizeAnswerFieldForPdf(object $question): object
  2995. {
  2996. $normalizedQuestion = clone $question;
  2997. // 以 paper_questions.question_text 为标准题干字段,兼容旧链路 content。
  2998. $questionText = trim((string) ($normalizedQuestion->question_text ?? ''));
  2999. if ($questionText === '') {
  3000. $questionText = trim((string) ($normalizedQuestion->content ?? ''));
  3001. }
  3002. if ($questionText !== '') {
  3003. $normalizedQuestion->question_text = $questionText;
  3004. $normalizedQuestion->content = $questionText;
  3005. }
  3006. $answerText = trim((string) ($normalizedQuestion->answer ?? ''));
  3007. if ($answerText !== '') {
  3008. return $normalizedQuestion;
  3009. }
  3010. foreach (['correct_answer', 'standard_answer', 'reference_answer'] as $fallbackField) {
  3011. $candidate = trim((string) ($normalizedQuestion->{$fallbackField} ?? ''));
  3012. if ($candidate !== '') {
  3013. $normalizedQuestion->answer = $candidate;
  3014. break;
  3015. }
  3016. }
  3017. return $normalizedQuestion;
  3018. }
  3019. /**
  3020. * 生成预览 PDF(用于题目预览验证工具)
  3021. *
  3022. * @param array $questionData 题目数据 ['stem', 'options', 'answer', 'solution', 'question_type']
  3023. * @return array|null 返回 ['url' => '...'] 或 null
  3024. */
  3025. public function generatePreviewPdf(array $questionData): ?array
  3026. {
  3027. try {
  3028. Log::info('generatePreviewPdf 开始', ['question_data' => $questionData]);
  3029. // 渲染 HTML
  3030. $html = $this->renderPreviewHtml($questionData);
  3031. if (empty($html)) {
  3032. Log::error('generatePreviewPdf: HTML 渲染为空');
  3033. return null;
  3034. }
  3035. // 生成 PDF
  3036. $pdfContent = $this->buildPdf($html);
  3037. if (empty($pdfContent)) {
  3038. Log::error('generatePreviewPdf: PDF 生成为空');
  3039. return null;
  3040. }
  3041. // 保存到临时目录
  3042. $filename = 'preview_'.uniqid().'.pdf';
  3043. $path = "previews/{$filename}";
  3044. $url = $this->pdfStorageService->put($path, $pdfContent);
  3045. Log::info('generatePreviewPdf 成功', ['url' => $url]);
  3046. return ['url' => $url];
  3047. } catch (\Exception $e) {
  3048. Log::error('generatePreviewPdf 失败', [
  3049. 'error' => $e->getMessage(),
  3050. 'trace' => $e->getTraceAsString(),
  3051. ]);
  3052. return null;
  3053. }
  3054. }
  3055. /**
  3056. * 渲染预览 HTML
  3057. */
  3058. private function renderPreviewHtml(array $questionData): string
  3059. {
  3060. $stem = $questionData['stem'] ?? '';
  3061. $options = $questionData['options'] ?? null;
  3062. $answer = $questionData['answer'] ?? '';
  3063. $solution = $questionData['solution'] ?? '';
  3064. $questionType = $questionData['question_type'] ?? 'fill';
  3065. // 使用 MathFormulaProcessor 处理公式
  3066. $processedStem = MathFormulaProcessor::processFormulas($stem);
  3067. $processedAnswer = MathFormulaProcessor::processFormulas($answer);
  3068. $processedSolution = MathFormulaProcessor::processFormulas($this->formatNewlines($solution));
  3069. $processedOptions = null;
  3070. if ($options && is_array($options)) {
  3071. $processedOptions = [];
  3072. foreach ($options as $key => $value) {
  3073. $processedOptions[$key] = MathFormulaProcessor::processFormulas($value);
  3074. }
  3075. }
  3076. // 渲染 HTML
  3077. return view('pdf.question-preview', [
  3078. 'stem' => $processedStem,
  3079. 'options' => $processedOptions,
  3080. 'answer' => $processedAnswer,
  3081. 'solution' => $processedSolution,
  3082. 'questionType' => $questionType,
  3083. ])->render();
  3084. }
  3085. /**
  3086. * 批量获取知识点的讲解内容
  3087. *
  3088. * @param array $kpCodes 知识点代码数组
  3089. * @return array [kp_code => explanation]
  3090. */
  3091. public function buildExplanations(array $kpCodes): array
  3092. {
  3093. $result = [];
  3094. if (empty($kpCodes)) {
  3095. return $result;
  3096. }
  3097. try {
  3098. // 批量获取知识点讲解
  3099. $kps = \App\Models\KnowledgePoint::whereIn('kp_code', $kpCodes)->get()->keyBy('kp_code');
  3100. // 有多少算多少
  3101. foreach ($kpCodes as $kpCode) {
  3102. $kp = $kps->get($kpCode);
  3103. if ($kp && ! empty($kp->explanation)) {
  3104. $result[] = [
  3105. 'kp_code' => $kpCode,
  3106. 'kp_name' => $kp->name ?? $kpCode,
  3107. 'explanation' => $this->normalizeKpExplanation($kp->explanation),
  3108. ];
  3109. continue;
  3110. }
  3111. $result[] = [
  3112. 'kp_code' => $kpCode,
  3113. 'kp_name' => $kp->name ?? $kpCode,
  3114. 'explanation' => $this->normalizeKpExplanation(
  3115. $this->getDefaultExplanation($kpCode, $kp->name ?? $kpCode)
  3116. ),
  3117. ];
  3118. }
  3119. } catch (\Throwable $e) {
  3120. Log::warning('批量获取知识点讲解失败', [
  3121. 'kp_codes' => $kpCodes,
  3122. 'error' => $e->getMessage(),
  3123. ]);
  3124. // 失败时返回默认内容
  3125. foreach ($kpCodes as $kpCode) {
  3126. $result[] = [
  3127. 'kp_code' => $kpCode,
  3128. 'kp_name' => $kpCode,
  3129. 'explanation' => $this->normalizeKpExplanation(
  3130. $this->getDefaultExplanation($kpCode, $kpCode)
  3131. ),
  3132. ];
  3133. }
  3134. }
  3135. return $result;
  3136. }
  3137. /**
  3138. * 获取默认的知识点讲解内容
  3139. */
  3140. private function getDefaultExplanation(string $kpCode, string $kpName): string
  3141. {
  3142. // 默认讲解模板
  3143. // 注意:PHP HEREDOC 中 \e 会被解释为 ESC 字符,所以需要用 \\end 而非 \end
  3144. return <<<'MARKDOWN'
  3145. ## 知识点
  3146. (1) 核心定义:二元一次方程是含有两个未知数且每个未知数的次数都是 1 的方程,一般形式为 $ax + by = c$(其中 $a,b,c$ 为常数,且 $a,b$ 不同时为 0)。二元一次方程组是由两个(或两个以上)二元一次方程组成,常见为
  3147. $$
  3148. \begin{cases}
  3149. a_1x + b_1y = c_1\\
  3150. a_2x + b_2y = c_2
  3151. \end{cases}
  3152. $$
  3153. 方程组应用建模就是把题目中的数量关系翻译成方程组,通过求解得到实际问题的答案。
  3154. (2) 性质定理:方程组的解必须同时满足方程组中的每一个方程,因此解是两个方程公共的 $(x,y)$。常用解法有代入消元法与加减消元法:代入消元法适合某个方程易表示成 $x = \dots$ 或 $y = \dots$;加减消元法适合两个方程中某个未知数的系数相同或相反,便于相加或相减消去一个未知数。建模时常用关系包括:总量关系(如“总数 = 部分之和”)、单价数量总价关系(“$总价 = 单价 \times 数量$”)、路程速度时间关系($路程 = 速度 \times 时间$)等。
  3155. (3) 注意事项:设未知数要带单位与含义,例如“设甲买了 $x$ 支笔”;列方程要对应同一类量,别把“支数”和“元数”混在一条等式里;检查条件是否满足题意(如数量应为整数且 $> 0$);消元后别忘了回代求另一个未知数;最后答案要写清对象与单位,并可把解代回原式检验。
  3156. ## 知识点应用
  3157. - 典型例题:文具店买笔和本子。小明买了 2 支笔和 3 本本子共花 19 元;小红买了 3 支笔和 2 本本子共花 18 元。求每支笔和每本本子的单价。
  3158. - 关键步骤:
  3159. 1. 设未知数并写出含义:设每支笔单价为 $x$ 元,每本本子单价为 $y$ 元。
  3160. 2. 根据题意列方程组:由“$总价 = 单价 \times 数量$”得
  3161. $$
  3162. \begin{cases}
  3163. 2x + 3y = 19\\
  3164. 3x + 2y = 18
  3165. \end{cases}
  3166. $$
  3167. 3. 选择消元并求解:用加减消元。将第一式乘 3、第二式乘 2:
  3168. $$
  3169. \begin{cases}
  3170. 6x + 9y = 57\\
  3171. 6x + 4y = 36
  3172. \end{cases}
  3173. $$
  3174. 相减得 $5y = 21$,所以 $y = \dfrac{21}{5} = 4.2$。代入 $3x + 2y = 18$ 得 $3x + 8.4 = 18$,所以 $3x = 9.6$,$x = 3.2$。
  3175. - 结论:每支笔 3.2 元,每本本子 4.2 元(两者均 $> 0$,符合题意)。
  3176. MARKDOWN;
  3177. }
  3178. private function normalizeKpExplanation(string $content): string
  3179. {
  3180. $content = trim($content);
  3181. if ($content === '') {
  3182. return '';
  3183. }
  3184. if ($this->looksLikeHtml($content)) {
  3185. return $content;
  3186. }
  3187. if (! class_exists(\Michelf\MarkdownExtra::class)) {
  3188. $safe = htmlspecialchars($content, ENT_QUOTES, 'UTF-8');
  3189. return '<div class="kp-markdown-container kp-markdown-content">'.nl2br($safe).'</div>';
  3190. }
  3191. $parser = new \Michelf\MarkdownExtra;
  3192. $markdown = html_entity_decode($content, ENT_QUOTES, 'UTF-8');
  3193. $rendered = $parser->transform($markdown);
  3194. return '<div class="kp-markdown-container kp-markdown-content">'.$rendered.'</div>';
  3195. }
  3196. private function looksLikeHtml(string $content): bool
  3197. {
  3198. if (stripos($content, 'kp-markdown-container') !== false ||
  3199. stripos($content, 'kp-markdown-content') !== false) {
  3200. return true;
  3201. }
  3202. return (bool) preg_match('/<\s*(p|div|h[1-6]|ul|ol|li|table|span|blockquote|pre|code|br)\b/i', $content);
  3203. }
  3204. private function shouldUseDefaultExplanations(): bool
  3205. {
  3206. if (!Schema::hasTable('knowledge_points')) {
  3207. return true;
  3208. }
  3209. return !Schema::hasColumn('knowledge_points', 'explanation');
  3210. }
  3211. }