ExamPdfExportService.php 106 KB

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