ExamPdfExportService.php 126 KB

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