ExamPdfExportService.php 120 KB

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