ExamPdfExportService.php 128 KB

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