ExamPdfExportService.php 131 KB

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