ExamPdfExportService.php 143 KB

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