ExamPdfExportService.php 112 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904
  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. if (! empty($analysisData['knowledge_point_analysis'])) {
  647. // 将knowledge_point_analysis转换为buildMasterySummary期望的格式
  648. foreach ($analysisData['knowledge_point_analysis'] as $kp) {
  649. $masteryData[] = [
  650. 'kp_code' => $kp['kp_id'] ?? null,
  651. 'kp_name' => $kp['kp_id'] ?? '未知知识点',
  652. 'mastery_level' => $kp['mastery_level'] ?? 0,
  653. 'mastery_change' => $kp['change'] ?? null,
  654. ];
  655. }
  656. // 【修复】基于所有兄弟节点历史数据计算父节点掌握度,并获取掌握度变化
  657. try {
  658. // 获取本次考试涉及的知识点代码列表
  659. $examKpCodes = array_column($masteryData, 'kp_code');
  660. Log::info('ExamPdfExportService: 本次考试涉及的知识点', [
  661. 'count' => count($examKpCodes),
  662. 'kp_codes' => $examKpCodes,
  663. ]);
  664. // 获取最新快照的数据(mastery_data 内已包含 current_mastery 和 previous_mastery)
  665. $lastSnapshot = DB::connection('mysql')
  666. ->table('knowledge_point_mastery_snapshots')
  667. ->where('student_id', $studentId)
  668. ->where('paper_id', $paper->paper_id)
  669. ->latest('snapshot_time')
  670. ->first();
  671. $previousMasteryData = [];
  672. $snapshotMasteryData = [];
  673. if ($lastSnapshot) {
  674. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  675. foreach ($previousMasteryJson as $kpCode => $data) {
  676. $snapshotMasteryData[$kpCode] = [
  677. 'current_mastery' => isset($data['current_mastery']) ? floatval($data['current_mastery']) : null,
  678. 'previous_mastery' => isset($data['previous_mastery']) ? floatval($data['previous_mastery']) : null,
  679. 'change' => isset($data['change']) ? floatval($data['change']) : null,
  680. ];
  681. $previousMasteryData[$kpCode] = [
  682. 'current_mastery' => $data['current_mastery'] ?? 0,
  683. 'previous_mastery' => $data['previous_mastery'] ?? null,
  684. ];
  685. }
  686. Log::info('ExamPdfExportService: 获取到上一次快照数据', [
  687. 'snapshot_time' => $lastSnapshot->snapshot_time,
  688. 'kp_count' => count($previousMasteryData),
  689. ]);
  690. }
  691. // 为当前知识点添加变化数据
  692. foreach ($masteryData as &$item) {
  693. $kpCode = $item['kp_code'];
  694. if (isset($previousMasteryData[$kpCode]) && $previousMasteryData[$kpCode]['previous_mastery'] !== null) {
  695. $previous = floatval($previousMasteryData[$kpCode]['previous_mastery']);
  696. $current = floatval($item['mastery_level']);
  697. $item['mastery_change'] = $current - $previous;
  698. }
  699. }
  700. unset($item); // 解除引用
  701. // 获取所有父节点掌握度
  702. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  703. $allParentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? [];
  704. $overviewDetails = $masteryOverview['details'] ?? [];
  705. foreach ($overviewDetails as $detail) {
  706. if (is_object($detail)) {
  707. $code = $detail->kp_code ?? null;
  708. if ($code) {
  709. $fullMasteryMap[$code] = floatval($detail->mastery_level ?? 0);
  710. }
  711. } elseif (is_array($detail)) {
  712. $code = $detail['kp_code'] ?? null;
  713. if ($code) {
  714. $fullMasteryMap[$code] = floatval($detail['mastery_level'] ?? 0);
  715. }
  716. }
  717. }
  718. // 计算与本次考试相关的父节点掌握度(基于所有兄弟节点)
  719. $parentMasteryLevels = [];
  720. // 【修复】使用数据库查询正确匹配父子关系,而不是字符串前缀
  721. foreach ($allParentMasteryLevels as $parentKpCode => $parentMastery) {
  722. // 查询这个父节点的所有子节点
  723. $childNodes = DB::connection('mysql')
  724. ->table('knowledge_points')
  725. ->where('parent_kp_code', $parentKpCode)
  726. ->pluck('kp_code')
  727. ->toArray();
  728. // 检查是否有子节点在本次考试中出现
  729. $relevantChildren = array_intersect($examKpCodes, $childNodes);
  730. if (! empty($relevantChildren)) {
  731. // 父节点变化值优先使用父节点自身快照(与父节点当前值同口径)
  732. $parentCurrentFromSnapshot = $snapshotMasteryData[$parentKpCode]['current_mastery'] ?? null;
  733. $parentPreviousFromSnapshot = $snapshotMasteryData[$parentKpCode]['previous_mastery'] ?? null;
  734. $parentDeltaFromSnapshot = null;
  735. if ($parentCurrentFromSnapshot !== null && $parentPreviousFromSnapshot !== null) {
  736. $parentDeltaFromSnapshot = floatval($parentCurrentFromSnapshot) - floatval($parentPreviousFromSnapshot);
  737. }
  738. // 次级兜底:若父节点快照缺失,才退回“命中子节点变化均值”
  739. $childChanges = [];
  740. foreach ($relevantChildren as $childKpCode) {
  741. $previousChild = $previousMasteryData[$childKpCode]['previous_mastery'] ?? null;
  742. $currentChild = null;
  743. foreach ($masteryData as $item) {
  744. if ($item['kp_code'] === $childKpCode) {
  745. $currentChild = $item['mastery_level'];
  746. break;
  747. }
  748. }
  749. if ($previousChild !== null && $currentChild !== null) {
  750. $childChanges[] = floatval($currentChild) - floatval($previousChild);
  751. }
  752. }
  753. $avgChildChange = ! empty($childChanges) ? array_sum($childChanges) / count($childChanges) : null;
  754. $finalParentChange = $parentDeltaFromSnapshot ?? $avgChildChange;
  755. $finalParentMastery = $parentCurrentFromSnapshot ?? $parentMastery;
  756. // 获取父节点中文名称
  757. $parentKpInfo = DB::connection('mysql')
  758. ->table('knowledge_points')
  759. ->where('kp_code', $parentKpCode)
  760. ->first();
  761. $parentMasteryLevels[$parentKpCode] = [
  762. 'kp_code' => $parentKpCode,
  763. 'kp_name' => $parentKpInfo->name ?? $parentKpCode,
  764. 'mastery_level' => $finalParentMastery,
  765. 'mastery_percentage' => round($finalParentMastery * 100, 1),
  766. 'mastery_change' => $finalParentChange,
  767. 'change_source' => $parentDeltaFromSnapshot !== null ? 'parent_snapshot' : 'children_average',
  768. 'children' => $relevantChildren,
  769. ];
  770. }
  771. }
  772. Log::info('ExamPdfExportService: 过滤后的父节点掌握度', [
  773. 'all_parent_count' => count($allParentMasteryLevels),
  774. 'filtered_parent_count' => count($parentMasteryLevels),
  775. 'filtered_codes' => array_keys($parentMasteryLevels),
  776. ]);
  777. } catch (\Exception $e) {
  778. Log::warning('ExamPdfExportService: 获取父节点掌握度失败', [
  779. 'error' => $e->getMessage(),
  780. ]);
  781. }
  782. Log::info('ExamPdfExportService: 使用analysisData中的掌握度数据', [
  783. 'count' => count($masteryData),
  784. 'masteryData_sample' => ! empty($masteryData) ? array_slice($masteryData, 0, 2) : [],
  785. ]);
  786. } else {
  787. // 如果没有knowledge_point_analysis,使用MasteryCalculator获取多层级掌握度概览
  788. try {
  789. Log::info('ExamPdfExportService: 获取学生多层级掌握度概览', [
  790. 'student_id' => $studentId,
  791. ]);
  792. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  793. $masteryData = $masteryOverview['details'] ?? [];
  794. $parentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? []; // 获取父节点掌握度
  795. // 【修复】将对象数组转换为关联数组(避免 stdClass 对象访问错误)
  796. if (! empty($masteryData) && is_array($masteryData)) {
  797. $masteryData = array_map(function ($item) {
  798. if (is_object($item)) {
  799. $kpCode = $item->kp_code ?? null;
  800. return [
  801. 'kp_code' => $kpCode,
  802. 'kp_name' => $item->kp_name ?? null,
  803. 'mastery_level' => floatval($item->mastery_level ?? 0),
  804. 'mastery_change' => $item->mastery_change !== null ? floatval($item->mastery_change) : null,
  805. ];
  806. }
  807. return $item;
  808. }, $masteryData);
  809. }
  810. foreach ($masteryData as $m) {
  811. $code = $m['kp_code'] ?? null;
  812. if ($code) {
  813. $fullMasteryMap[$code] = floatval($m['mastery_level'] ?? 0);
  814. }
  815. }
  816. // 【修复】获取快照数据以计算掌握度变化
  817. $lastSnapshot = DB::connection('mysql')
  818. ->table('knowledge_point_mastery_snapshots')
  819. ->where('student_id', $studentId)
  820. ->latest('snapshot_time')
  821. ->first();
  822. if ($lastSnapshot) {
  823. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  824. foreach ($masteryData as &$item) {
  825. $kpCode = $item['kp_code'];
  826. if (isset($previousMasteryJson[$kpCode])) {
  827. $previous = floatval($previousMasteryJson[$kpCode]['previous_mastery'] ?? 0);
  828. $current = floatval($item['mastery_level']);
  829. $item['mastery_change'] = $current - $previous;
  830. }
  831. }
  832. unset($item);
  833. }
  834. Log::info('ExamPdfExportService: 成功获取多层级掌握度数据', [
  835. 'count' => count($masteryData),
  836. 'parent_count' => count($parentMasteryLevels),
  837. ]);
  838. } catch (\Exception $e) {
  839. Log::error('ExamPdfExportService: 获取掌握度数据失败', [
  840. 'student_id' => $studentId,
  841. 'error' => $e->getMessage(),
  842. ]);
  843. }
  844. }
  845. // 【修改】使用本地方法获取学习路径推荐(替代API调用)
  846. $recommendations = [];
  847. try {
  848. Log::info('ExamPdfExportService: 获取学习路径推荐', [
  849. 'student_id' => $studentId,
  850. ]);
  851. $learningPaths = $this->learningAnalyticsService->recommendLearningPaths($studentId, 3);
  852. $recommendations = $learningPaths['recommendations'] ?? [];
  853. Log::info('ExamPdfExportService: 成功获取学习路径推荐', [
  854. 'count' => count($recommendations),
  855. ]);
  856. } catch (\Exception $e) {
  857. Log::error('ExamPdfExportService: 获取学习路径推荐失败', [
  858. 'student_id' => $studentId,
  859. 'error' => $e->getMessage(),
  860. ]);
  861. }
  862. // 获取知识点名称映射
  863. $kpNameMap = $this->buildKnowledgePointNameMap();
  864. Log::info('ExamPdfExportService: 获取知识点名称映射', [
  865. 'kpNameMap_count' => count($kpNameMap),
  866. 'kpNameMap_keys_sample' => ! empty($kpNameMap) ? array_slice(array_keys($kpNameMap), 0, 5) : [],
  867. ]);
  868. // 【修复】直接从MySQL数据库获取题目详情(不通过API)
  869. // 只有当 $paper 是 Paper 模型时才查询题目详情
  870. $questionDetails = ($paper instanceof \App\Models\Paper)
  871. ? $this->getQuestionDetailsFromMySQL($paper)
  872. : [];
  873. // 处理题目数据
  874. $questions = $this->processQuestionsForReport($paper, $questionDetails, $kpNameMap);
  875. // 【关键调试】查看buildMasterySummary的返回结果
  876. $masterySummary = $this->buildMasterySummary($masteryData, $kpNameMap);
  877. Log::info('ExamPdfExportService: buildMasterySummary返回结果', [
  878. 'masteryData_count' => count($masteryData),
  879. 'kpNameMap_count' => count($kpNameMap),
  880. 'masterySummary_keys' => array_keys($masterySummary),
  881. 'masterySummary_items_count' => count($masterySummary['items'] ?? []),
  882. 'masterySummary_items_sample' => ! empty($masterySummary['items']) ? array_slice($masterySummary['items'], 0, 2) : [],
  883. ]);
  884. // 构建当前学生掌握度映射,供父子影响分析展示使用
  885. $masteryMap = !empty($fullMasteryMap) ? $fullMasteryMap : [];
  886. if (empty($masteryMap)) {
  887. foreach ($masteryData as $m) {
  888. $code = $m['kp_code'] ?? null;
  889. if ($code) {
  890. $masteryMap[$code] = floatval($m['mastery_level'] ?? 0);
  891. }
  892. }
  893. }
  894. // 【修复】处理父节点掌握度数据:过滤零值、转换名称、构建层级关系
  895. $examKpCodes = array_column($masteryData, 'kp_code'); // 本次考试涉及的知识点
  896. $processedParentMastery = $this->processParentMasteryLevels($parentMasteryLevels, $kpNameMap, $examKpCodes, $masteryMap);
  897. Log::info('ExamPdfExportService: 处理后的父节点掌握度', [
  898. 'raw_count' => count($parentMasteryLevels),
  899. 'processed_count' => count($processedParentMastery),
  900. 'processed_sample' => ! empty($processedParentMastery) ? array_slice($processedParentMastery, 0, 3) : [],
  901. ]);
  902. return [
  903. 'paper' => [
  904. 'id' => $paper->paper_id,
  905. 'name' => $paper->paper_name,
  906. 'paper_type' => $paper->paper_type,
  907. 'assemble_type_label' => $assembleTypeLabel,
  908. 'total_questions' => $paper->question_count,
  909. 'total_score' => $paper->total_score,
  910. 'created_at' => $paper->created_at,
  911. ],
  912. 'student' => $studentInfo,
  913. 'teacher' => $teacherInfo,
  914. 'questions' => $questions,
  915. 'mastery' => $masterySummary,
  916. 'parent_mastery_levels' => $processedParentMastery, // 【修复】使用处理后的父节点数据
  917. 'insights' => $analysisData['question_analysis'] ?? [], // 使用question_analysis替代question_results
  918. 'recommendations' => $recommendations,
  919. 'analysis_data' => $analysisData,
  920. ];
  921. }
  922. /**
  923. * 【修复】直接从PaperQuestion表获取题目详情(不通过API)
  924. */
  925. private function getQuestionDetailsFromMySQL(Paper $paper): array
  926. {
  927. $details = [];
  928. Log::info('ExamPdfExportService: 从PaperQuestion表查询题目详情', [
  929. 'paper_id' => $paper->paper_id,
  930. 'question_count' => $paper->questions->count(),
  931. ]);
  932. foreach ($paper->questions as $pq) {
  933. try {
  934. // 【关键修复】直接从PaperQuestion对象获取solution和correct_answer
  935. $detail = [
  936. 'id' => $pq->question_id,
  937. 'content' => $pq->question_text,
  938. 'question_type' => $pq->question_type,
  939. 'answer' => $pq->correct_answer ?? null, // 【修复】从PaperQuestion获取正确答案
  940. 'solution' => $pq->solution ?? null, // 【修复】从PaperQuestion获取解题思路
  941. ];
  942. $details[(string) ($pq->question_id ?? $pq->id)] = $detail;
  943. Log::debug('ExamPdfExportService: 成功获取题目详情', [
  944. 'paper_question_id' => $pq->id,
  945. 'question_id' => $pq->question_id,
  946. 'has_answer' => ! empty($pq->correct_answer),
  947. 'has_solution' => ! empty($pq->solution),
  948. 'answer_preview' => $pq->correct_answer ? substr($pq->correct_answer, 0, 50) : null,
  949. ]);
  950. } catch (\Throwable $e) {
  951. Log::error('ExamPdfExportService: 获取题目详情失败', [
  952. 'paper_question_id' => $pq->id,
  953. 'error' => $e->getMessage(),
  954. ]);
  955. }
  956. }
  957. return $details;
  958. }
  959. /**
  960. * 处理题目数据(用于报告)
  961. */
  962. private function processQuestionsForReport($paper, array $questionDetails, array $kpNameMap): array
  963. {
  964. $grouped = [
  965. 'choice' => [],
  966. 'fill' => [],
  967. 'answer' => [],
  968. ];
  969. // 【修复】处理空的试卷(questions可能不存在)
  970. $questions = $paper->questions ?? collect();
  971. if ($questions->isEmpty()) {
  972. Log::info('ExamPdfExportService: 试卷没有题目,返回空数组');
  973. return $grouped;
  974. }
  975. $sortedQuestions = $questions
  976. ->sortBy(function ($q, int $idx) {
  977. $number = $q->question_number ?? $idx + 1;
  978. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  979. });
  980. foreach ($sortedQuestions as $idx => $question) {
  981. $kpCode = $question->knowledge_point ?? '';
  982. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  983. // 【修复】直接从PaperQuestion对象获取solution和correct_answer
  984. $answer = $question->correct_answer ?? null; // 直接从PaperQuestion获取
  985. $solution = $question->solution ?? null; // 直接从PaperQuestion获取
  986. $detail = $questionDetails[(string) ($question->question_id ?? $question->id)] ?? [];
  987. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  988. $normalizedType = $this->normalizeQuestionType($typeRaw);
  989. $number = $question->question_number ?? ($idx + 1);
  990. // 处理题干文本
  991. $questionText = is_array($question->question_text)
  992. ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
  993. : ($question->question_text ?? '');
  994. $payload = [
  995. 'question_id' => $question->question_id ?? null,
  996. 'question_bank_id' => $question->question_bank_id ?? $question->question_id ?? null,
  997. 'question_number' => $number,
  998. 'question_text' => $this->formatNewlines($questionText), // 格式化换行
  999. 'question_type' => $normalizedType,
  1000. 'knowledge_point' => $kpCode,
  1001. 'knowledge_point_name' => $kpName,
  1002. 'score' => $question->score,
  1003. 'answer' => $this->formatNewlines($answer), // 格式化换行
  1004. 'solution' => $this->formatNewlines($solution), // 格式化换行
  1005. 'student_answer' => $this->formatNewlines($question->student_answer ?? null), // 格式化换行
  1006. 'correct_answer' => $this->formatNewlines($answer), // 格式化换行
  1007. 'is_correct' => $question->is_correct ?? null,
  1008. 'score_obtained' => $question->score_obtained ?? null,
  1009. ];
  1010. $grouped[$normalizedType][] = $payload;
  1011. // 【调试】记录题目数据
  1012. Log::debug('ExamPdfExportService: 处理题目数据', [
  1013. 'paper_question_id' => $question->id,
  1014. 'question_id' => $question->question_id,
  1015. 'has_answer' => ! empty($answer),
  1016. 'has_solution' => ! empty($solution),
  1017. 'answer_preview' => $answer ? substr($answer, 0, 50) : null,
  1018. ]);
  1019. }
  1020. $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  1021. // 按卷面顺序重新编号
  1022. foreach ($ordered as $i => &$q) {
  1023. $q['display_number'] = $i + 1;
  1024. }
  1025. unset($q);
  1026. return $ordered;
  1027. }
  1028. /**
  1029. * 构建PDF
  1030. */
  1031. private function buildPdf(string $html): ?string
  1032. {
  1033. $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_').'.html';
  1034. $utf8Html = $this->ensureUtf8Html($html);
  1035. $written = file_put_contents($tmpHtml, $utf8Html);
  1036. Log::debug('ExamPdfExportService: HTML文件已创建', [
  1037. 'path' => $tmpHtml,
  1038. 'html_length' => strlen($utf8Html),
  1039. 'written_bytes' => $written,
  1040. ]);
  1041. // 【调试】如果启用了HTML保存调试,复制HTML到storage用于分析
  1042. if (config('pdf.debug_save_html', false)) {
  1043. $debugPath = storage_path('app/debug_pdf_'.date('YmdHis').'.html');
  1044. @copy($tmpHtml, $debugPath);
  1045. Log::warning('ExamPdfExportService: [DEBUG] HTML副本已保存', ['path' => $debugPath]);
  1046. }
  1047. // 仅使用Chrome渲染
  1048. $chromePdf = $this->renderWithChrome($tmpHtml);
  1049. @unlink($tmpHtml);
  1050. return $chromePdf;
  1051. }
  1052. /**
  1053. * 使用Chrome渲染PDF
  1054. */
  1055. private function renderWithChrome(string $htmlPath): ?string
  1056. {
  1057. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_').'.pdf';
  1058. $userDataDir = sys_get_temp_dir().'/chrome-profile-'.uniqid();
  1059. $chromeBinary = $this->findChromeBinary();
  1060. if (! $chromeBinary) {
  1061. Log::error('ExamPdfExportService: 未找到可用的Chrome/Chromium');
  1062. return null;
  1063. }
  1064. // 设置运行时目录
  1065. $runtimeHome = sys_get_temp_dir().'/chrome-home';
  1066. $runtimeXdg = sys_get_temp_dir().'/chrome-xdg';
  1067. if (! File::exists($runtimeHome)) {
  1068. @File::makeDirectory($runtimeHome, 0755, true);
  1069. }
  1070. if (! File::exists($runtimeXdg)) {
  1071. @File::makeDirectory($runtimeXdg, 0755, true);
  1072. }
  1073. $process = new Process([
  1074. $chromeBinary,
  1075. '--headless=new', // 【优化】使用新渲染引擎
  1076. '--disable-gpu',
  1077. '--no-sandbox',
  1078. '--disable-setuid-sandbox',
  1079. '--disable-dev-shm-usage',
  1080. '--disable-web-security',
  1081. '--disable-features=VizDisplayCompositor',
  1082. '--disable-extensions',
  1083. // '--disable-background-networking', // 注释掉,可能阻止必要的网络请求
  1084. '--disable-component-update',
  1085. '--disable-client-side-phishing-detection',
  1086. '--disable-default-apps',
  1087. '--disable-domain-reliability',
  1088. '--disable-sync',
  1089. '--no-first-run',
  1090. '--no-default-browser-check',
  1091. '--disable-crash-reporter',
  1092. '--disable-print-preview',
  1093. '--disable-features=TranslateUI',
  1094. '--disable-features=OptimizationHints',
  1095. '--disable-ipc-flooding-protection',
  1096. '--disable-background-timer-throttling',
  1097. '--disable-backgrounding-occluded-windows',
  1098. '--disable-renderer-backgrounding',
  1099. '--disable-features=AudioServiceOutOfProcess',
  1100. '--disable-gpu-sandbox',
  1101. '--disable-software-rasterizer',
  1102. '--disable-background-mode',
  1103. '--disable-extensions-http-throttling',
  1104. '--disable-ipc-flooding-protection',
  1105. '--disable-features=Dbus', // 禁用 dbus
  1106. // 【关键修复】添加虚拟时间预算,让Chrome有足够时间加载CDN资源和执行JS
  1107. '--virtual-time-budget=30000', // 30秒虚拟时间用于加载外部资源
  1108. '--run-all-compositor-stages-before-draw', // 确保所有渲染完成后再生成PDF
  1109. '--user-data-dir='.$userDataDir,
  1110. '--print-to-pdf='.$tmpPdf,
  1111. '--print-to-pdf-no-header',
  1112. '--allow-file-access-from-files',
  1113. '--font-render-hinting=none', // 【优化】禁用字体渲染提示
  1114. '--disable-font-antialiasing',
  1115. 'file://'.$htmlPath,
  1116. ], null, [
  1117. 'HOME' => $runtimeHome,
  1118. 'XDG_RUNTIME_DIR' => $runtimeXdg,
  1119. ]);
  1120. $process->setTimeout(90); // 【修复】增加超时时间到90秒
  1121. $killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
  1122. Log::warning('ExamPdfExportService: [调试] Chrome命令准备执行', [
  1123. 'chrome_binary' => $chromeBinary,
  1124. 'html_path' => $htmlPath,
  1125. 'html_exists' => file_exists($htmlPath),
  1126. 'html_size' => file_exists($htmlPath) ? filesize($htmlPath) : 0,
  1127. 'pdf_path' => $tmpPdf,
  1128. 'user_data_dir' => $userDataDir,
  1129. ]);
  1130. try {
  1131. $startedAt = microtime(true);
  1132. $process->start();
  1133. $pdfGenerated = false;
  1134. // 轮询检测PDF是否生成
  1135. $pollStart = microtime(true);
  1136. $maxPollSeconds = 80; // 【修复】增加轮询超时到80秒
  1137. while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
  1138. if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
  1139. $pdfGenerated = true;
  1140. Log::info('ExamPdfExportService: PDF生成成功,提前终止Chrome进程', [
  1141. 'elapsed' => round(microtime(true) - $startedAt, 2),
  1142. 'pdf_size' => filesize($tmpPdf),
  1143. ]);
  1144. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1145. break;
  1146. }
  1147. usleep(100_000); // 【优化】从200ms减少到100ms
  1148. }
  1149. if ($process->isRunning()) {
  1150. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1151. }
  1152. // 【优化】删除不必要的wait()调用,避免重复等待
  1153. // $process->wait();
  1154. } catch (ProcessTimedOutException|ProcessSignaledException $e) {
  1155. if ($process->isRunning()) {
  1156. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1157. }
  1158. Log::warning('ExamPdfExportService: Chrome进程超时或被信号中断', [
  1159. 'elapsed' => round((microtime(true) - $startedAt), 2),
  1160. 'exception' => get_class($e),
  1161. ]);
  1162. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
  1163. } catch (\Throwable $e) {
  1164. if ($process->isRunning()) {
  1165. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1166. }
  1167. Log::error('ExamPdfExportService: Chrome进程异常', [
  1168. 'elapsed' => round((microtime(true) - $startedAt), 2),
  1169. 'error' => $e->getMessage(),
  1170. ]);
  1171. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  1172. }
  1173. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  1174. }
  1175. /**
  1176. * 处理Chrome进程结果
  1177. */
  1178. private function handleChromeProcessResult(string $tmpPdf, string $userDataDir, Process $process, ?float $startedAt): ?string
  1179. {
  1180. $pdfExists = file_exists($tmpPdf);
  1181. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  1182. $elapsed = $startedAt ? round((microtime(true) - $startedAt), 2) : null;
  1183. // 【优化】即使进程未成功,只要PDF存在且大小合理就返回
  1184. if ($pdfExists && $pdfSize > 1000) { // 至少1KB
  1185. Log::info('ExamPdfExportService: PDF生成成功', [
  1186. 'elapsed' => $elapsed,
  1187. 'pdf_size' => $pdfSize,
  1188. 'exit_code' => $process->getExitCode(),
  1189. 'is_successful' => $process->isSuccessful(),
  1190. ]);
  1191. $pdfBinary = file_get_contents($tmpPdf);
  1192. @unlink($tmpPdf);
  1193. File::deleteDirectory($userDataDir);
  1194. return $pdfBinary;
  1195. }
  1196. // 如果PDF不存在或太小,记录错误
  1197. Log::error('ExamPdfExportService: Chrome渲染失败', [
  1198. 'elapsed' => $elapsed,
  1199. 'pdf_exists' => $pdfExists,
  1200. 'pdf_size' => $pdfSize,
  1201. 'exit_code' => $process->getExitCode(),
  1202. 'error' => $process->getErrorOutput(),
  1203. 'output' => $process->getOutput(),
  1204. ]);
  1205. @unlink($tmpPdf);
  1206. File::deleteDirectory($userDataDir);
  1207. return null;
  1208. }
  1209. /**
  1210. * 查找Chrome二进制文件
  1211. */
  1212. private function findChromeBinary(): ?string
  1213. {
  1214. $candidates = [
  1215. env('PDF_CHROME_BINARY'),
  1216. env('CHROME_BIN'), // Docker Alpine 环境变量
  1217. '/usr/bin/chromium-browser', // Alpine Linux
  1218. '/usr/bin/chromium',
  1219. '/usr/bin/google-chrome-stable',
  1220. '/usr/bin/google-chrome',
  1221. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', // macOS
  1222. ];
  1223. foreach ($candidates as $path) {
  1224. if ($path && is_file($path) && is_executable($path)) {
  1225. return $path;
  1226. }
  1227. }
  1228. return null;
  1229. }
  1230. /**
  1231. * 确保HTML为UTF-8编码,并内联外部资源
  1232. */
  1233. private function ensureUtf8Html(string $html): string
  1234. {
  1235. $meta = '<meta charset="UTF-8">';
  1236. if (stripos($html, '<head>') !== false) {
  1237. $html = preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
  1238. } else {
  1239. $html = $meta.$html;
  1240. }
  1241. // 【关键修复】内联KaTeX CSS,避免Chrome在容器中加载CDN资源超时
  1242. $html = $this->inlineExternalResources($html);
  1243. return $html;
  1244. }
  1245. /**
  1246. * 将CDN资源替换为内联资源
  1247. * 【关键修复】避免Chrome在容器中加载CDN资源超时,同时支持本地路径
  1248. */
  1249. private function inlineExternalResources(string $html): string
  1250. {
  1251. // 检查是否包含 KaTeX 资源(CDN 或本地)
  1252. $hasKatexCdn = strpos($html, 'cdn.jsdelivr.net/npm/katex') !== false;
  1253. $hasKatexLocal = strpos($html, '/js/katex.min.js') !== false || strpos($html, '/css/katex/katex.min.css') !== false;
  1254. // 【调试】记录HTML内容信息
  1255. Log::warning('ExamPdfExportService: inlineExternalResources', [
  1256. 'html_length' => strlen($html),
  1257. 'has_katex_cdn' => $hasKatexCdn,
  1258. 'has_katex_local' => $hasKatexLocal,
  1259. ]);
  1260. // 如果既没有 CDN 也没有本地链接,跳过
  1261. if (! $hasKatexCdn && ! $hasKatexLocal) {
  1262. Log::warning('ExamPdfExportService: HTML 中没有 KaTeX 资源链接,跳过内联');
  1263. return $html;
  1264. }
  1265. try {
  1266. // 读取并内联 KaTeX CSS(无论 CDN 还是本地)
  1267. $katexCssPath = public_path('css/katex/katex.min.css');
  1268. if (file_exists($katexCssPath)) {
  1269. $katexCss = file_get_contents($katexCssPath);
  1270. // 修复字体路径:将相对路径改为 data URI
  1271. $fontsDir = public_path('css/katex/fonts');
  1272. $katexCss = preg_replace_callback(
  1273. '/url\(["\']?fonts\/([^"\')\s]+)["\']?\)/i',
  1274. function ($matches) use ($fontsDir) {
  1275. $fontFile = $fontsDir.'/'.$matches[1];
  1276. if (file_exists($fontFile)) {
  1277. $fontData = base64_encode(file_get_contents($fontFile));
  1278. $mimeType = str_ends_with($matches[1], '.woff2') ? 'font/woff2' : 'font/woff';
  1279. return 'url(data:'.$mimeType.';base64,'.$fontData.')';
  1280. }
  1281. return $matches[0];
  1282. },
  1283. $katexCss
  1284. );
  1285. // 替换 CDN CSS 链接
  1286. if ($hasKatexCdn) {
  1287. $html = preg_replace(
  1288. '/<link[^>]*href=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*katex\.min\.css["\'][^>]*>/i',
  1289. '<style type="text/css">'.$katexCss.'</style>',
  1290. $html
  1291. );
  1292. }
  1293. // 替换本地 CSS 链接
  1294. if ($hasKatexLocal) {
  1295. $html = preg_replace(
  1296. '/<link[^>]*href=["\']\/css\/katex\/katex\.min\.css["\'][^>]*>/i',
  1297. '<style type="text/css">'.$katexCss.'</style>',
  1298. $html
  1299. );
  1300. }
  1301. Log::info('ExamPdfExportService: KaTeX CSS 已内联(含字体 data URI)');
  1302. }
  1303. // 读取本地 KaTeX JS(用于移除)
  1304. $katexJsPath = public_path('js/katex.min.js');
  1305. $autoRenderJsPath = public_path('js/auto-render.min.js');
  1306. if (file_exists($katexJsPath)) {
  1307. $katexJs = file_get_contents($katexJsPath);
  1308. $html = preg_replace(
  1309. '/<script[^>]*src=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*katex\.min\.js["\'][^>]*><\/script>/i',
  1310. '<script type="text/javascript">'.$katexJs.'</script>',
  1311. $html
  1312. );
  1313. }
  1314. if (file_exists($autoRenderJsPath)) {
  1315. $autoRenderJs = file_get_contents($autoRenderJsPath);
  1316. $html = preg_replace(
  1317. '/<script[^>]*src=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*auto-render[^"\']*["\'][^>]*><\/script>/i',
  1318. '<script type="text/javascript">'.$autoRenderJs.'</script>',
  1319. $html
  1320. );
  1321. }
  1322. // 【关键修复】使用服务端预渲染,而不是依赖客户端 JavaScript
  1323. // Chrome headless 的 --print-to-pdf 不会等待 JS 执行完成
  1324. // 所以我们使用 Node.js KaTeX 在服务端预渲染所有公式
  1325. // 1. 移除所有 KaTeX JavaScript(不再需要,因为使用服务端渲染)
  1326. // 移除内联的 katex.min.js
  1327. $html = preg_replace(
  1328. '/<script[^>]*type=["\']text\/javascript["\'][^>]*>[\s\S]*?katex[\s\S]*?<\/script>/i',
  1329. '<!-- KaTeX JS removed, using server-side rendering -->',
  1330. $html
  1331. );
  1332. // 移除 DOMContentLoaded 监听器
  1333. $html = preg_replace(
  1334. '/<script[^>]*>[\s\S]*?document\.addEventListener[\s\S]*?DOMContentLoaded[\s\S]*?<\/script>/i',
  1335. '<!-- DOMContentLoaded removed -->',
  1336. $html
  1337. );
  1338. // 2. 使用 KatexRenderer 进行服务端预渲染
  1339. if ($this->katexRenderer) {
  1340. $beforeLength = strlen($html);
  1341. $html = $this->katexRenderer->renderHtml($html);
  1342. $afterLength = strlen($html);
  1343. Log::info('ExamPdfExportService: LaTeX 公式服务端预渲染完成', [
  1344. 'before_length' => $beforeLength,
  1345. 'after_length' => $afterLength,
  1346. 'size_change' => $afterLength - $beforeLength,
  1347. ]);
  1348. } else {
  1349. Log::warning('ExamPdfExportService: KatexRenderer 未初始化,跳过预渲染');
  1350. }
  1351. // 【换行处理】将字面的 \n 转换为 <br> 标签(在 KaTeX 渲染后处理,避免破坏公式)
  1352. // 先替换所有 \n 为 <br>,然后合并连续的 <br>(最多保留2个)
  1353. $html = str_replace('\\n', '<br>', $html);
  1354. $html = preg_replace('/(<br>\s*){3,}/', '<br><br>', $html); // 3个以上合并为2个
  1355. } catch (\Exception $e) {
  1356. Log::warning('ExamPdfExportService: 内联资源处理失败,保留原始HTML', [
  1357. 'error' => $e->getMessage(),
  1358. ]);
  1359. }
  1360. return $html;
  1361. }
  1362. /**
  1363. * 【新增】合并两个HTML页面,插入分页符
  1364. * 保留原始页面样式和结构,只在中间插入分页符
  1365. */
  1366. private function mergeHtmlWithPageBreak(string $examHtml, string $gradingHtml, ?string $kpExplainHtml = null): ?string
  1367. {
  1368. try {
  1369. // 确保HTML编码正确
  1370. $examHtml = $this->ensureUtf8Html($examHtml);
  1371. $gradingHtml = $this->ensureUtf8Html($gradingHtml);
  1372. if ($kpExplainHtml) {
  1373. $kpExplainHtml = $this->ensureUtf8Html($kpExplainHtml);
  1374. }
  1375. // 提取body内容
  1376. $examBody = $this->extractBodyContent($examHtml);
  1377. $gradingBody = $this->extractBodyContent($gradingHtml);
  1378. // 知识点讲解使用专门的提取方法,避免嵌套完整HTML结构
  1379. $kpExplainBody = $kpExplainHtml ? $this->extractKpExplainContent($kpExplainHtml) : null;
  1380. if (empty($examBody) || empty($gradingBody)) {
  1381. Log::error('ExamPdfExportService: HTML内容提取失败', [
  1382. 'exam_body_length' => strlen($examBody),
  1383. 'grading_body_length' => strlen($gradingBody),
  1384. ]);
  1385. return null;
  1386. }
  1387. // 提取head内容(保留原始样式和meta信息)
  1388. $examHead = $this->extractHeadContent($examHtml);
  1389. $gradingHead = $this->extractHeadContent($gradingHtml);
  1390. $kpExplainHead = $kpExplainHtml ? $this->extractHeadContent($kpExplainHtml) : null;
  1391. // 构建统一HTML文档(保留原始结构)
  1392. $unifiedHtml = $this->buildUnifiedHtmlWithOriginalStructure(
  1393. $examHead,
  1394. $examBody,
  1395. $gradingBody,
  1396. $gradingHead,
  1397. $kpExplainBody,
  1398. $kpExplainHead
  1399. );
  1400. Log::info('HTML合并成功(保留原始样式)', [
  1401. 'exam_length' => strlen($examBody),
  1402. 'grading_length' => strlen($gradingBody),
  1403. 'kp_explain_length' => $kpExplainBody ? strlen($kpExplainBody) : 0,
  1404. 'unified_length' => strlen($unifiedHtml),
  1405. 'head_length' => strlen($examHead),
  1406. 'has_kp_explain' => ! empty($kpExplainBody),
  1407. ]);
  1408. return $unifiedHtml;
  1409. } catch (\Throwable $e) {
  1410. Log::error('mergeHtmlWithPageBreak 失败', [
  1411. 'error' => $e->getMessage(),
  1412. 'trace' => $e->getTraceAsString(),
  1413. ]);
  1414. return null;
  1415. }
  1416. }
  1417. /**
  1418. * 【新增】提取HTML的body内容
  1419. */
  1420. private function extractBodyContent(string $html): string
  1421. {
  1422. // 匹配body标签内容
  1423. if (preg_match('/<body[^>]*>(.*)<\/body>/is', $html, $matches)) {
  1424. return $matches[1];
  1425. }
  1426. // 如果没有body标签,返回整个HTML
  1427. return $html;
  1428. }
  1429. /**
  1430. * 【新增】提取HTML的head内容
  1431. * 保留原始页面的样式和meta信息
  1432. */
  1433. private function extractHeadContent(string $html): string
  1434. {
  1435. // 匹配head标签内容
  1436. if (preg_match('/<head[^>]*>(.*)<\/head>/is', $html, $matches)) {
  1437. return $matches[1];
  1438. }
  1439. // 如果没有head标签,返回默认meta
  1440. return '<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">';
  1441. }
  1442. /**
  1443. * 【新增】提取知识点讲解的核心内容
  1444. * 只提取 kp-explain 容器内部的内容,避免嵌套完整的HTML结构
  1445. */
  1446. private function extractKpExplainContent(string $html): string
  1447. {
  1448. // 如果 HTML 中包含嵌套的 <html> 标签,提取嵌套内容
  1449. if (preg_match('/<html[^>]*>(.*)<\/html>/is', $html, $htmlMatches)) {
  1450. $html = $htmlMatches[1];
  1451. }
  1452. // 如果 HTML 中包含 <head> 标签,跳过 head
  1453. if (preg_match('/<head[^>]*>.*?<\/head>/is', $html, $headMatch)) {
  1454. $html = substr($html, strpos($html, '</head>') + 7);
  1455. }
  1456. // 如果 HTML 中包含 <body> 标签,提取 body 内容
  1457. if (preg_match('/<body[^>]*>(.*)<\/body>/is', $html, $bodyMatches)) {
  1458. $html = $bodyMatches[1];
  1459. }
  1460. // 移除可能存在的嵌套 <html>, <head>, <body> 标签
  1461. $html = preg_replace('/<\/?(html|head|body)[^>]*>/is', '', $html);
  1462. // 移除 script 标签和注释
  1463. $html = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $html);
  1464. $html = preg_replace('/<!--[^>]*-->/is', '', $html);
  1465. return trim($html);
  1466. }
  1467. /**
  1468. * 【优化重构】构建统一的HTML文档(容器结构 + 消除空白页)
  1469. * 使用容器结构替代空的 page-break div,避免中间出现空白页
  1470. */
  1471. private function buildUnifiedHtmlWithOriginalStructure(
  1472. string $examHead,
  1473. string $examBody,
  1474. string $gradingBody,
  1475. string $gradingHead,
  1476. ?string $kpExplainBody = null,
  1477. ?string $kpExplainHead = null
  1478. ): string
  1479. {
  1480. // 清洗内容:移除可能存在的分页符,避免双重分页
  1481. $examBody = $this->stripPageBreakElements($examBody);
  1482. $gradingBody = $this->stripPageBreakElements($gradingBody);
  1483. if ($kpExplainBody) {
  1484. $kpExplainBody = $this->stripPageBreakElements($kpExplainBody);
  1485. }
  1486. // 合并 head 内容:试卷 head + 判卷 head + 知识点讲解 head(去重)+ 分页控制样式
  1487. $mergedHead = $examHead;
  1488. // 按顺序合并其他 head 里的 <style>(避免重复)
  1489. foreach ([$gradingHead, $kpExplainHead] as $extraHead) {
  1490. if (! $extraHead) {
  1491. continue;
  1492. }
  1493. if (preg_match_all('/<style[^>]*>(.*?)<\/style>/is', $extraHead, $styleMatches)) {
  1494. foreach ($styleMatches[0] as $idx => $styleTag) {
  1495. if (! str_contains($mergedHead, $styleMatches[1][$idx])) {
  1496. $mergedHead .= "\n ".$styleTag;
  1497. }
  1498. }
  1499. }
  1500. }
  1501. // 添加分页控制样式
  1502. $headContent = $mergedHead.'
  1503. <style>
  1504. /* 容器基础样式 - 保持现有页面边距 */
  1505. .exam-part,
  1506. .grading-part,
  1507. .kp-explain-part {
  1508. width: 100%;
  1509. margin: 0;
  1510. padding: 0;
  1511. }
  1512. /* 试卷部分 - 只有在知识点讲解后才需要分页 */
  1513. .exam-part {
  1514. /* 如果有知识点讲解,需要在新页面开始(通过 kp-explain-part 的 break-after 控制) */
  1515. /* 如果没有知识点讲解,试卷从第一页开始,不需要分页 */
  1516. break-after: auto;
  1517. page-break-after: auto;
  1518. /* 确保顶部没有额外边距 */
  1519. margin-top: 0;
  1520. padding-top: 0;
  1521. }
  1522. /* 核心分页控制:只在 grading-part 上设置 */
  1523. .grading-part {
  1524. /* CSS3 新标准 */
  1525. break-before: page;
  1526. /* 兼容旧版 WebKit */
  1527. page-break-before: always;
  1528. /* 确保顶部没有额外边距 */
  1529. margin-top: 0;
  1530. padding-top: 0;
  1531. }
  1532. /* 知识点讲解部分末尾强制分页(确保试卷从新页面开始) */
  1533. .kp-explain-part {
  1534. break-after: page;
  1535. page-break-after: always;
  1536. }
  1537. /* 防止试卷部分末尾分页 */
  1538. .exam-part {
  1539. /* 确保试卷内容连续 */
  1540. break-after: auto;
  1541. page-break-after: auto;
  1542. }
  1543. /* 避免在关键元素中间分页 */
  1544. .exam-part h1, .exam-part h2,
  1545. .grading-part h1, .grading-part h2 {
  1546. break-after: avoid;
  1547. page-break-after: avoid;
  1548. }
  1549. .exam-part table, .exam-part .question-item,
  1550. .grading-part table, .grading-part .answer-item {
  1551. break-inside: avoid;
  1552. page-break-inside: avoid;
  1553. }
  1554. /* 防止孤儿行 */
  1555. .exam-part p, .exam-part li,
  1556. .grading-part p, .grading-part li {
  1557. orphans: 2;
  1558. widows: 2;
  1559. }
  1560. /* 数学公式优化 */
  1561. .katex {
  1562. break-inside: avoid;
  1563. page-break-inside: avoid;
  1564. }
  1565. </style>';
  1566. // 构建HTML内容
  1567. $bodyContent = '';
  1568. $mergedTitle = '试卷与判卷合并';
  1569. if (preg_match('/<title>(.*?)<\/title>/is', $examHead, $titleMatches)) {
  1570. $candidateTitle = trim(strip_tags($titleMatches[1]));
  1571. if ($candidateTitle !== '') {
  1572. $mergedTitle = $candidateTitle;
  1573. }
  1574. }
  1575. // 如果有知识点讲解,添加到最前面
  1576. if ($kpExplainBody) {
  1577. $bodyContent .= '
  1578. <!-- 知识点讲解部分 -->
  1579. <div class="kp-explain-part">
  1580. '.$kpExplainBody.'
  1581. </div>
  1582. ';
  1583. }
  1584. // 添加试卷部分
  1585. $bodyContent .= '
  1586. <!-- 试卷部分 - 连续显示 -->
  1587. <div class="exam-part">
  1588. '.$examBody.'
  1589. </div>
  1590. ';
  1591. // 添加判卷部分
  1592. $bodyContent .= '
  1593. <!-- 判卷部分 - 强制新页面开始 -->
  1594. <div class="grading-part">
  1595. '.$gradingBody.'
  1596. </div>
  1597. ';
  1598. return '<!DOCTYPE html>
  1599. <html lang="zh-CN">
  1600. <head>
  1601. <meta charset="UTF-8">
  1602. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1603. <title>'.$mergedTitle.'</title>
  1604. '.$headContent.'
  1605. </head>
  1606. <body>
  1607. '.$bodyContent.'
  1608. </body>
  1609. </html>';
  1610. }
  1611. /**
  1612. * 【新增】清洗HTML内容中的分页符元素
  1613. * 移除可能存在的 page-break 元素,避免双重分页导致空白页
  1614. */
  1615. private function stripPageBreakElements(string $content): string
  1616. {
  1617. // 只移除空的 page-break div 元素(通常是 <div class="page-break"></div>)
  1618. // 使用更精确的正则,只匹配空内容或纯空白内容的 div
  1619. $patterns = [
  1620. '/<div[^>]*class="[^"]*page-break[^"]*"[^>]*>\s*<\/div>/si',
  1621. '/<div[^>]*style="[^"]*page-break[^"]*"[^>]*>\s*<\/div>/si',
  1622. ];
  1623. foreach ($patterns as $pattern) {
  1624. $content = preg_replace($pattern, '', $content);
  1625. }
  1626. return $content;
  1627. }
  1628. /**
  1629. * 【新增】获取PDF通用样式
  1630. */
  1631. private function getCommonPdfStyles(): string
  1632. {
  1633. return '
  1634. * {
  1635. margin: 0;
  1636. padding: 0;
  1637. box-sizing: border-box;
  1638. }
  1639. body {
  1640. font-family: "Microsoft YaHei", "SimHei", Arial, sans-serif;
  1641. font-size: 14px;
  1642. line-height: 1.6;
  1643. color: #333;
  1644. background: #fff;
  1645. }
  1646. .paper-container {
  1647. max-width: 210mm;
  1648. margin: 0 auto;
  1649. padding: 20mm;
  1650. background: white;
  1651. }
  1652. .paper-header {
  1653. text-align: center;
  1654. margin-bottom: 30px;
  1655. padding-bottom: 15px;
  1656. border-bottom: 2px solid #333;
  1657. }
  1658. .paper-title {
  1659. font-size: 24px;
  1660. font-weight: bold;
  1661. margin-bottom: 10px;
  1662. }
  1663. .paper-info {
  1664. font-size: 14px;
  1665. color: #666;
  1666. }
  1667. .question {
  1668. margin-bottom: 30px;
  1669. padding: 20px;
  1670. border: 1px solid #ddd;
  1671. border-radius: 5px;
  1672. }
  1673. .question-number {
  1674. font-weight: bold;
  1675. margin-bottom: 10px;
  1676. }
  1677. .question-stem {
  1678. margin-bottom: 15px;
  1679. }
  1680. .options {
  1681. list-style: none;
  1682. margin-left: 20px;
  1683. }
  1684. .options li {
  1685. margin-bottom: 8px;
  1686. }
  1687. .answer-section {
  1688. margin-top: 20px;
  1689. padding-top: 15px;
  1690. border-top: 1px solid #eee;
  1691. }
  1692. .answer-label {
  1693. font-weight: bold;
  1694. color: #d9534f;
  1695. }
  1696. .solution {
  1697. margin-top: 10px;
  1698. padding: 10px;
  1699. background: #f5f5f5;
  1700. border-left: 4px solid #5bc0de;
  1701. }
  1702. ';
  1703. }
  1704. /**
  1705. * 构建知识点名称映射
  1706. */
  1707. private function buildKnowledgePointNameMap(): array
  1708. {
  1709. try {
  1710. $options = $this->questionServiceApi->getKnowledgePointOptions();
  1711. return $options ?: [];
  1712. } catch (\Throwable $e) {
  1713. Log::warning('ExamPdfExportService: 获取知识点名称失败', [
  1714. 'error' => $e->getMessage(),
  1715. ]);
  1716. return [];
  1717. }
  1718. }
  1719. /**
  1720. * 构建掌握度摘要
  1721. */
  1722. private function buildMasterySummary(array $masteryData, array $kpNameMap): array
  1723. {
  1724. Log::info('ExamPdfExportService: buildMasterySummary开始处理', [
  1725. 'masteryData_count' => count($masteryData),
  1726. 'kpNameMap_count' => count($kpNameMap),
  1727. ]);
  1728. $items = [];
  1729. $total = 0;
  1730. $count = 0;
  1731. foreach ($masteryData as $row) {
  1732. $code = $row['kp_code'] ?? null;
  1733. // 【修复】使用kpNameMap转换名称为友好显示名
  1734. $name = $kpNameMap[$code] ?? $row['kp_name'] ?? $code ?: '未知知识点';
  1735. $level = (float) ($row['mastery_level'] ?? 0);
  1736. $delta = $row['mastery_change'] ?? null;
  1737. $items[] = [
  1738. 'kp_code' => $code,
  1739. 'kp_name' => $name,
  1740. 'mastery_level' => $level,
  1741. 'mastery_change' => $delta,
  1742. ];
  1743. $total += $level;
  1744. $count++;
  1745. }
  1746. $average = $count > 0 ? round($total / $count, 2) : null;
  1747. // 按掌握度从低到高排序
  1748. if (! empty($items)) {
  1749. usort($items, fn ($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  1750. }
  1751. $result = [
  1752. 'items' => $items,
  1753. 'average' => $average,
  1754. 'weak_list' => array_slice($items, 0, 5),
  1755. ];
  1756. Log::info('ExamPdfExportService: buildMasterySummary完成', [
  1757. 'total_count' => $count,
  1758. 'items_count' => count($items),
  1759. ]);
  1760. return $result;
  1761. }
  1762. /**
  1763. * 标准化题型
  1764. */
  1765. private function normalizeQuestionType(string $type): string
  1766. {
  1767. $t = strtolower(trim($type));
  1768. return match (true) {
  1769. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  1770. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  1771. default => 'answer',
  1772. };
  1773. }
  1774. private function buildPaperNamePrefix(Paper $paper): string
  1775. {
  1776. $assembleType = ($paper->paper_type === null || $paper->paper_type === '')
  1777. ? null
  1778. : (int) $paper->paper_type;
  1779. $studentName = Student::query()
  1780. ->where('student_id', $paper->student_id)
  1781. ->value('name') ?? ($paper->student_id ?: '________');
  1782. try {
  1783. $assembleTypeLabel = $assembleType !== null ? PaperNaming::assembleTypeLabel($assembleType) : '未知类型';
  1784. } catch (\Throwable $e) {
  1785. $assembleTypeLabel = '未知类型';
  1786. }
  1787. return "{$studentName}_".PaperNaming::extractExamCode((string) $paper->paper_id)."_{$assembleTypeLabel}";
  1788. }
  1789. private function buildPaperDisplayTitle(Paper $paper): string
  1790. {
  1791. return $this->buildPaperNamePrefix($paper).'_'.now()->format('Ymd');
  1792. }
  1793. private function buildPdfFileName(Paper $paper, ?string $stamp = null): string
  1794. {
  1795. $basePrefix = $this->buildPaperNamePrefix($paper);
  1796. $stamp = $stamp ?: now()->format('YmdHis').strtoupper(Str::random(4));
  1797. $base = "{$basePrefix}_{$stamp}";
  1798. $safe = PaperNaming::toSafeFilename($base);
  1799. return "{$safe}.pdf";
  1800. }
  1801. private function extractUploadStamp(string $url): ?string
  1802. {
  1803. $path = parse_url($url, PHP_URL_PATH);
  1804. if (! is_string($path) || $path === '') {
  1805. return null;
  1806. }
  1807. $stem = pathinfo($path, PATHINFO_FILENAME);
  1808. if (! is_string($stem) || $stem === '') {
  1809. return null;
  1810. }
  1811. if (preg_match('/(\d{14}[A-Za-z0-9]{4})/', $stem, $matches)) {
  1812. return $matches[1];
  1813. }
  1814. return null;
  1815. }
  1816. /**
  1817. * 保存PDF URL到数据库
  1818. */
  1819. private function savePdfUrlToDatabase(string $paperId, string $field, string $url): void
  1820. {
  1821. try {
  1822. $paper = Paper::where('paper_id', $paperId)->first();
  1823. if ($paper) {
  1824. $paperDisplayTitle = $this->buildPaperDisplayTitle($paper);
  1825. $stamp = $this->extractUploadStamp($url);
  1826. if ($stamp) {
  1827. $paperDisplayTitle = $this->buildPaperNamePrefix($paper).'_'.$stamp;
  1828. }
  1829. $updatePayload = [
  1830. $field => $url,
  1831. 'paper_name' => $paperDisplayTitle,
  1832. ];
  1833. $paper->update($updatePayload);
  1834. Log::info('ExamPdfExportService: PDF URL已写入数据库', [
  1835. 'paper_id' => $paperId,
  1836. 'field' => $field,
  1837. 'url' => $url,
  1838. 'paper_name' => $paperDisplayTitle,
  1839. ]);
  1840. }
  1841. } catch (\Throwable $e) {
  1842. Log::error('ExamPdfExportService: 写入PDF URL失败', [
  1843. 'paper_id' => $paperId,
  1844. 'field' => $field,
  1845. 'error' => $e->getMessage(),
  1846. ]);
  1847. }
  1848. }
  1849. /**
  1850. * 保存学情分析PDF URL
  1851. */
  1852. private function saveAnalysisPdfUrl(string $paperId, string $studentId, ?string $recordId, string $url): void
  1853. {
  1854. try {
  1855. if ($recordId) {
  1856. // OCR记录
  1857. $ocrRecord = \App\Models\OCRRecord::find($recordId);
  1858. if ($ocrRecord) {
  1859. $ocrRecord->update(['analysis_pdf_url' => $url]);
  1860. Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
  1861. 'record_id' => $recordId,
  1862. 'paper_id' => $paperId,
  1863. 'student_id' => $studentId,
  1864. 'url' => $url,
  1865. ]);
  1866. }
  1867. } else {
  1868. // 【修复】同时更新 exam_analysis_results 表和分析报告表
  1869. $updated = \DB::connection('mysql')->table('exam_analysis_results')
  1870. ->where('student_id', $studentId)
  1871. ->where('paper_id', $paperId)
  1872. ->update([
  1873. 'analysis_pdf_url' => $url,
  1874. 'updated_at' => now(),
  1875. ]);
  1876. if ($updated) {
  1877. Log::info('ExamPdfExportService: 学情分析PDF URL已写入exam_analysis_results表', [
  1878. 'student_id' => $studentId,
  1879. 'paper_id' => $paperId,
  1880. 'url' => $url,
  1881. 'updated_rows' => $updated,
  1882. ]);
  1883. } else {
  1884. Log::warning('ExamPdfExportService: 未找到要更新的学情分析记录', [
  1885. 'student_id' => $studentId,
  1886. 'paper_id' => $paperId,
  1887. ]);
  1888. }
  1889. // 学生记录 - 使用新的 student_reports 表(备用)
  1890. \App\Models\StudentReport::updateOrCreate(
  1891. [
  1892. 'student_id' => $studentId,
  1893. 'report_type' => 'exam_analysis',
  1894. 'paper_id' => $paperId,
  1895. ],
  1896. [
  1897. 'pdf_url' => $url,
  1898. 'generation_status' => 'completed',
  1899. 'generated_at' => now(),
  1900. 'updated_at' => now(),
  1901. ]
  1902. );
  1903. Log::info('ExamPdfExportService: 学生学情报告PDF URL已保存到student_reports表(备用)', [
  1904. 'student_id' => $studentId,
  1905. 'paper_id' => $paperId,
  1906. 'url' => $url,
  1907. ]);
  1908. }
  1909. } catch (\Throwable $e) {
  1910. Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
  1911. 'paper_id' => $paperId,
  1912. 'student_id' => $studentId,
  1913. 'record_id' => $recordId,
  1914. 'error' => $e->getMessage(),
  1915. ]);
  1916. }
  1917. }
  1918. /**
  1919. * 【修复】处理父节点掌握度数据
  1920. * 1. 过滤掉掌握度为0或null的父节点
  1921. * 2. 将kp_code转换为友好的kp_name
  1922. * 3. 构建父子层级关系(只显示本次考试相关的子节点)
  1923. */
  1924. private function processParentMasteryLevels(array $parentMasteryLevels, array $kpNameMap, array $examKpCodes = [], array $masteryMap = []): array
  1925. {
  1926. $processed = [];
  1927. foreach ($parentMasteryLevels as $kpCode => $masteryData) {
  1928. // 兼容不同数据结构:可能是数组或数字
  1929. $masteryLevel = is_array($masteryData) ? ($masteryData['mastery_level'] ?? 0) : $masteryData;
  1930. $masteryChange = is_array($masteryData) ? ($masteryData['mastery_change'] ?? null) : null;
  1931. $changeSource = is_array($masteryData) ? ($masteryData['change_source'] ?? null) : null;
  1932. // 过滤零值和空值
  1933. if ($masteryLevel === null || $masteryLevel === 0.0 || $masteryLevel <= 0.001) {
  1934. continue;
  1935. }
  1936. // 获取友好名称
  1937. $kpName = $kpNameMap[$kpCode] ?? $kpCode;
  1938. // 构建父节点数据,包含子节点信息(只显示本次考试相关的)
  1939. $childrenData = $this->getChildKnowledgePoints($kpCode, $kpNameMap, $examKpCodes, $masteryMap);
  1940. $hitLevels = array_map(
  1941. fn ($c) => floatval($c['mastery_level'] ?? 0),
  1942. $childrenData['hit_children'] ?? []
  1943. );
  1944. $hitAvg = ! empty($hitLevels) ? array_sum($hitLevels) / count($hitLevels) : null;
  1945. $processed[$kpCode] = [
  1946. 'kp_code' => $kpCode,
  1947. 'kp_name' => $kpName,
  1948. 'mastery_level' => round(floatval($masteryLevel), 4),
  1949. 'mastery_percentage' => round(floatval($masteryLevel) * 100, 2),
  1950. 'mastery_change' => $masteryChange !== null ? round(floatval($masteryChange), 4) : null,
  1951. 'change_source' => $changeSource,
  1952. // 兼容旧模板字段:仅命中子节点
  1953. 'children' => $childrenData['hit_children'] ?? [],
  1954. // 新增:全部直接子节点(含掌握度、是否命中)
  1955. 'children_all' => $childrenData['all_children'] ?? [],
  1956. 'children_hit_count' => count($childrenData['hit_children'] ?? []),
  1957. 'children_total_count' => count($childrenData['all_children'] ?? []),
  1958. 'children_hit_avg_mastery' => $hitAvg !== null ? round($hitAvg, 4) : null,
  1959. 'level' => $this->calculateKnowledgePointLevel($kpCode),
  1960. ];
  1961. }
  1962. // 按掌握度降序排序
  1963. uasort($processed, function ($a, $b) {
  1964. return $b['mastery_level'] <=> $a['mastery_level'];
  1965. });
  1966. return $processed;
  1967. }
  1968. /**
  1969. * 【修复】获取子知识点列表(只返回本次考试涉及的)
  1970. */
  1971. private function getChildKnowledgePoints(string $parentKpCode, array $kpNameMap, array $examKpCodes = [], array $masteryMap = []): array
  1972. {
  1973. $allChildren = [];
  1974. $hitChildren = [];
  1975. try {
  1976. $childCodes = DB::connection('mysql')
  1977. ->table('knowledge_points')
  1978. ->where('parent_kp_code', $parentKpCode)
  1979. ->pluck('kp_code')
  1980. ->toArray();
  1981. foreach ($childCodes as $childCode) {
  1982. $isHit = in_array($childCode, $examKpCodes);
  1983. $childData = [
  1984. 'kp_code' => $childCode,
  1985. 'kp_name' => $kpNameMap[$childCode] ?? $childCode,
  1986. 'mastery_level' => floatval($masteryMap[$childCode] ?? 0),
  1987. 'is_hit' => $isHit,
  1988. ];
  1989. $allChildren[] = $childData;
  1990. if ($isHit) {
  1991. $hitChildren[] = $childData;
  1992. }
  1993. }
  1994. } catch (\Exception $e) {
  1995. Log::warning('获取子知识点失败', [
  1996. 'parent_kp_code' => $parentKpCode,
  1997. 'error' => $e->getMessage(),
  1998. ]);
  1999. }
  2000. return [
  2001. 'all_children' => $allChildren,
  2002. 'hit_children' => $hitChildren,
  2003. ];
  2004. }
  2005. /**
  2006. * 计算知识点层级深度
  2007. */
  2008. private function calculateKnowledgePointLevel(string $kpCode): int
  2009. {
  2010. // 根据kp_code前缀判断层级深度
  2011. // 例如: M (1级) -> M01 (2级) -> M01A (3级)
  2012. if (preg_match('/^[A-Z]+$/', $kpCode)) {
  2013. return 1; // 一级分类,如 M, S, E, G
  2014. } elseif (preg_match('/^[A-Z]+\d+$/', $kpCode)) {
  2015. return 2; // 二级分类,如 M01, S02
  2016. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+$/', $kpCode)) {
  2017. return 3; // 三级分类,如 M01A, S02B
  2018. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+\d+$/', $kpCode)) {
  2019. return 4; // 四级分类,如 M01A1
  2020. }
  2021. return 1; // 默认一级
  2022. }
  2023. /**
  2024. * 构建题目数据(用于PDF生成)
  2025. */
  2026. private function buildQuestionsData(Paper $paper): array
  2027. {
  2028. $paperQuestions = $paper->questions()->orderBy('question_number')->get();
  2029. $questionsData = [];
  2030. foreach ($paperQuestions as $pq) {
  2031. $questionsData[] = [
  2032. 'id' => $pq->question_bank_id,
  2033. 'question_number' => $pq->question_number, // 传递原始题号,确保渲染时序号正确
  2034. 'kp_code' => $pq->knowledge_point,
  2035. 'question_type' => $pq->question_type ?? 'answer',
  2036. 'stem' => $pq->question_text ?? '题目内容缺失',
  2037. 'solution' => $pq->solution ?? '',
  2038. 'answer' => $pq->correct_answer ?? '',
  2039. 'difficulty' => $pq->difficulty ?? 0.5,
  2040. 'score' => $pq->score ?? 5,
  2041. 'tags' => '',
  2042. 'content' => $pq->question_text ?? '',
  2043. ];
  2044. }
  2045. // 获取完整题目详情
  2046. if (! empty($questionsData)) {
  2047. $questionIds = array_column($questionsData, 'id');
  2048. $questionsResponse = $this->questionServiceApi->getQuestionsByIds($questionIds);
  2049. $responseData = $questionsResponse['data'] ?? [];
  2050. if (! empty($responseData)) {
  2051. $responseDataMap = [];
  2052. foreach ($responseData as $respQ) {
  2053. $responseDataMap[$respQ['id']] = $respQ;
  2054. }
  2055. $questionsData = array_map(function ($q) use ($responseDataMap) {
  2056. if (isset($responseDataMap[$q['id']])) {
  2057. $apiData = $responseDataMap[$q['id']];
  2058. $q['stem'] = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  2059. $q['content'] = $q['stem'];
  2060. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  2061. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  2062. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  2063. $q['options'] = $apiData['options'] ?? [];
  2064. }
  2065. return $q;
  2066. }, $questionsData);
  2067. }
  2068. }
  2069. // 按题型分类
  2070. $classified = ['choice' => [], 'fill' => [], 'answer' => []];
  2071. foreach ($questionsData as $q) {
  2072. $type = $this->determineQuestionType($q);
  2073. $classified[$type][] = (object) $q;
  2074. }
  2075. // 【调试】记录题目分类情况
  2076. Log::debug('buildQuestionsData: 题目分类结果', [
  2077. 'total_questions' => count($questionsData),
  2078. 'choice_count' => count($classified['choice']),
  2079. 'fill_count' => count($classified['fill']),
  2080. 'answer_count' => count($classified['answer']),
  2081. 'choice_numbers' => array_map(fn ($q) => $q->question_number ?? 'N/A', $classified['choice']),
  2082. 'fill_numbers' => array_map(fn ($q) => $q->question_number ?? 'N/A', $classified['fill']),
  2083. 'answer_numbers' => array_map(fn ($q) => $q->question_number ?? 'N/A', $classified['answer']),
  2084. ]);
  2085. return $classified;
  2086. }
  2087. /**
  2088. * 获取学生信息
  2089. */
  2090. private function getStudentInfo(?string $studentId): array
  2091. {
  2092. if (! $studentId) {
  2093. return [
  2094. 'name' => '未知学生',
  2095. 'grade' => '未知年级',
  2096. 'class' => '未知班级',
  2097. ];
  2098. }
  2099. try {
  2100. $student = DB::table('students')
  2101. ->where('student_id', $studentId)
  2102. ->first();
  2103. if ($student) {
  2104. return [
  2105. 'name' => $student->name ?? $studentId,
  2106. 'grade' => $student->grade ?? '未知',
  2107. 'class' => $student->class ?? '未知',
  2108. ];
  2109. }
  2110. } catch (\Exception $e) {
  2111. Log::warning('获取学生信息失败', [
  2112. 'student_id' => $studentId,
  2113. 'error' => $e->getMessage(),
  2114. ]);
  2115. }
  2116. return [
  2117. 'name' => $studentId,
  2118. 'grade' => '未知',
  2119. 'class' => '未知',
  2120. ];
  2121. }
  2122. /**
  2123. * 获取教师信息
  2124. */
  2125. private function getTeacherInfo(?string $teacherId): array
  2126. {
  2127. if (! $teacherId) {
  2128. return [
  2129. 'name' => '未知老师',
  2130. 'subject' => '数学',
  2131. ];
  2132. }
  2133. try {
  2134. $query = DB::table('teachers')->where('teacher_id', $teacherId);
  2135. // 仅在列存在时追加,避免 Unknown column 'id'
  2136. if (Schema::hasColumn('teachers', 'id')) {
  2137. $query->orWhere('id', $teacherId);
  2138. }
  2139. $teacher = $query->first();
  2140. if ($teacher) {
  2141. return [
  2142. 'name' => $teacher->name ?? '________',
  2143. 'subject' => $teacher->subject ?? '数学',
  2144. ];
  2145. }
  2146. } catch (\Exception $e) {
  2147. Log::warning('获取教师信息失败', [
  2148. 'teacher_id' => $teacherId,
  2149. 'error' => $e->getMessage(),
  2150. ]);
  2151. }
  2152. return [
  2153. 'name' => '________',
  2154. 'subject' => '数学',
  2155. ];
  2156. }
  2157. /**
  2158. * 判断题目类型
  2159. * 【修复】优先使用 question_type 字段,避免选择题因含有()被误判为填空题
  2160. */
  2161. private function determineQuestionType(array $question): string
  2162. {
  2163. // 1. 【优先】根据已有类型字段判断(最可靠的来源)
  2164. if (! empty($question['question_type'])) {
  2165. $type = strtolower(trim($question['question_type']));
  2166. if (in_array($type, ['choice', '选择题'])) {
  2167. return 'choice';
  2168. }
  2169. if (in_array($type, ['fill', '填空题'])) {
  2170. return 'fill';
  2171. }
  2172. if (in_array($type, ['answer', '解答题'])) {
  2173. return 'answer';
  2174. }
  2175. }
  2176. // 2. 如果没有明确类型,则根据题干内容推断
  2177. $stem = $question['stem'] ?? $question['content'] ?? '';
  2178. if (is_string($stem)) {
  2179. // 检查是否有选项模式 A. B. C. D.
  2180. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  2181. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  2182. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  2183. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  2184. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0);
  2185. if ($optionCount >= 2) {
  2186. return 'choice';
  2187. }
  2188. // 检查是否有填空标记(但要排除选择题的括号)
  2189. if (preg_match('/(\s*)|\(\s*\)/', $stem)) {
  2190. return 'fill';
  2191. }
  2192. }
  2193. // 3. 默认返回解答题
  2194. return 'answer';
  2195. }
  2196. /**
  2197. * 格式化换行符:将字面的 \n 转换为 HTML <br> 标签
  2198. * 用于 PDF 渲染时正确显示换行
  2199. */
  2200. private function formatNewlines(?string $text): ?string
  2201. {
  2202. if ($text === null) {
  2203. return null;
  2204. }
  2205. // 【修复】替换 \n 为 <br>,但保护 LaTeX 命令如 \neq, \ne, \newline, \nu 等
  2206. // 使用负向前瞻 (?![a-zA-Z]) 避免误伤 LaTeX 命令
  2207. $text = preg_replace('/\\\\n(?![a-zA-Z])/', '<br>', $text);
  2208. // 合并连续的 <br>(最多保留2个)
  2209. return preg_replace('/(<br>\s*){3,}/', '<br><br>', $text);
  2210. }
  2211. /**
  2212. * 根据指定的题目生成PDF(新增方法)
  2213. *
  2214. * @param object $paper 虚拟试卷对象
  2215. * @param array $groupedQuestions 按题型分组的题目数据
  2216. * @param array $student 学生信息 ['name' => '', 'grade' => '']
  2217. * @param array $teacher 教师信息 ['name' => '']
  2218. * @param bool $includeGrading 是否包含判卷版本
  2219. * @return array 返回 ['pdf_url' => '...', 'grading_pdf_url' => '...']
  2220. */
  2221. public function generateByQuestions(
  2222. object $paper,
  2223. array $groupedQuestions,
  2224. array $student = [],
  2225. array $teacher = [],
  2226. bool $includeGrading = false
  2227. ): array {
  2228. Log::info('generateByQuestions 开始', [
  2229. 'paper_id' => $paper->paper_id,
  2230. 'question_counts' => [
  2231. 'choice' => count($groupedQuestions['choice'] ?? []),
  2232. 'fill' => count($groupedQuestions['fill'] ?? []),
  2233. 'answer' => count($groupedQuestions['answer'] ?? []),
  2234. ],
  2235. 'include_grading' => $includeGrading,
  2236. ]);
  2237. try {
  2238. $result = [];
  2239. // 1. 生成试卷PDF(不含答案)
  2240. $examHtml = $this->renderCustomExamHtml($paper, $groupedQuestions, $student, $teacher, false);
  2241. if ($examHtml) {
  2242. // 【修复】使用服务端 KaTeX 预渲染 LaTeX 公式
  2243. if ($this->katexRenderer) {
  2244. $examHtml = $this->katexRenderer->renderHtml($examHtml);
  2245. }
  2246. $examPdf = $this->buildPdf($examHtml);
  2247. if ($examPdf) {
  2248. $examPath = "custom_exams/{$paper->paper_id}_exam.pdf";
  2249. $examUrl = $this->pdfStorageService->put($examPath, $examPdf);
  2250. $result['pdf_url'] = $examUrl;
  2251. Log::info('试卷PDF生成成功', ['url' => $examUrl]);
  2252. }
  2253. }
  2254. // 2. 如果需要,生成判卷PDF(含答案)
  2255. if ($includeGrading) {
  2256. $gradingHtml = $this->renderCustomExamHtml($paper, $groupedQuestions, $student, $teacher, true);
  2257. if ($gradingHtml) {
  2258. // 【修复】使用服务端 KaTeX 预渲染 LaTeX 公式
  2259. if ($this->katexRenderer) {
  2260. $gradingHtml = $this->katexRenderer->renderHtml($gradingHtml);
  2261. }
  2262. $gradingPdf = $this->buildPdf($gradingHtml);
  2263. if ($gradingPdf) {
  2264. $gradingPath = "custom_exams/{$paper->paper_id}_grading.pdf";
  2265. $gradingUrl = $this->pdfStorageService->put($gradingPath, $gradingPdf);
  2266. $result['grading_pdf_url'] = $gradingUrl;
  2267. Log::info('判卷PDF生成成功', ['url' => $gradingUrl]);
  2268. }
  2269. }
  2270. }
  2271. return $result;
  2272. } catch (\Throwable $e) {
  2273. Log::error('generateByQuestions 失败', [
  2274. 'paper_id' => $paper->paper_id,
  2275. 'error' => $e->getMessage(),
  2276. 'trace' => $e->getTraceAsString(),
  2277. ]);
  2278. throw $e;
  2279. }
  2280. }
  2281. /**
  2282. * 渲染自定义题目的HTML
  2283. */
  2284. private function renderCustomExamHtml(
  2285. object $paper,
  2286. array $groupedQuestions,
  2287. array $student,
  2288. array $teacher,
  2289. bool $grading
  2290. ): ?string {
  2291. try {
  2292. $viewName = $grading ? 'pdf.exam-grading' : 'pdf.exam-paper';
  2293. $html = view($viewName, [
  2294. 'paper' => $paper,
  2295. 'questions' => $groupedQuestions,
  2296. 'student' => $student,
  2297. 'teacher' => $teacher,
  2298. 'grading' => $grading,
  2299. 'includeAnswer' => false, // exam-paper 视图需要这个变量
  2300. ])->render();
  2301. if (empty(trim($html))) {
  2302. Log::error('renderCustomExamHtml: 视图渲染结果为空', [
  2303. 'paper_id' => $paper->paper_id,
  2304. 'view_name' => $viewName,
  2305. ]);
  2306. return null;
  2307. }
  2308. return $this->ensureUtf8Html($html);
  2309. } catch (\Exception $e) {
  2310. Log::error('renderCustomExamHtml 失败', [
  2311. 'paper_id' => $paper->paper_id,
  2312. 'error' => $e->getMessage(),
  2313. 'trace' => $e->getTraceAsString(),
  2314. ]);
  2315. return null;
  2316. }
  2317. }
  2318. /**
  2319. * 生成预览 PDF(用于题目预览验证工具)
  2320. *
  2321. * @param array $questionData 题目数据 ['stem', 'options', 'answer', 'solution', 'question_type']
  2322. * @return array|null 返回 ['url' => '...'] 或 null
  2323. */
  2324. public function generatePreviewPdf(array $questionData): ?array
  2325. {
  2326. try {
  2327. Log::info('generatePreviewPdf 开始', ['question_data' => $questionData]);
  2328. // 渲染 HTML
  2329. $html = $this->renderPreviewHtml($questionData);
  2330. if (empty($html)) {
  2331. Log::error('generatePreviewPdf: HTML 渲染为空');
  2332. return null;
  2333. }
  2334. // 生成 PDF
  2335. $pdfContent = $this->buildPdf($html);
  2336. if (empty($pdfContent)) {
  2337. Log::error('generatePreviewPdf: PDF 生成为空');
  2338. return null;
  2339. }
  2340. // 保存到临时目录
  2341. $filename = 'preview_'.uniqid().'.pdf';
  2342. $path = "previews/{$filename}";
  2343. $url = $this->pdfStorageService->put($path, $pdfContent);
  2344. Log::info('generatePreviewPdf 成功', ['url' => $url]);
  2345. return ['url' => $url];
  2346. } catch (\Exception $e) {
  2347. Log::error('generatePreviewPdf 失败', [
  2348. 'error' => $e->getMessage(),
  2349. 'trace' => $e->getTraceAsString(),
  2350. ]);
  2351. return null;
  2352. }
  2353. }
  2354. /**
  2355. * 渲染预览 HTML
  2356. */
  2357. private function renderPreviewHtml(array $questionData): string
  2358. {
  2359. $stem = $questionData['stem'] ?? '';
  2360. $options = $questionData['options'] ?? null;
  2361. $answer = $questionData['answer'] ?? '';
  2362. $solution = $questionData['solution'] ?? '';
  2363. $questionType = $questionData['question_type'] ?? 'fill';
  2364. // 使用 MathFormulaProcessor 处理公式
  2365. $processedStem = MathFormulaProcessor::processFormulas($stem);
  2366. $processedAnswer = MathFormulaProcessor::processFormulas($answer);
  2367. $processedSolution = MathFormulaProcessor::processFormulas($this->formatNewlines($solution));
  2368. $processedOptions = null;
  2369. if ($options && is_array($options)) {
  2370. $processedOptions = [];
  2371. foreach ($options as $key => $value) {
  2372. $processedOptions[$key] = MathFormulaProcessor::processFormulas($value);
  2373. }
  2374. }
  2375. // 渲染 HTML
  2376. return view('pdf.question-preview', [
  2377. 'stem' => $processedStem,
  2378. 'options' => $processedOptions,
  2379. 'answer' => $processedAnswer,
  2380. 'solution' => $processedSolution,
  2381. 'questionType' => $questionType,
  2382. ])->render();
  2383. }
  2384. /**
  2385. * 批量获取知识点的讲解内容
  2386. *
  2387. * @param array $kpCodes 知识点代码数组
  2388. * @return array [kp_code => explanation]
  2389. */
  2390. public function buildExplanations(array $kpCodes): array
  2391. {
  2392. $result = [];
  2393. if (empty($kpCodes)) {
  2394. return $result;
  2395. }
  2396. try {
  2397. // 批量获取知识点讲解
  2398. $kps = \App\Models\KnowledgePoint::whereIn('kp_code', $kpCodes)->get()->keyBy('kp_code');
  2399. // 有多少算多少
  2400. foreach ($kpCodes as $kpCode) {
  2401. $kp = $kps->get($kpCode);
  2402. if ($kp && ! empty($kp->explanation)) {
  2403. $result[] = [
  2404. 'kp_code' => $kpCode,
  2405. 'kp_name' => $kp->name ?? $kpCode,
  2406. 'explanation' => $this->normalizeKpExplanation($kp->explanation),
  2407. ];
  2408. continue;
  2409. }
  2410. $result[] = [
  2411. 'kp_code' => $kpCode,
  2412. 'kp_name' => $kp->name ?? $kpCode,
  2413. 'explanation' => $this->normalizeKpExplanation(
  2414. $this->getDefaultExplanation($kpCode, $kp->name ?? $kpCode)
  2415. ),
  2416. ];
  2417. }
  2418. } catch (\Throwable $e) {
  2419. Log::warning('批量获取知识点讲解失败', [
  2420. 'kp_codes' => $kpCodes,
  2421. 'error' => $e->getMessage(),
  2422. ]);
  2423. // 失败时返回默认内容
  2424. foreach ($kpCodes as $kpCode) {
  2425. $result[] = [
  2426. 'kp_code' => $kpCode,
  2427. 'kp_name' => $kpCode,
  2428. 'explanation' => $this->normalizeKpExplanation(
  2429. $this->getDefaultExplanation($kpCode, $kpCode)
  2430. ),
  2431. ];
  2432. }
  2433. }
  2434. return $result;
  2435. }
  2436. /**
  2437. * 获取默认的知识点讲解内容
  2438. */
  2439. private function getDefaultExplanation(string $kpCode, string $kpName): string
  2440. {
  2441. // 默认讲解模板
  2442. // 注意:PHP HEREDOC 中 \e 会被解释为 ESC 字符,所以需要用 \\end 而非 \end
  2443. return <<<'MARKDOWN'
  2444. ## 知识点
  2445. (1) 核心定义:二元一次方程是含有两个未知数且每个未知数的次数都是 1 的方程,一般形式为 $ax + by = c$(其中 $a,b,c$ 为常数,且 $a,b$ 不同时为 0)。二元一次方程组是由两个(或两个以上)二元一次方程组成,常见为
  2446. $$
  2447. \begin{cases}
  2448. a_1x + b_1y = c_1\\
  2449. a_2x + b_2y = c_2
  2450. \end{cases}
  2451. $$
  2452. 方程组应用建模就是把题目中的数量关系翻译成方程组,通过求解得到实际问题的答案。
  2453. (2) 性质定理:方程组的解必须同时满足方程组中的每一个方程,因此解是两个方程公共的 $(x,y)$。常用解法有代入消元法与加减消元法:代入消元法适合某个方程易表示成 $x = \dots$ 或 $y = \dots$;加减消元法适合两个方程中某个未知数的系数相同或相反,便于相加或相减消去一个未知数。建模时常用关系包括:总量关系(如“总数 = 部分之和”)、单价数量总价关系(“$总价 = 单价 \times 数量$”)、路程速度时间关系($路程 = 速度 \times 时间$)等。
  2454. (3) 注意事项:设未知数要带单位与含义,例如“设甲买了 $x$ 支笔”;列方程要对应同一类量,别把“支数”和“元数”混在一条等式里;检查条件是否满足题意(如数量应为整数且 $> 0$);消元后别忘了回代求另一个未知数;最后答案要写清对象与单位,并可把解代回原式检验。
  2455. ## 知识点应用
  2456. - 典型例题:文具店买笔和本子。小明买了 2 支笔和 3 本本子共花 19 元;小红买了 3 支笔和 2 本本子共花 18 元。求每支笔和每本本子的单价。
  2457. - 关键步骤:
  2458. 1. 设未知数并写出含义:设每支笔单价为 $x$ 元,每本本子单价为 $y$ 元。
  2459. 2. 根据题意列方程组:由“$总价 = 单价 \times 数量$”得
  2460. $$
  2461. \begin{cases}
  2462. 2x + 3y = 19\\
  2463. 3x + 2y = 18
  2464. \end{cases}
  2465. $$
  2466. 3. 选择消元并求解:用加减消元。将第一式乘 3、第二式乘 2:
  2467. $$
  2468. \begin{cases}
  2469. 6x + 9y = 57\\
  2470. 6x + 4y = 36
  2471. \end{cases}
  2472. $$
  2473. 相减得 $5y = 21$,所以 $y = \dfrac{21}{5} = 4.2$。代入 $3x + 2y = 18$ 得 $3x + 8.4 = 18$,所以 $3x = 9.6$,$x = 3.2$。
  2474. - 结论:每支笔 3.2 元,每本本子 4.2 元(两者均 $> 0$,符合题意)。
  2475. MARKDOWN;
  2476. }
  2477. private function normalizeKpExplanation(string $content): string
  2478. {
  2479. $content = trim($content);
  2480. if ($content === '') {
  2481. return '';
  2482. }
  2483. if ($this->looksLikeHtml($content)) {
  2484. return $content;
  2485. }
  2486. if (! class_exists(\Michelf\MarkdownExtra::class)) {
  2487. $safe = htmlspecialchars($content, ENT_QUOTES, 'UTF-8');
  2488. return '<div class="kp-markdown-container kp-markdown-content">'.nl2br($safe).'</div>';
  2489. }
  2490. $parser = new \Michelf\MarkdownExtra;
  2491. $markdown = html_entity_decode($content, ENT_QUOTES, 'UTF-8');
  2492. $rendered = $parser->transform($markdown);
  2493. return '<div class="kp-markdown-container kp-markdown-content">'.$rendered.'</div>';
  2494. }
  2495. private function looksLikeHtml(string $content): bool
  2496. {
  2497. if (stripos($content, 'kp-markdown-container') !== false ||
  2498. stripos($content, 'kp-markdown-content') !== false) {
  2499. return true;
  2500. }
  2501. return (bool) preg_match('/<\s*(p|div|h[1-6]|ul|ol|li|table|span|blockquote|pre|code|br)\b/i', $content);
  2502. }
  2503. private function shouldUseDefaultExplanations(): bool
  2504. {
  2505. if (!Schema::hasTable('knowledge_points')) {
  2506. return true;
  2507. }
  2508. return !Schema::hasColumn('knowledge_points', 'explanation');
  2509. }
  2510. }