ExamPdfExportService.php 123 KB

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