ExamPdfExportService.php 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001
  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\PaperQuestion;
  7. use App\Models\Student;
  8. use Illuminate\Http\Request;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\File;
  11. use Illuminate\Support\Facades\Http;
  12. use Illuminate\Support\Facades\Log;
  13. use Illuminate\Support\Facades\Storage;
  14. use Illuminate\Support\Facades\URL;
  15. use Symfony\Component\Process\Exception\ProcessSignaledException;
  16. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  17. use Symfony\Component\Process\Process;
  18. /**
  19. * PDF导出服务(重构版)
  20. * 负责生成试卷PDF、判卷PDF和学情报告PDF
  21. */
  22. class ExamPdfExportService
  23. {
  24. public function __construct(
  25. private readonly LearningAnalyticsService $learningAnalyticsService,
  26. private readonly QuestionBankService $questionBankService,
  27. private readonly QuestionServiceApi $questionServiceApi,
  28. private readonly PdfStorageService $pdfStorageService,
  29. private readonly MasteryCalculator $masteryCalculator,
  30. private readonly PdfMerger $pdfMerger
  31. ) {}
  32. /**
  33. * 确保exams目录存在
  34. */
  35. private function ensureExamsDirectory(): bool
  36. {
  37. $examsDir = storage_path("app/public/exams");
  38. if (!is_dir($examsDir)) {
  39. Log::info('ExamPdfExportService: 创建exams目录', ['path' => $examsDir]);
  40. if (!mkdir($examsDir, 0755, true)) {
  41. Log::error('ExamPdfExportService: 创建exams目录失败', ['path' => $examsDir]);
  42. return false;
  43. }
  44. Log::info('ExamPdfExportService: exams目录创建成功', ['path' => $examsDir]);
  45. }
  46. return true;
  47. }
  48. /**
  49. * 生成试卷 PDF(不含答案)
  50. */
  51. public function generateExamPdf(string $paperId): ?string
  52. {
  53. Log::info('generateExamPdf 开始:', ['paper_id' => $paperId]);
  54. // 返回页面URL(用于数据库保存)
  55. $pageUrl = route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);
  56. Log::info('generateExamPdf 页面URL:', ['paper_id' => $paperId, 'url' => $pageUrl]);
  57. // 将页面URL写入数据库
  58. $this->savePdfUrlToDatabase($paperId, 'exam_pdf_url', $pageUrl);
  59. // 生成PDF文件(用于合并,不上传云存储)
  60. $pdfPath = storage_path("app/public/exams/{$paperId}_exam.pdf");
  61. // 【修复】确保exams目录存在
  62. if (!$this->ensureExamsDirectory()) {
  63. return null;
  64. }
  65. Log::info('ExamPdfExportService: 开始生成试卷PDF', ['path' => $pdfPath, 'url' => $pageUrl]);
  66. $pdfBinary = $this->buildPdfFromUrl($pageUrl);
  67. if (!$pdfBinary) {
  68. Log::error('ExamPdfExportService: 生成试卷PDF失败', ['url' => $pageUrl]);
  69. return null;
  70. }
  71. Log::info('ExamPdfExportService: PDF生成成功,开始写入文件', ['path' => $pdfPath, 'size' => strlen($pdfBinary)]);
  72. $result = file_put_contents($pdfPath, $pdfBinary);
  73. if ($result === false) {
  74. Log::error('ExamPdfExportService: 写入试卷PDF文件失败', ['path' => $pdfPath]);
  75. return null;
  76. }
  77. // 【关键修复】验证文件是否真的写入成功
  78. if (!file_exists($pdfPath)) {
  79. Log::error('ExamPdfExportService: 文件写入后不存在', ['path' => $pdfPath, 'result' => $result]);
  80. return null;
  81. }
  82. Log::info('ExamPdfExportService: 试卷PDF文件写入成功', ['path' => $pdfPath, 'size' => $result]);
  83. // 返回页面URL(不是PDF URL)
  84. return $pageUrl;
  85. }
  86. /**
  87. * 生成判卷 PDF(含答案与解析)
  88. */
  89. public function generateGradingPdf(string $paperId): ?string
  90. {
  91. Log::info('generateGradingPdf 开始:', ['paper_id' => $paperId]);
  92. // 返回页面URL(用于数据库保存)
  93. $pageUrl = route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'true']);
  94. Log::info('generateGradingPdf 页面URL:', ['paper_id' => $paperId, 'url' => $pageUrl]);
  95. // 将页面URL写入数据库
  96. $this->savePdfUrlToDatabase($paperId, 'grading_pdf_url', $pageUrl);
  97. // 生成PDF文件(用于合并,不上传云存储)
  98. $pdfPath = storage_path("app/public/exams/{$paperId}_grading.pdf");
  99. // 【修复】确保exams目录存在
  100. if (!$this->ensureExamsDirectory()) {
  101. return null;
  102. }
  103. Log::info('ExamPdfExportService: 开始生成判卷PDF', ['path' => $pdfPath, 'url' => $pageUrl]);
  104. $pdfBinary = $this->buildPdfFromUrl($pageUrl);
  105. if (!$pdfBinary) {
  106. Log::error('ExamPdfExportService: 生成判卷PDF失败', ['url' => $pageUrl]);
  107. return null;
  108. }
  109. Log::info('ExamPdfExportService: 判卷PDF生成成功,开始写入文件', ['path' => $pdfPath, 'size' => strlen($pdfBinary)]);
  110. $result = file_put_contents($pdfPath, $pdfBinary);
  111. if ($result === false) {
  112. Log::error('ExamPdfExportService: 写入判卷PDF文件失败', ['path' => $pdfPath]);
  113. return null;
  114. }
  115. // 【关键修复】验证文件是否真的写入成功
  116. if (!file_exists($pdfPath)) {
  117. Log::error('ExamPdfExportService: 判卷文件写入后不存在', ['path' => $pdfPath, 'result' => $result]);
  118. return null;
  119. }
  120. Log::info('ExamPdfExportService: 判卷PDF文件写入成功', ['path' => $pdfPath, 'size' => $result]);
  121. // 返回页面URL(不是PDF URL)
  122. return $pageUrl;
  123. }
  124. /**
  125. * 生成合并PDF(试卷 + 判卷)
  126. * 先分别生成两个PDF,然后合并
  127. * 【优化】添加进度回调支持和快速合并模式
  128. * 【修复】优化临时文件清理逻辑,确保合并成功后才删除源文件
  129. */
  130. public function generateMergedPdf(string $paperId, ?callable $progressCallback = null): ?string
  131. {
  132. Log::info('generateMergedPdf 开始:', ['paper_id' => $paperId]);
  133. // 【新增】快速幂等性检查:如果all_pdf_url已存在,直接返回
  134. $existingPaper = \App\Models\Paper::where('paper_id', $paperId)->first();
  135. if ($existingPaper && $existingPaper->all_pdf_url) {
  136. Log::info('【快速返回】合并PDF已存在,无需重新生成', [
  137. 'paper_id' => $paperId,
  138. 'existing_url' => $existingPaper->all_pdf_url
  139. ]);
  140. if ($progressCallback) {
  141. $progressCallback(100, '合并PDF已存在,直接返回');
  142. }
  143. return $existingPaper->all_pdf_url;
  144. }
  145. if ($progressCallback) {
  146. $progressCallback(0, '准备合并PDF...');
  147. }
  148. $tempDir = storage_path("app/temp");
  149. if (!is_dir($tempDir)) {
  150. mkdir($tempDir, 0755, true);
  151. }
  152. $examPdfPath = null;
  153. $gradingPdfPath = null;
  154. $mergedPdfPath = null;
  155. $mergeSuccess = false;
  156. $uploadSuccess = false;
  157. try {
  158. // 【修复】不重复生成PDF,直接使用已有的文件
  159. // 假设PDF已经通过generateExamPdf和generateGradingPdf生成过了
  160. // 获取数据库中的页面URL(用于记录)
  161. $paper = \App\Models\Paper::where('paper_id', $paperId)->first();
  162. $examPdfUrl = $paper?->exam_pdf_url;
  163. $gradingPdfUrl = $paper?->grading_pdf_url;
  164. if (!$examPdfUrl || !$gradingPdfUrl) {
  165. Log::warning('ExamPdfExportService: 未找到PDF页面URL,可能尚未生成', [
  166. 'paper_id' => $paperId,
  167. 'exam_pdf_url' => $examPdfUrl,
  168. 'grading_pdf_url' => $gradingPdfUrl
  169. ]);
  170. }
  171. Log::info('使用本地PDF文件进行合并', [
  172. 'exam_url' => $examPdfUrl,
  173. 'grading_url' => $gradingPdfUrl
  174. ]);
  175. if ($progressCallback) {
  176. $progressCallback(10, '验证PDF文件...');
  177. }
  178. // 直接使用本地PDF文件
  179. $examPdfPath = storage_path("app/public/exams/{$paperId}_exam.pdf");
  180. $gradingPdfPath = storage_path("app/public/exams/{$paperId}_grading.pdf");
  181. // 验证文件是否存在
  182. Log::info('ExamPdfExportService: 检查PDF文件是否存在', [
  183. 'exam_pdf' => $examPdfPath,
  184. 'exam_exists' => file_exists($examPdfPath),
  185. 'grading_pdf' => $gradingPdfPath,
  186. 'grading_exists' => file_exists($gradingPdfPath)
  187. ]);
  188. if (!file_exists($examPdfPath)) {
  189. Log::error('ExamPdfExportService: 试卷PDF文件不存在', [
  190. 'path' => $examPdfUrl,
  191. 'local_path' => $examPdfPath,
  192. 'directory_exists' => is_dir(dirname($examPdfPath)),
  193. 'directory_contents' => is_dir(dirname($examPdfPath)) ? scandir(dirname($examPdfPath)) : null
  194. ]);
  195. return null;
  196. }
  197. if (!file_exists($gradingPdfPath)) {
  198. Log::error('ExamPdfExportService: 判卷PDF文件不存在', [
  199. 'path' => $gradingPdfUrl,
  200. 'local_path' => $gradingPdfPath,
  201. 'directory_exists' => is_dir(dirname($gradingPdfPath)),
  202. 'directory_contents' => is_dir(dirname($gradingPdfPath)) ? scandir(dirname($gradingPdfPath)) : null
  203. ]);
  204. return null;
  205. }
  206. $examSize = filesize($examPdfPath);
  207. $gradingSize = filesize($gradingPdfPath);
  208. Log::info('PDF文件验证成功', [
  209. 'exam_pdf' => $examPdfPath,
  210. 'grading_pdf' => $gradingPdfPath,
  211. 'exam_size' => $examSize,
  212. 'grading_size' => $gradingSize,
  213. 'total_size' => $examSize + $gradingSize
  214. ]);
  215. if ($examSize < 1000 || $gradingSize < 1000) {
  216. Log::warning('ExamPdfExportService: PDF文件过小,可能生成不完整', [
  217. 'exam_size' => $examSize,
  218. 'grading_size' => $gradingSize
  219. ]);
  220. }
  221. if ($progressCallback) {
  222. $progressCallback(20, '开始合并PDF文件...');
  223. }
  224. // 【优化】合并PDF文件 - 使用快速合并模式
  225. $mergedPdfPath = $tempDir . "/{$paperId}_merged.pdf";
  226. $merged = $this->pdfMerger->mergeWithProgress([$examPdfPath, $gradingPdfPath], $mergedPdfPath, $progressCallback);
  227. if (!$merged) {
  228. Log::error('ExamPdfExportService: PDF文件合并失败', [
  229. 'tool' => $this->pdfMerger->getMergeTool(),
  230. 'exam_pdf' => $examPdfPath,
  231. 'grading_pdf' => $gradingPdfPath,
  232. 'output_pdf' => $mergedPdfPath
  233. ]);
  234. return null;
  235. }
  236. // 【新增】验证合并后的PDF内容
  237. if (!file_exists($mergedPdfPath)) {
  238. Log::error('ExamPdfExportService: 合并后PDF文件不存在', ['path' => $mergedPdfPath]);
  239. return null;
  240. }
  241. $mergedSize = filesize($mergedPdfPath);
  242. Log::info('ExamPdfExportService: 合并PDF验证', [
  243. 'merged_pdf' => $mergedPdfPath,
  244. 'merged_size' => $mergedSize,
  245. 'expected_min_size' => max($examSize, $gradingSize) + 1000,
  246. 'size_valid' => $mergedSize > max($examSize, $gradingSize)
  247. ]);
  248. // 验证合并后的PDF大小是否合理(应该大于任一源文件)
  249. if ($mergedSize <= max($examSize, $gradingSize)) {
  250. Log::warning('ExamPdfExportService: 合并PDF大小异常,可能合并失败', [
  251. 'merged_size' => $mergedSize,
  252. 'exam_size' => $examSize,
  253. 'grading_size' => $gradingSize,
  254. 'max_source_size' => max($examSize, $gradingSize)
  255. ]);
  256. }
  257. $mergeSuccess = true;
  258. if ($progressCallback) {
  259. $progressCallback(80, '上传合并PDF...');
  260. }
  261. // 读取合并后的PDF内容并上传到云存储
  262. $mergedPdfContent = file_get_contents($mergedPdfPath);
  263. if (strlen($mergedPdfContent) < 1000) {
  264. Log::error('ExamPdfExportService: 合并PDF内容过小,上传失败', [
  265. 'content_size' => strlen($mergedPdfContent),
  266. 'file_size' => $mergedSize
  267. ]);
  268. return null;
  269. }
  270. $path = "exams/{$paperId}_all.pdf";
  271. $mergedUrl = $this->pdfStorageService->put($path, $mergedPdfContent);
  272. if (!$mergedUrl) {
  273. Log::error('ExamPdfExportService: 保存合并PDF失败', ['path' => $path]);
  274. return null;
  275. }
  276. Log::info('ExamPdfExportService: 合并PDF上传成功', [
  277. 'url' => $mergedUrl,
  278. 'content_size' => strlen($mergedPdfContent),
  279. 'file_size' => $mergedSize
  280. ]);
  281. $uploadSuccess = true;
  282. // 保存到数据库的all_pdf_url字段
  283. $this->saveAllPdfUrlToDatabase($paperId, $mergedUrl);
  284. Log::info('generateMergedPdf 完成:', [
  285. 'paper_id' => $paperId,
  286. 'url' => $mergedUrl,
  287. 'tool' => $this->pdfMerger->getMergeTool(),
  288. 'exam_size' => $examSize,
  289. 'grading_size' => $gradingSize,
  290. 'merged_size' => $mergedSize
  291. ]);
  292. return $mergedUrl;
  293. } catch (\Throwable $e) {
  294. Log::error('ExamPdfExportService: 生成合并PDF失败', [
  295. 'paper_id' => $paperId,
  296. 'error' => $e->getMessage(),
  297. 'trace' => $e->getTraceAsString(),
  298. ]);
  299. if ($progressCallback) {
  300. $progressCallback(-1, '合并PDF失败: ' . $e->getMessage());
  301. }
  302. return null;
  303. } finally {
  304. // 【修复】优化临时文件清理逻辑:
  305. // 1. 合并失败时不删除源文件,便于重试
  306. // 2. 合并成功后不立即删除源文件,保留2小时用于调试
  307. // 3. 保留合并后的文件30分钟用于调试
  308. if ($mergeSuccess && $uploadSuccess) {
  309. // 【优化】合并成功且上传成功,不立即删除源文件
  310. // 改为设置未来删除时间,让源文件保留2小时
  311. $sourceFiles = [$examPdfPath, $gradingPdfPath];
  312. foreach ($sourceFiles as $file) {
  313. if ($file && file_exists($file)) {
  314. // 设置2小时后删除
  315. $deletionTime = time() + 7200; // 2小时 = 7200秒
  316. @touch($file, $deletionTime);
  317. Log::info('源PDF文件将在2小时后自动删除', [
  318. 'path' => $file,
  319. 'deletion_time' => date('Y-m-d H:i:s', $deletionTime)
  320. ]);
  321. }
  322. }
  323. // 保留合并文件30分钟后删除
  324. if ($mergedPdfPath && file_exists($mergedPdfPath)) {
  325. $deletionTime = time() + 1800; // 30分钟后
  326. @touch($mergedPdfPath, $deletionTime);
  327. Log::info('合并PDF文件保留30分钟用于调试', [
  328. 'path' => $mergedPdfPath,
  329. 'deletion_time' => date('Y-m-d H:i:s', $deletionTime)
  330. ]);
  331. }
  332. } else {
  333. // 合并失败或上传失败,保留所有文件用于调试
  334. Log::warning('PDF合并未完全成功,保留临时文件用于调试', [
  335. 'merge_success' => $mergeSuccess,
  336. 'upload_success' => $uploadSuccess,
  337. 'exam_pdf' => $examPdfPath,
  338. 'grading_pdf' => $gradingPdfPath,
  339. 'merged_pdf' => $mergedPdfPath,
  340. 'exam_exists' => $examPdfPath ? file_exists($examPdfPath) : false,
  341. 'grading_exists' => $gradingPdfPath ? file_exists($gradingPdfPath) : false,
  342. 'merged_exists' => $mergedPdfPath ? file_exists($mergedPdfPath) : false
  343. ]);
  344. }
  345. Log::debug('PDF合并流程完成', [
  346. 'merge_success' => $mergeSuccess,
  347. 'upload_success' => $uploadSuccess
  348. ]);
  349. }
  350. }
  351. /**
  352. * 将URL转换为本地文件路径
  353. */
  354. private function convertUrlToPath(string $url): ?string
  355. {
  356. // 如果是本地存储,URL格式类似:/storage/exams/paper_id_exam.pdf
  357. // 需要转换为绝对路径
  358. if (strpos($url, '/storage/') === 0) {
  359. return public_path(ltrim($url, '/'));
  360. }
  361. // 如果是完整路径,直接返回
  362. if (strpos($url, '/') === 0 && file_exists($url)) {
  363. return $url;
  364. }
  365. // 如果是相对路径,转换为绝对路径
  366. $path = public_path($url);
  367. if (file_exists($path)) {
  368. return $path;
  369. }
  370. return null;
  371. }
  372. /**
  373. * 保存合并PDF URL到数据库
  374. */
  375. private function saveAllPdfUrlToDatabase(string $paperId, string $url): void
  376. {
  377. try {
  378. \App\Models\Paper::where('paper_id', $paperId)->update([
  379. 'all_pdf_url' => $url
  380. ]);
  381. Log::debug('保存all_pdf_url成功', ['paper_id' => $paperId, 'url' => $url]);
  382. } catch (\Exception $e) {
  383. Log::error('保存all_pdf_url失败', [
  384. 'paper_id' => $paperId,
  385. 'url' => $url,
  386. 'error' => $e->getMessage()
  387. ]);
  388. throw $e;
  389. }
  390. }
  391. /**
  392. * 生成学情分析 PDF
  393. */
  394. public function generateAnalysisReportPdf(string $paperId, string $studentId, ?string $recordId = null): ?string
  395. {
  396. if (function_exists('set_time_limit')) {
  397. @set_time_limit(240);
  398. }
  399. try {
  400. // 【调试】打印输入参数
  401. Log::info('ExamPdfExportService: 开始生成学情分析PDF', [
  402. 'paper_id' => $paperId,
  403. 'student_id' => $studentId,
  404. 'record_id' => $recordId,
  405. ]);
  406. // 构建分析数据
  407. $analysisData = $this->buildAnalysisData($paperId, $studentId);
  408. if (!$analysisData) {
  409. Log::warning('ExamPdfExportService: buildAnalysisData返回空数据', [
  410. 'paper_id' => $paperId,
  411. 'student_id' => $studentId,
  412. ]);
  413. return null;
  414. }
  415. Log::info('ExamPdfExportService: buildAnalysisData返回数据', [
  416. 'paper_id' => $paperId,
  417. 'student_id' => $studentId,
  418. 'analysisData_keys' => array_keys($analysisData),
  419. 'mastery_count' => count($analysisData['mastery']['items'] ?? []),
  420. 'questions_count' => count($analysisData['questions'] ?? []),
  421. ]);
  422. // 创建DTO
  423. $dto = ExamAnalysisDataDto::fromArray($analysisData);
  424. $payloadDto = ReportPayloadDto::fromExamAnalysisDataDto($dto);
  425. // 【调试】打印传给模板的数据
  426. $templateData = $payloadDto->toArray();
  427. Log::info('ExamPdfExportService: 传给模板的数据', [
  428. 'paper' => $templateData['paper'] ?? null,
  429. 'student' => $templateData['student'] ?? null,
  430. 'mastery' => $templateData['mastery'] ?? null,
  431. 'parent_mastery_levels' => $templateData['parent_mastery_levels'] ?? null, // 新增:检查父节点掌握度
  432. 'questions_count' => count($templateData['questions'] ?? []),
  433. 'insights_count' => count($templateData['question_insights'] ?? []),
  434. 'recommendations_count' => count($templateData['recommendations'] ?? []),
  435. ]);
  436. // 渲染HTML
  437. $html = view('exam-analysis.pdf-report', $templateData)->render();
  438. if (!$html) {
  439. Log::error('ExamPdfExportService: 渲染HTML为空', ['paper_id' => $paperId]);
  440. return null;
  441. }
  442. // 生成PDF
  443. $pdfBinary = $this->buildPdf($html);
  444. if (!$pdfBinary) {
  445. return null;
  446. }
  447. // 保存PDF
  448. $version = time();
  449. $path = "analysis_reports/{$paperId}_{$studentId}_{$version}.pdf";
  450. $url = $this->pdfStorageService->put($path, $pdfBinary);
  451. if (!$url) {
  452. Log::error('ExamPdfExportService: 保存学情PDF失败', ['path' => $path]);
  453. return null;
  454. }
  455. // 保存URL到数据库
  456. $this->saveAnalysisPdfUrl($paperId, $studentId, $recordId, $url);
  457. return $url;
  458. } catch (\Throwable $e) {
  459. Log::error('ExamPdfExportService: 生成学情分析PDF失败', [
  460. 'paper_id' => $paperId,
  461. 'student_id' => $studentId,
  462. 'record_id' => $recordId,
  463. 'error' => $e->getMessage(),
  464. 'exception' => get_class($e),
  465. 'trace' => $e->getTraceAsString(),
  466. ]);
  467. return null;
  468. }
  469. }
  470. /**
  471. * 渲染并存储试卷PDF
  472. */
  473. private function renderAndStoreExamPdf(
  474. string $paperId,
  475. bool $includeAnswer,
  476. string $suffix,
  477. bool $useGradingView = false
  478. ): ?string {
  479. // 放宽脚本执行时间
  480. if (function_exists('set_time_limit')) {
  481. @set_time_limit(240);
  482. }
  483. try {
  484. $html = $this->renderExamHtml($paperId, $includeAnswer, $useGradingView);
  485. if (!$html) {
  486. Log::error('ExamPdfExportService: 渲染HTML为空', [
  487. 'paper_id' => $paperId,
  488. 'include_answer' => $includeAnswer,
  489. 'use_grading_view' => $useGradingView,
  490. ]);
  491. return null;
  492. }
  493. $pdfBinary = $this->buildPdf($html);
  494. if (!$pdfBinary) {
  495. Log::error('ExamPdfExportService: buildPdf为空', [
  496. 'paper_id' => $paperId,
  497. 'include_answer' => $includeAnswer,
  498. 'use_grading_view' => $useGradingView,
  499. ]);
  500. return null;
  501. }
  502. $path = "exams/{$paperId}_{$suffix}.pdf";
  503. $url = $this->pdfStorageService->put($path, $pdfBinary);
  504. if (!$url) {
  505. Log::error('ExamPdfExportService: 保存PDF失败', ['path' => $path]);
  506. return null;
  507. }
  508. return $url;
  509. } catch (\Throwable $e) {
  510. Log::error('ExamPdfExportService: 生成PDF失败', [
  511. 'paper_id' => $paperId,
  512. 'suffix' => $suffix,
  513. 'error' => $e->getMessage(),
  514. 'exception' => get_class($e),
  515. 'trace' => $e->getTraceAsString(),
  516. ]);
  517. return null;
  518. }
  519. }
  520. /**
  521. * 渲染试卷HTML(重构版)
  522. */
  523. private function renderExamHtml(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
  524. {
  525. // 直接构造请求URL,使用路由生成HTML
  526. $routeName = $useGradingView
  527. ? 'filament.admin.auth.intelligent-exam.grading'
  528. : 'filament.admin.auth.intelligent-exam.pdf';
  529. $url = route($routeName, ['paper_id' => $paperId, 'answer' => $includeAnswer ? 'true' : 'false']);
  530. // 使用HTTP客户端获取渲染后的HTML
  531. try {
  532. $response = Http::get($url);
  533. if ($response->successful()) {
  534. $html = $response->body();
  535. if (!empty(trim($html))) {
  536. return $this->ensureUtf8Html($html);
  537. } else {
  538. Log::warning('ExamPdfExportService: HTTP返回的HTML为空,使用备用方案', [
  539. 'paper_id' => $paperId,
  540. 'url' => $url,
  541. ]);
  542. }
  543. }
  544. } catch (\Exception $e) {
  545. Log::warning('ExamPdfExportService: 通过HTTP获取HTML失败,使用备用方案', [
  546. 'paper_id' => $paperId,
  547. 'error' => $e->getMessage(),
  548. ]);
  549. }
  550. // 备用方案:直接渲染视图(如果路由不可用)
  551. try {
  552. $paper = Paper::with('questions')->find($paperId);
  553. if (!$paper) {
  554. Log::error('ExamPdfExportService: 试卷不存在,备用方案无法渲染', [
  555. 'paper_id' => $paperId,
  556. 'include_answer' => $includeAnswer,
  557. 'use_grading_view' => $useGradingView,
  558. ]);
  559. return null;
  560. }
  561. // 检查试卷是否有题目
  562. if ($paper->questions->isEmpty()) {
  563. Log::error('ExamPdfExportService: 试卷没有题目数据', [
  564. 'paper_id' => $paperId,
  565. 'question_count' => 0,
  566. ]);
  567. return null;
  568. }
  569. $viewName = $useGradingView ? 'exam-pdf.grading' : 'exam-pdf.student';
  570. $html = view($viewName, compact('paper'))->render();
  571. if (empty(trim($html))) {
  572. Log::error('ExamPdfExportService: 视图渲染结果为空', [
  573. 'paper_id' => $paperId,
  574. 'view_name' => $viewName,
  575. 'question_count' => $paper->questions->count(),
  576. ]);
  577. return null;
  578. }
  579. return $this->ensureUtf8Html($html);
  580. } catch (\Exception $e) {
  581. Log::error('ExamPdfExportService: 备用方案渲染失败', [
  582. 'paper_id' => $paperId,
  583. 'error' => $e->getMessage(),
  584. 'trace' => $e->getTraceAsString(),
  585. ]);
  586. return null;
  587. }
  588. }
  589. /**
  590. * 构建分析数据(重构版)
  591. * 优先使用本地MySQL数据,减少API依赖
  592. */
  593. private function buildAnalysisData(string $paperId, string $studentId): ?array
  594. {
  595. // 【关键调试】确认方法被调用
  596. Log::warning('ExamPdfExportService: buildAnalysisData方法被调用了!', [
  597. 'paper_id' => $paperId,
  598. 'student_id' => $studentId,
  599. 'timestamp' => now()->toISOString()
  600. ]);
  601. $paper = Paper::with(['questions' => function ($query) {
  602. $query->orderBy('question_number')->orderBy('id');
  603. }])->find($paperId);
  604. if (!$paper) {
  605. Log::warning('ExamPdfExportService: 未找到试卷,将尝试仅基于分析数据生成PDF', [
  606. 'paper_id' => $paperId,
  607. 'student_id' => $studentId,
  608. ]);
  609. // 【修复】即使试卷不存在,也尝试基于分析数据生成PDF
  610. $paper = new \stdClass();
  611. $paper->paper_id = $paperId;
  612. $paper->paper_name = "学情分析报告_{$studentId}_{$paperId}";
  613. $paper->question_count = 0;
  614. $paper->total_score = 0;
  615. $paper->created_at = now();
  616. $paper->questions = collect();
  617. }
  618. $student = Student::find($studentId);
  619. $studentInfo = [
  620. 'id' => $student?->student_id ?? $studentId,
  621. 'name' => $student?->name ?? $studentId,
  622. 'grade' => $student?->grade ?? '未知年级',
  623. 'class' => $student?->class_name ?? '未知班级',
  624. ];
  625. // 【修改】直接从本地数据库获取分析数据(不再调用API)
  626. $analysisData = [];
  627. // 首先尝试从paper->analysis_id获取
  628. if (!empty($paper->analysis_id)) {
  629. Log::info('ExamPdfExportService: 从本地数据库获取试卷分析数据', [
  630. 'paper_id' => $paperId,
  631. 'student_id' => $studentId,
  632. 'analysis_id' => $paper->analysis_id
  633. ]);
  634. $analysisRecord = \DB::table('exam_analysis_results')
  635. ->where('id', $paper->analysis_id)
  636. ->where('student_id', $studentId)
  637. ->first();
  638. if ($analysisRecord && !empty($analysisRecord->analysis_data)) {
  639. $analysisData = json_decode($analysisRecord->analysis_data, true);
  640. Log::info('ExamPdfExportService: 成功获取本地分析数据(通过analysis_id)', [
  641. 'data_size' => strlen($analysisRecord->analysis_data)
  642. ]);
  643. } else {
  644. Log::warning('ExamPdfExportService: 未找到本地分析数据,将尝试其他方式', [
  645. 'paper_id' => $paperId,
  646. 'student_id' => $studentId,
  647. 'analysis_id' => $paper->analysis_id
  648. ]);
  649. }
  650. }
  651. // 如果没有analysis_id或未找到数据,直接从exam_analysis_results表查询
  652. if (empty($analysisData)) {
  653. Log::info('ExamPdfExportService: 直接从exam_analysis_results表查询分析数据', [
  654. 'paper_id' => $paperId,
  655. 'student_id' => $studentId
  656. ]);
  657. $analysisRecord = \DB::table('exam_analysis_results')
  658. ->where('paper_id', $paperId)
  659. ->where('student_id', $studentId)
  660. ->first();
  661. if ($analysisRecord && !empty($analysisRecord->analysis_data)) {
  662. $analysisData = json_decode($analysisRecord->analysis_data, true);
  663. Log::info('ExamPdfExportService: 成功获取本地分析数据(直接查询)', [
  664. 'data_size' => strlen($analysisRecord->analysis_data),
  665. 'question_count' => count($analysisData['question_analysis'] ?? [])
  666. ]);
  667. } else {
  668. Log::warning('ExamPdfExportService: 未找到任何分析数据,将使用空数据', [
  669. 'paper_id' => $paperId,
  670. 'student_id' => $studentId
  671. ]);
  672. }
  673. }
  674. // 【修复】优先使用analysisData中的knowledge_point_analysis数据
  675. $masteryData = [];
  676. $parentMasteryLevels = []; // 新增:父节点掌握度数据
  677. Log::info('ExamPdfExportService: 开始处理掌握度数据', [
  678. 'student_id' => $studentId,
  679. 'analysisData_keys' => array_keys($analysisData),
  680. 'has_knowledge_point_analysis' => !empty($analysisData['knowledge_point_analysis']),
  681. ]);
  682. if (!empty($analysisData['knowledge_point_analysis'])) {
  683. // 将knowledge_point_analysis转换为buildMasterySummary期望的格式
  684. foreach ($analysisData['knowledge_point_analysis'] as $kp) {
  685. $masteryData[] = [
  686. 'kp_code' => $kp['kp_id'] ?? null,
  687. 'kp_name' => $kp['kp_id'] ?? '未知知识点',
  688. 'mastery_level' => $kp['mastery_level'] ?? 0,
  689. 'mastery_change' => $kp['change'] ?? null,
  690. ];
  691. }
  692. // 【修复】基于所有兄弟节点历史数据计算父节点掌握度,并获取掌握度变化
  693. try {
  694. // 获取本次考试涉及的知识点代码列表
  695. $examKpCodes = array_column($masteryData, 'kp_code');
  696. Log::info('ExamPdfExportService: 本次考试涉及的知识点', [
  697. 'count' => count($examKpCodes),
  698. 'kp_codes' => $examKpCodes
  699. ]);
  700. // 获取上一个快照的数据(用于计算变化)
  701. // 如果没有其他试卷的记录,使用同一试卷的上一次快照
  702. $lastSnapshot = DB::connection('mysql')
  703. ->table('knowledge_point_mastery_snapshots')
  704. ->where('student_id', $studentId)
  705. ->where('paper_id', $paper->paper_id)
  706. ->where('snapshot_id', '!=', "snap_{$paper->paper_id}_" . date('YmdHis'))
  707. ->latest('snapshot_time')
  708. ->first();
  709. $previousMasteryData = [];
  710. if ($lastSnapshot) {
  711. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  712. foreach ($previousMasteryJson as $kpCode => $data) {
  713. $previousMasteryData[$kpCode] = [
  714. 'current_mastery' => $data['current_mastery'] ?? 0,
  715. 'previous_mastery' => $data['previous_mastery'] ?? null,
  716. ];
  717. }
  718. Log::info('ExamPdfExportService: 获取到上一次快照数据', [
  719. 'snapshot_time' => $lastSnapshot->snapshot_time,
  720. 'kp_count' => count($previousMasteryData)
  721. ]);
  722. }
  723. // 为当前知识点添加变化数据
  724. foreach ($masteryData as &$item) {
  725. $kpCode = $item['kp_code'];
  726. if (isset($previousMasteryData[$kpCode])) {
  727. $previous = floatval($previousMasteryData[$kpCode]['previous_mastery'] ?? 0);
  728. $current = floatval($item['mastery_level']);
  729. $item['mastery_change'] = $current - $previous;
  730. }
  731. }
  732. unset($item); // 解除引用
  733. // 获取所有父节点掌握度
  734. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  735. $allParentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? [];
  736. // 计算与本次考试相关的父节点掌握度(基于所有兄弟节点)
  737. $parentMasteryLevels = [];
  738. // 【修复】使用数据库查询正确匹配父子关系,而不是字符串前缀
  739. foreach ($allParentMasteryLevels as $parentKpCode => $parentMastery) {
  740. // 查询这个父节点的所有子节点
  741. $childNodes = DB::connection('mysql')
  742. ->table('knowledge_points')
  743. ->where('parent_kp_code', $parentKpCode)
  744. ->pluck('kp_code')
  745. ->toArray();
  746. // 检查是否有子节点在本次考试中出现
  747. $relevantChildren = array_intersect($examKpCodes, $childNodes);
  748. if (!empty($relevantChildren)) {
  749. // 【修复】计算父节点变化:基于所有子节点的平均变化
  750. $childChanges = [];
  751. foreach ($relevantChildren as $childKpCode) {
  752. $previousChild = $previousMasteryData[$childKpCode]['previous_mastery'] ?? null;
  753. $currentChild = null;
  754. foreach ($masteryData as $item) {
  755. if ($item['kp_code'] === $childKpCode) {
  756. $currentChild = $item['mastery_level'];
  757. break;
  758. }
  759. }
  760. if ($previousChild !== null && $currentChild !== null) {
  761. $childChanges[] = floatval($currentChild) - floatval($previousChild);
  762. }
  763. }
  764. $avgChange = !empty($childChanges) ? array_sum($childChanges) / count($childChanges) : null;
  765. // 获取父节点中文名称
  766. $parentKpInfo = DB::connection('mysql')
  767. ->table('knowledge_points')
  768. ->where('kp_code', $parentKpCode)
  769. ->first();
  770. $parentMasteryLevels[$parentKpCode] = [
  771. 'kp_code' => $parentKpCode,
  772. 'kp_name' => $parentKpInfo->name ?? $parentKpCode,
  773. 'mastery_level' => $parentMastery,
  774. 'mastery_percentage' => round($parentMastery * 100, 1),
  775. 'mastery_change' => $avgChange,
  776. 'children' => $relevantChildren,
  777. ];
  778. }
  779. }
  780. Log::info('ExamPdfExportService: 过滤后的父节点掌握度', [
  781. 'all_parent_count' => count($allParentMasteryLevels),
  782. 'filtered_parent_count' => count($parentMasteryLevels),
  783. 'filtered_codes' => array_keys($parentMasteryLevels)
  784. ]);
  785. } catch (\Exception $e) {
  786. Log::warning('ExamPdfExportService: 获取父节点掌握度失败', [
  787. 'error' => $e->getMessage()
  788. ]);
  789. }
  790. Log::info('ExamPdfExportService: 使用analysisData中的掌握度数据', [
  791. 'count' => count($masteryData),
  792. 'masteryData_sample' => !empty($masteryData) ? array_slice($masteryData, 0, 2) : []
  793. ]);
  794. } else {
  795. // 如果没有knowledge_point_analysis,使用MasteryCalculator获取多层级掌握度概览
  796. try {
  797. Log::info('ExamPdfExportService: 获取学生多层级掌握度概览', [
  798. 'student_id' => $studentId
  799. ]);
  800. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  801. $masteryData = $masteryOverview['details'] ?? [];
  802. $parentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? []; // 获取父节点掌握度
  803. // 【修复】将对象数组转换为关联数组(避免 stdClass 对象访问错误)
  804. if (!empty($masteryData) && is_array($masteryData)) {
  805. $masteryData = array_map(function($item) {
  806. if (is_object($item)) {
  807. return [
  808. 'kp_code' => $item->kp_code ?? null,
  809. 'kp_name' => $item->kp_name ?? null,
  810. 'mastery_level' => floatval($item->mastery_level ?? 0),
  811. 'mastery_change' => $item->mastery_change !== null ? floatval($item->mastery_change) : null,
  812. ];
  813. }
  814. return $item;
  815. }, $masteryData);
  816. }
  817. // 【修复】获取快照数据以计算掌握度变化
  818. $lastSnapshot = DB::connection('mysql')
  819. ->table('knowledge_point_mastery_snapshots')
  820. ->where('student_id', $studentId)
  821. ->latest('snapshot_time')
  822. ->first();
  823. if ($lastSnapshot) {
  824. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  825. foreach ($masteryData as &$item) {
  826. $kpCode = $item['kp_code'];
  827. if (isset($previousMasteryJson[$kpCode])) {
  828. $previous = floatval($previousMasteryJson[$kpCode]['previous_mastery'] ?? 0);
  829. $current = floatval($item['mastery_level']);
  830. $item['mastery_change'] = $current - $previous;
  831. }
  832. }
  833. unset($item);
  834. }
  835. Log::info('ExamPdfExportService: 成功获取多层级掌握度数据', [
  836. 'count' => count($masteryData),
  837. 'parent_count' => count($parentMasteryLevels)
  838. ]);
  839. } catch (\Exception $e) {
  840. Log::error('ExamPdfExportService: 获取掌握度数据失败', [
  841. 'student_id' => $studentId,
  842. 'error' => $e->getMessage()
  843. ]);
  844. }
  845. }
  846. // 【修改】使用本地方法获取学习路径推荐(替代API调用)
  847. $recommendations = [];
  848. try {
  849. Log::info('ExamPdfExportService: 获取学习路径推荐', [
  850. 'student_id' => $studentId
  851. ]);
  852. $learningPaths = $this->learningAnalyticsService->recommendLearningPaths($studentId, 3);
  853. $recommendations = $learningPaths['recommendations'] ?? [];
  854. Log::info('ExamPdfExportService: 成功获取学习路径推荐', [
  855. 'count' => count($recommendations)
  856. ]);
  857. } catch (\Exception $e) {
  858. Log::error('ExamPdfExportService: 获取学习路径推荐失败', [
  859. 'student_id' => $studentId,
  860. 'error' => $e->getMessage()
  861. ]);
  862. }
  863. // 获取知识点名称映射
  864. $kpNameMap = $this->buildKnowledgePointNameMap();
  865. Log::info('ExamPdfExportService: 获取知识点名称映射', [
  866. 'kpNameMap_count' => count($kpNameMap),
  867. 'kpNameMap_keys_sample' => !empty($kpNameMap) ? array_slice(array_keys($kpNameMap), 0, 5) : []
  868. ]);
  869. // 【修复】直接从MySQL数据库获取题目详情(不通过API)
  870. $questionDetails = $this->getQuestionDetailsFromMySQL($paper);
  871. // 处理题目数据
  872. $questions = $this->processQuestionsForReport($paper, $questionDetails, $kpNameMap);
  873. // 【关键调试】查看buildMasterySummary的返回结果
  874. $masterySummary = $this->buildMasterySummary($masteryData, $kpNameMap);
  875. Log::info('ExamPdfExportService: buildMasterySummary返回结果', [
  876. 'masteryData_count' => count($masteryData),
  877. 'kpNameMap_count' => count($kpNameMap),
  878. 'masterySummary_keys' => array_keys($masterySummary),
  879. 'masterySummary_items_count' => count($masterySummary['items'] ?? []),
  880. 'masterySummary_items_sample' => !empty($masterySummary['items']) ? array_slice($masterySummary['items'], 0, 2) : []
  881. ]);
  882. // 【修复】处理父节点掌握度数据:过滤零值、转换名称、构建层级关系
  883. $examKpCodes = array_column($masteryData, 'kp_code'); // 本次考试涉及的知识点
  884. $processedParentMastery = $this->processParentMasteryLevels($parentMasteryLevels, $kpNameMap, $examKpCodes);
  885. Log::info('ExamPdfExportService: 处理后的父节点掌握度', [
  886. 'raw_count' => count($parentMasteryLevels),
  887. 'processed_count' => count($processedParentMastery),
  888. 'processed_sample' => !empty($processedParentMastery) ? array_slice($processedParentMastery, 0, 3) : []
  889. ]);
  890. return [
  891. 'paper' => [
  892. 'id' => $paper->paper_id,
  893. 'name' => $paper->paper_name,
  894. 'total_questions' => $paper->question_count,
  895. 'total_score' => $paper->total_score,
  896. 'created_at' => $paper->created_at,
  897. ],
  898. 'student' => $studentInfo,
  899. 'questions' => $questions,
  900. 'mastery' => $masterySummary,
  901. 'parent_mastery_levels' => $processedParentMastery, // 【修复】使用处理后的父节点数据
  902. 'insights' => $analysisData['question_analysis'] ?? [], // 使用question_analysis替代question_results
  903. 'recommendations' => $recommendations,
  904. 'analysis_data' => $analysisData,
  905. ];
  906. }
  907. /**
  908. * 【修复】直接从PaperQuestion表获取题目详情(不通过API)
  909. */
  910. private function getQuestionDetailsFromMySQL(Paper $paper): array
  911. {
  912. $details = [];
  913. Log::info('ExamPdfExportService: 从PaperQuestion表查询题目详情', [
  914. 'paper_id' => $paper->paper_id,
  915. 'question_count' => $paper->questions->count()
  916. ]);
  917. foreach ($paper->questions as $pq) {
  918. try {
  919. // 【关键修复】直接从PaperQuestion对象获取solution和correct_answer
  920. $detail = [
  921. 'id' => $pq->question_id,
  922. 'content' => $pq->question_text,
  923. 'question_type' => $pq->question_type,
  924. 'answer' => $pq->correct_answer ?? null, // 【修复】从PaperQuestion获取正确答案
  925. 'solution' => $pq->solution ?? null, // 【修复】从PaperQuestion获取解题思路
  926. ];
  927. $details[(string) ($pq->question_id ?? $pq->id)] = $detail;
  928. Log::debug('ExamPdfExportService: 成功获取题目详情', [
  929. 'paper_question_id' => $pq->id,
  930. 'question_id' => $pq->question_id,
  931. 'has_answer' => !empty($pq->correct_answer),
  932. 'has_solution' => !empty($pq->solution),
  933. 'answer_preview' => $pq->correct_answer ? substr($pq->correct_answer, 0, 50) : null
  934. ]);
  935. } catch (\Throwable $e) {
  936. Log::error('ExamPdfExportService: 获取题目详情失败', [
  937. 'paper_question_id' => $pq->id,
  938. 'error' => $e->getMessage(),
  939. ]);
  940. }
  941. }
  942. return $details;
  943. }
  944. /**
  945. * 处理题目数据(用于报告)
  946. */
  947. private function processQuestionsForReport($paper, array $questionDetails, array $kpNameMap): array
  948. {
  949. $grouped = [
  950. 'choice' => [],
  951. 'fill' => [],
  952. 'answer' => [],
  953. ];
  954. // 【修复】处理空的试卷(questions可能不存在)
  955. $questions = $paper->questions ?? collect();
  956. if ($questions->isEmpty()) {
  957. Log::info('ExamPdfExportService: 试卷没有题目,返回空数组');
  958. return $grouped;
  959. }
  960. $sortedQuestions = $questions
  961. ->sortBy(function ($q, int $idx) {
  962. $number = $q->question_number ?? $idx + 1;
  963. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  964. });
  965. foreach ($sortedQuestions as $idx => $question) {
  966. $kpCode = $question->knowledge_point ?? '';
  967. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  968. // 【修复】直接从PaperQuestion对象获取solution和correct_answer
  969. $answer = $question->correct_answer ?? null; // 直接从PaperQuestion获取
  970. $solution = $question->solution ?? null; // 直接从PaperQuestion获取
  971. $detail = $questionDetails[(string) ($question->question_id ?? $question->id)] ?? [];
  972. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  973. $normalizedType = $this->normalizeQuestionType($typeRaw);
  974. $number = $question->question_number ?? ($idx + 1);
  975. $payload = [
  976. 'question_number' => $number,
  977. 'question_text' => is_array($question->question_text)
  978. ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
  979. : ($question->question_text ?? ''),
  980. 'question_type' => $normalizedType,
  981. 'knowledge_point' => $kpCode,
  982. 'knowledge_point_name' => $kpName,
  983. 'score' => $question->score,
  984. 'answer' => $answer, // 正确答案
  985. 'solution' => $solution, // 解题思路
  986. 'student_answer' => $question->student_answer ?? null, // 【新增】学生答案
  987. 'correct_answer' => $answer, // 【新增】正确答案
  988. 'is_correct' => $question->is_correct ?? null, // 【新增】判分结果
  989. 'score_obtained' => $question->score_obtained ?? null, // 【新增】得分
  990. ];
  991. $grouped[$normalizedType][] = $payload;
  992. // 【调试】记录题目数据
  993. Log::debug('ExamPdfExportService: 处理题目数据', [
  994. 'paper_question_id' => $question->id,
  995. 'question_id' => $question->question_id,
  996. 'has_answer' => !empty($answer),
  997. 'has_solution' => !empty($solution),
  998. 'answer_preview' => $answer ? substr($answer, 0, 50) : null
  999. ]);
  1000. }
  1001. $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  1002. // 按卷面顺序重新编号
  1003. foreach ($ordered as $i => &$q) {
  1004. $q['display_number'] = $i + 1;
  1005. }
  1006. unset($q);
  1007. return $ordered;
  1008. }
  1009. /**
  1010. * 构建PDF
  1011. */
  1012. private function buildPdf(string $html): ?string
  1013. {
  1014. Log::info('ExamPdfExportService: buildPdf开始', ['html_size' => strlen($html)]);
  1015. $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_') . '.html';
  1016. Log::info('ExamPdfExportService: 创建临时HTML文件', ['tmp_html' => $tmpHtml]);
  1017. $utf8Html = $this->ensureUtf8Html($html);
  1018. file_put_contents($tmpHtml, $utf8Html);
  1019. Log::info('ExamPdfExportService: HTML文件已写入', ['tmp_html' => $tmpHtml, 'size' => filesize($tmpHtml)]);
  1020. // 仅使用Chrome渲染
  1021. Log::info('ExamPdfExportService: 开始调用renderWithChrome', ['tmp_html' => $tmpHtml]);
  1022. $chromePdf = $this->renderWithChrome($tmpHtml);
  1023. Log::info('ExamPdfExportService: renderWithChrome完成', [
  1024. 'pdf_size' => $chromePdf ? strlen($chromePdf) : 0,
  1025. 'pdf_success' => !empty($chromePdf)
  1026. ]);
  1027. @unlink($tmpHtml);
  1028. return $chromePdf;
  1029. }
  1030. /**
  1031. * 从URL生成PDF
  1032. */
  1033. private function buildPdfFromUrl(string $url): ?string
  1034. {
  1035. Log::info('ExamPdfExportService: buildPdfFromUrl开始', ['url' => $url]);
  1036. try {
  1037. $response = Http::get($url);
  1038. Log::info('ExamPdfExportService: HTTP请求完成', [
  1039. 'url' => $url,
  1040. 'status' => $response->status(),
  1041. 'successful' => $response->successful()
  1042. ]);
  1043. if (!$response->successful()) {
  1044. Log::error('ExamPdfExportService: 获取URL内容失败', [
  1045. 'url' => $url,
  1046. 'status_code' => $response->status()
  1047. ]);
  1048. return null;
  1049. }
  1050. $html = $response->body();
  1051. $htmlSize = strlen($html);
  1052. Log::info('ExamPdfExportService: 获取HTML内容成功', [
  1053. 'url' => $url,
  1054. 'html_size' => $htmlSize,
  1055. 'html_preview' => substr($html, 0, 100)
  1056. ]);
  1057. if (empty($html)) {
  1058. Log::error('ExamPdfExportService: URL返回内容为空', ['url' => $url]);
  1059. return null;
  1060. }
  1061. Log::info('ExamPdfExportService: 开始调用buildPdf', ['html_size' => $htmlSize]);
  1062. $pdfBinary = $this->buildPdf($html);
  1063. Log::info('ExamPdfExportService: buildPdf完成', [
  1064. 'pdf_size' => $pdfBinary ? strlen($pdfBinary) : 0,
  1065. 'pdf_success' => !empty($pdfBinary)
  1066. ]);
  1067. return $pdfBinary;
  1068. } catch (\Exception $e) {
  1069. Log::error('ExamPdfExportService: buildPdfFromUrl异常', [
  1070. 'url' => $url,
  1071. 'error' => $e->getMessage(),
  1072. 'trace' => $e->getTraceAsString()
  1073. ]);
  1074. return null;
  1075. }
  1076. }
  1077. /**
  1078. * 使用Chrome渲染PDF
  1079. */
  1080. private function renderWithChrome(string $htmlPath): ?string
  1081. {
  1082. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_') . '.pdf';
  1083. $userDataDir = sys_get_temp_dir() . '/chrome-profile-' . uniqid();
  1084. $chromeBinary = $this->findChromeBinary();
  1085. if (!$chromeBinary) {
  1086. Log::error('ExamPdfExportService: 未找到可用的Chrome/Chromium');
  1087. return null;
  1088. }
  1089. Log::info('ExamPdfExportService: 开始Chrome渲染', [
  1090. 'html_path' => $htmlPath,
  1091. 'tmp_pdf' => $tmpPdf,
  1092. 'chrome_binary' => $chromeBinary
  1093. ]);
  1094. // 设置运行时目录
  1095. $runtimeHome = sys_get_temp_dir() . '/chrome-home';
  1096. $runtimeXdg = sys_get_temp_dir() . '/chrome-xdg';
  1097. if (!File::exists($runtimeHome)) {
  1098. @File::makeDirectory($runtimeHome, 0755, true);
  1099. }
  1100. if (!File::exists($runtimeXdg)) {
  1101. @File::makeDirectory($runtimeXdg, 0755, true);
  1102. }
  1103. // 【性能优化】深度优化Chrome参数,提升渲染速度
  1104. $process = new Process([
  1105. $chromeBinary,
  1106. '--headless=new',
  1107. '--disable-gpu',
  1108. '--no-sandbox',
  1109. '--disable-setuid-sandbox',
  1110. '--disable-dev-shm-usage',
  1111. '--disable-software-rasterizer',
  1112. '--disable-extensions',
  1113. '--disable-background-networking',
  1114. '--disable-component-update',
  1115. '--disable-client-side-phishing-detection',
  1116. '--disable-default-apps',
  1117. '--disable-domain-reliability',
  1118. '--disable-sync',
  1119. '--safebrowsing-disable-auto-update',
  1120. '--no-first-run',
  1121. '--no-default-browser-check',
  1122. '--disable-crash-reporter',
  1123. '--disable-print-preview',
  1124. '--disable-features=PrintHeaderFooter',
  1125. '--disable-features=TranslateUI',
  1126. '--disable-features=OptimizationHints',
  1127. '--disable-ipc-flooding-protection',
  1128. '--disable-background-networking',
  1129. '--disable-background-timer-throttling',
  1130. '--disable-backgrounding-occluded-windows',
  1131. '--disable-renderer-backgrounding',
  1132. '--disable-features=AudioServiceOutOfProcess',
  1133. '--disable-gpu-rasterization',
  1134. '--disable-web-security',
  1135. '--disable-features=VizDisplayCompositor',
  1136. '--font-render-hinting=none',
  1137. '--disable-logging',
  1138. '--disable-gpu-sandbox',
  1139. '--disable-partial-raster',
  1140. '--disable-skia-runtime',
  1141. '--no-zygote',
  1142. // 【新增】启用高级性能优化
  1143. '--enable-features=NetworkService,NetworkServiceInProcess',
  1144. '--enable-automation',
  1145. '--disable-infobars',
  1146. '--disable-extensions-ui',
  1147. '--disable-smooth-scrolling',
  1148. '--disable-ipc-flooding-protection',
  1149. '--user-data-dir=' . $userDataDir,
  1150. '--print-to-pdf=' . $tmpPdf,
  1151. '--print-to-pdf-no-header',
  1152. '--allow-file-access-from-files',
  1153. // 【优化】增加虚拟时间预算到25秒(原来是15秒)
  1154. '--virtual-time-budget=25000',
  1155. // 【优化】移除可能导致卡顿的参数
  1156. // '--run-all-compositor-stages-before-draw', // 移除此参数
  1157. // 【优化】增加堆内存限制(原来512MB,现在1024MB)
  1158. '--max_old_space_size=1024',
  1159. // 【优化】增加新堆内存限制(原来64MB,现在128MB)
  1160. '--max_new_space_size=128',
  1161. 'file://' . $htmlPath,
  1162. ], null, [
  1163. 'HOME' => $runtimeHome,
  1164. 'XDG_RUNTIME_DIR' => $runtimeXdg,
  1165. ]);
  1166. // 【性能优化】增加超时时间到200秒(原来是45秒)
  1167. // 匹配25秒虚拟时间预算,同时给Chrome充足时间处理复杂页面
  1168. $process->setTimeout(200);
  1169. $killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
  1170. try {
  1171. $startedAt = microtime(true);
  1172. Log::info('ExamPdfExportService: 优化Chrome进程启动', [
  1173. 'start_time' => date('Y-m-d H:i:s', (int)$startedAt),
  1174. 'timeout' => 200,
  1175. 'virtual_time_budget' => 25000,
  1176. 'html_size' => file_exists($htmlPath) ? filesize($htmlPath) : 0
  1177. ]);
  1178. $process->start();
  1179. $pdfGenerated = false;
  1180. // 【性能优化】调整轮询时间:195秒轮询(小于Chrome超时200秒)
  1181. $pollStart = microtime(true);
  1182. $maxPollSeconds = 195; // 从43秒增加到195秒
  1183. $checkInterval = 30_000; // 保持30ms检查间隔
  1184. // 【性能优化】缩短初始等待时间到500ms
  1185. usleep(500_000);
  1186. while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
  1187. // 【优化】每1秒输出一次进度(原来是2秒)
  1188. $currentElapsed = microtime(true) - $pollStart;
  1189. if (fmod($currentElapsed, 1) < 0.1 || $currentElapsed < 0.2) {
  1190. Log::debug('ExamPdfExportService: 优化Chrome渲染中', [
  1191. 'elapsed' => round($currentElapsed, 2) . 's',
  1192. 'pdf_exists' => file_exists($tmpPdf),
  1193. 'pdf_size' => file_exists($tmpPdf) ? filesize($tmpPdf) : 0
  1194. ]);
  1195. }
  1196. // 【优化】早期检查PDF生成(每30ms)
  1197. if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
  1198. $pdfGenerated = true;
  1199. $elapsed = microtime(true) - $startedAt;
  1200. Log::info('ExamPdfExportService: 优化PDF文件已生成,提前终止Chrome', [
  1201. 'elapsed' => round($elapsed, 2) . 's',
  1202. 'pdf_size' => filesize($tmpPdf),
  1203. 'poll_elapsed' => round($currentElapsed, 2) . 's'
  1204. ]);
  1205. $process->stop(1, $killSignal);
  1206. break;
  1207. }
  1208. usleep($checkInterval);
  1209. }
  1210. $elapsed = microtime(true) - $startedAt;
  1211. Log::info('ExamPdfExportService: Chrome轮询结束', [
  1212. 'elapsed' => round($elapsed, 2) . 's',
  1213. 'is_running' => $process->isRunning(),
  1214. 'pdf_exists' => file_exists($tmpPdf),
  1215. 'pdf_size' => file_exists($tmpPdf) ? filesize($tmpPdf) : 0,
  1216. 'timeout' => $maxPollSeconds
  1217. ]);
  1218. // 【优化】强制快速停止Chrome进程
  1219. if ($process->isRunning()) {
  1220. Log::warning('ExamPdfExportService: Chrome进程仍在运行,强制停止', [
  1221. 'elapsed' => round($elapsed, 2) . 's',
  1222. 'reason' => 'timeout'
  1223. ]);
  1224. $process->stop(1, $killSignal);
  1225. }
  1226. $process->wait();
  1227. } catch (ProcessTimedOutException $e) {
  1228. Log::error('ExamPdfExportService: Chrome进程超时', [
  1229. 'timeout' => $e->getExceededTimeout(),
  1230. 'elapsed' => round(microtime(true) - $startedAt, 2) . 's',
  1231. 'html_size' => file_exists($htmlPath) ? filesize($htmlPath) : 0,
  1232. 'message' => 'Chrome渲染超时,已自动终止'
  1233. ]);
  1234. if ($process->isRunning()) {
  1235. $process->stop(1, $killSignal);
  1236. }
  1237. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
  1238. } catch (ProcessSignaledException $e) {
  1239. Log::warning('ExamPdfExportService: Chrome进程被信号终止', [
  1240. 'signal' => $e->getSignal(),
  1241. 'elapsed' => round(microtime(true) - $startedAt, 2) . 's'
  1242. ]);
  1243. if ($process->isRunning()) {
  1244. $process->stop(1, $killSignal);
  1245. }
  1246. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
  1247. } catch (\Throwable $e) {
  1248. Log::error('ExamPdfExportService: Chrome渲染异常', [
  1249. 'error' => $e->getMessage(),
  1250. 'elapsed' => round(microtime(true) - $startedAt, 2) . 's',
  1251. 'trace' => $e->getTraceAsString()
  1252. ]);
  1253. if ($process->isRunning()) {
  1254. $process->stop(1, $killSignal);
  1255. }
  1256. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  1257. }
  1258. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  1259. }
  1260. /**
  1261. * 处理Chrome进程结果
  1262. */
  1263. private function handleChromeProcessResult(string $tmpPdf, string $userDataDir, Process $process, ?float $startedAt): ?string
  1264. {
  1265. $elapsed = $startedAt ? round(microtime(true) - $startedAt, 2) : 0;
  1266. $pdfExists = file_exists($tmpPdf);
  1267. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  1268. if (!$process->isSuccessful()) {
  1269. if ($pdfExists && $pdfSize > 0) {
  1270. Log::warning('ExamPdfExportService: Chrome进程异常但生成了PDF', [
  1271. 'elapsed' => $elapsed . 's',
  1272. 'exit_code' => $process->getExitCode(),
  1273. 'tmp_pdf_size' => $pdfSize,
  1274. ]);
  1275. } else {
  1276. Log::error('ExamPdfExportService: Chrome渲染失败', [
  1277. 'elapsed' => $elapsed . 's',
  1278. 'exit_code' => $process->getExitCode(),
  1279. 'error' => $process->getErrorOutput(),
  1280. 'tmp_pdf_exists' => $pdfExists,
  1281. 'tmp_pdf_size' => $pdfSize
  1282. ]);
  1283. }
  1284. } else {
  1285. Log::info('ExamPdfExportService: Chrome进程正常结束', [
  1286. 'elapsed' => $elapsed . 's',
  1287. 'exit_code' => $process->getExitCode(),
  1288. 'pdf_exists' => $pdfExists,
  1289. 'pdf_size' => $pdfSize
  1290. ]);
  1291. }
  1292. // 读取PDF内容
  1293. $pdfBinary = null;
  1294. if ($pdfExists && $pdfSize > 0) {
  1295. $pdfBinary = file_get_contents($tmpPdf);
  1296. Log::info('ExamPdfExportService: PDF读取成功', [
  1297. 'size' => strlen($pdfBinary),
  1298. 'elapsed' => $elapsed . 's'
  1299. ]);
  1300. } else {
  1301. Log::error('ExamPdfExportService: PDF文件不存在或为空', [
  1302. 'tmp_pdf' => $tmpPdf,
  1303. 'exists' => $pdfExists,
  1304. 'size' => $pdfSize
  1305. ]);
  1306. }
  1307. // 【优化】确保资源正确释放,使用try-catch包装
  1308. try {
  1309. if ($pdfExists && file_exists($tmpPdf)) {
  1310. @unlink($tmpPdf);
  1311. Log::debug('ExamPdfExportService: 临时PDF文件已删除', ['path' => $tmpPdf]);
  1312. }
  1313. } catch (\Exception $e) {
  1314. Log::warning('ExamPdfExportService: 删除临时PDF文件失败', [
  1315. 'path' => $tmpPdf,
  1316. 'error' => $e->getMessage()
  1317. ]);
  1318. }
  1319. try {
  1320. if ($userDataDir && is_dir($userDataDir)) {
  1321. File::deleteDirectory($userDataDir);
  1322. Log::debug('ExamPdfExportService: Chrome用户数据目录已删除', ['path' => $userDataDir]);
  1323. }
  1324. } catch (\Exception $e) {
  1325. Log::warning('ExamPdfExportService: 删除Chrome用户数据目录失败', [
  1326. 'path' => $userDataDir,
  1327. 'error' => $e->getMessage()
  1328. ]);
  1329. }
  1330. return $pdfBinary ?: null;
  1331. }
  1332. /**
  1333. * 查找Chrome二进制文件
  1334. */
  1335. private function findChromeBinary(): ?string
  1336. {
  1337. $candidates = [
  1338. env('PDF_CHROME_BINARY'),
  1339. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  1340. '/usr/bin/google-chrome-stable',
  1341. '/usr/bin/google-chrome',
  1342. '/usr/bin/chromium-browser',
  1343. '/usr/bin/chromium',
  1344. ];
  1345. foreach ($candidates as $path) {
  1346. if ($path && is_file($path) && is_executable($path)) {
  1347. return $path;
  1348. }
  1349. }
  1350. return null;
  1351. }
  1352. /**
  1353. * 确保HTML为UTF-8编码
  1354. */
  1355. private function ensureUtf8Html(string $html): string
  1356. {
  1357. $meta = '<meta charset="UTF-8">';
  1358. if (stripos($html, '<head>') !== false) {
  1359. return preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
  1360. }
  1361. return $meta . $html;
  1362. }
  1363. /**
  1364. * 构建知识点名称映射
  1365. */
  1366. private function buildKnowledgePointNameMap(): array
  1367. {
  1368. try {
  1369. $options = $this->questionServiceApi->getKnowledgePointOptions();
  1370. return $options ?: [];
  1371. } catch (\Throwable $e) {
  1372. Log::warning('ExamPdfExportService: 获取知识点名称失败', [
  1373. 'error' => $e->getMessage(),
  1374. ]);
  1375. return [];
  1376. }
  1377. }
  1378. /**
  1379. * 构建掌握度摘要
  1380. */
  1381. private function buildMasterySummary(array $masteryData, array $kpNameMap): array
  1382. {
  1383. Log::info('ExamPdfExportService: buildMasterySummary开始处理', [
  1384. 'masteryData_count' => count($masteryData),
  1385. 'kpNameMap_count' => count($kpNameMap)
  1386. ]);
  1387. $items = [];
  1388. $total = 0;
  1389. $count = 0;
  1390. foreach ($masteryData as $row) {
  1391. $code = $row['kp_code'] ?? null;
  1392. // 【修复】使用kpNameMap转换名称为友好显示名
  1393. $name = $kpNameMap[$code] ?? $row['kp_name'] ?? $code ?: '未知知识点';
  1394. $level = (float)($row['mastery_level'] ?? 0);
  1395. $delta = $row['mastery_change'] ?? null;
  1396. $items[] = [
  1397. 'kp_code' => $code,
  1398. 'kp_name' => $name,
  1399. 'mastery_level' => $level,
  1400. 'mastery_change' => $delta,
  1401. ];
  1402. $total += $level;
  1403. $count++;
  1404. }
  1405. $average = $count > 0 ? round($total / $count, 2) : null;
  1406. // 按掌握度从低到高排序
  1407. if (!empty($items)) {
  1408. usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  1409. }
  1410. $result = [
  1411. 'items' => $items,
  1412. 'average' => $average,
  1413. 'weak_list' => array_slice($items, 0, 5),
  1414. ];
  1415. Log::info('ExamPdfExportService: buildMasterySummary完成', [
  1416. 'total_count' => $count,
  1417. 'items_count' => count($items)
  1418. ]);
  1419. return $result;
  1420. }
  1421. /**
  1422. * 标准化题型
  1423. */
  1424. private function normalizeQuestionType(string $type): string
  1425. {
  1426. $t = strtolower(trim($type));
  1427. return match (true) {
  1428. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  1429. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  1430. default => 'answer',
  1431. };
  1432. }
  1433. /**
  1434. * 保存PDF URL到数据库
  1435. */
  1436. private function savePdfUrlToDatabase(string $paperId, string $field, string $url): void
  1437. {
  1438. try {
  1439. $paper = Paper::where('paper_id', $paperId)->first();
  1440. if ($paper) {
  1441. $paper->update([$field => $url]);
  1442. Log::info('ExamPdfExportService: PDF URL已写入数据库', [
  1443. 'paper_id' => $paperId,
  1444. 'field' => $field,
  1445. 'url' => $url,
  1446. ]);
  1447. }
  1448. } catch (\Throwable $e) {
  1449. Log::error('ExamPdfExportService: 写入PDF URL失败', [
  1450. 'paper_id' => $paperId,
  1451. 'field' => $field,
  1452. 'error' => $e->getMessage(),
  1453. ]);
  1454. }
  1455. }
  1456. /**
  1457. * 保存学情分析PDF URL
  1458. */
  1459. private function saveAnalysisPdfUrl(string $paperId, string $studentId, ?string $recordId, string $url): void
  1460. {
  1461. try {
  1462. if ($recordId) {
  1463. // OCR记录
  1464. $ocrRecord = \App\Models\OCRRecord::find($recordId);
  1465. if ($ocrRecord) {
  1466. $ocrRecord->update(['analysis_pdf_url' => $url]);
  1467. Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
  1468. 'record_id' => $recordId,
  1469. 'paper_id' => $paperId,
  1470. 'student_id' => $studentId,
  1471. 'url' => $url,
  1472. ]);
  1473. }
  1474. } else {
  1475. // 【修复】同时更新 exam_analysis_results 表和分析报告表
  1476. $updated = \DB::connection('mysql')->table('exam_analysis_results')
  1477. ->where('student_id', $studentId)
  1478. ->where('paper_id', $paperId)
  1479. ->update([
  1480. 'analysis_pdf_url' => $url,
  1481. 'updated_at' => now(),
  1482. ]);
  1483. if ($updated) {
  1484. Log::info('ExamPdfExportService: 学情分析PDF URL已写入exam_analysis_results表', [
  1485. 'student_id' => $studentId,
  1486. 'paper_id' => $paperId,
  1487. 'url' => $url,
  1488. 'updated_rows' => $updated,
  1489. ]);
  1490. } else {
  1491. Log::warning('ExamPdfExportService: 未找到要更新的学情分析记录', [
  1492. 'student_id' => $studentId,
  1493. 'paper_id' => $paperId,
  1494. ]);
  1495. }
  1496. // 学生记录 - 使用新的 student_reports 表(备用)
  1497. \App\Models\StudentReport::updateOrCreate(
  1498. [
  1499. 'student_id' => $studentId,
  1500. 'report_type' => 'exam_analysis',
  1501. 'paper_id' => $paperId,
  1502. ],
  1503. [
  1504. 'pdf_url' => $url,
  1505. 'generation_status' => 'completed',
  1506. 'generated_at' => now(),
  1507. 'updated_at' => now(),
  1508. ]
  1509. );
  1510. Log::info('ExamPdfExportService: 学生学情报告PDF URL已保存到student_reports表(备用)', [
  1511. 'student_id' => $studentId,
  1512. 'paper_id' => $paperId,
  1513. 'url' => $url,
  1514. ]);
  1515. }
  1516. } catch (\Throwable $e) {
  1517. Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
  1518. 'paper_id' => $paperId,
  1519. 'student_id' => $studentId,
  1520. 'record_id' => $recordId,
  1521. 'error' => $e->getMessage(),
  1522. ]);
  1523. }
  1524. }
  1525. /**
  1526. * 【修复】处理父节点掌握度数据
  1527. * 1. 过滤掉掌握度为0或null的父节点
  1528. * 2. 将kp_code转换为友好的kp_name
  1529. * 3. 构建父子层级关系(只显示本次考试相关的子节点)
  1530. */
  1531. private function processParentMasteryLevels(array $parentMasteryLevels, array $kpNameMap, array $examKpCodes = []): array
  1532. {
  1533. $processed = [];
  1534. foreach ($parentMasteryLevels as $kpCode => $masteryData) {
  1535. // 兼容不同数据结构:可能是数组或数字
  1536. $masteryLevel = is_array($masteryData) ? ($masteryData['mastery_level'] ?? 0) : $masteryData;
  1537. $masteryChange = is_array($masteryData) ? ($masteryData['mastery_change'] ?? null) : null;
  1538. // 过滤零值和空值
  1539. if ($masteryLevel === null || $masteryLevel === 0.0 || $masteryLevel <= 0.001) {
  1540. continue;
  1541. }
  1542. // 获取友好名称
  1543. $kpName = $kpNameMap[$kpCode] ?? $kpCode;
  1544. // 构建父节点数据,包含子节点信息(只显示本次考试相关的)
  1545. $processed[$kpCode] = [
  1546. 'kp_code' => $kpCode,
  1547. 'kp_name' => $kpName,
  1548. 'mastery_level' => round(floatval($masteryLevel), 4),
  1549. 'mastery_percentage' => round(floatval($masteryLevel) * 100, 2),
  1550. 'mastery_change' => $masteryChange !== null ? round(floatval($masteryChange), 4) : null,
  1551. // 【修复】只获取本次考试涉及的子节点
  1552. 'children' => $this->getChildKnowledgePoints($kpCode, $kpNameMap, $examKpCodes),
  1553. 'level' => $this->calculateKnowledgePointLevel($kpCode),
  1554. ];
  1555. }
  1556. // 按掌握度降序排序
  1557. uasort($processed, function($a, $b) {
  1558. return $b['mastery_level'] <=> $a['mastery_level'];
  1559. });
  1560. return $processed;
  1561. }
  1562. /**
  1563. * 【修复】获取子知识点列表(只返回本次考试涉及的)
  1564. */
  1565. private function getChildKnowledgePoints(string $parentKpCode, array $kpNameMap, array $examKpCodes = []): array
  1566. {
  1567. $children = [];
  1568. try {
  1569. $childCodes = DB::connection('mysql')
  1570. ->table('knowledge_points')
  1571. ->where('parent_kp_code', $parentKpCode)
  1572. ->pluck('kp_code')
  1573. ->toArray();
  1574. foreach ($childCodes as $childCode) {
  1575. // 只包含本次考试涉及的知识点
  1576. if (in_array($childCode, $examKpCodes)) {
  1577. $children[] = [
  1578. 'kp_code' => $childCode,
  1579. 'kp_name' => $kpNameMap[$childCode] ?? $childCode,
  1580. ];
  1581. }
  1582. }
  1583. } catch (\Exception $e) {
  1584. Log::warning('获取子知识点失败', [
  1585. 'parent_kp_code' => $parentKpCode,
  1586. 'error' => $e->getMessage(),
  1587. ]);
  1588. }
  1589. return $children;
  1590. }
  1591. /**
  1592. * 计算知识点层级深度
  1593. */
  1594. private function calculateKnowledgePointLevel(string $kpCode): int
  1595. {
  1596. // 根据kp_code前缀判断层级深度
  1597. // 例如: M (1级) -> M01 (2级) -> M01A (3级)
  1598. if (preg_match('/^[A-Z]+$/', $kpCode)) {
  1599. return 1; // 一级分类,如 M, S, E, G
  1600. } elseif (preg_match('/^[A-Z]+\d+$/', $kpCode)) {
  1601. return 2; // 二级分类,如 M01, S02
  1602. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+$/', $kpCode)) {
  1603. return 3; // 三级分类,如 M01A, S02B
  1604. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+\d+$/', $kpCode)) {
  1605. return 4; // 四级分类,如 M01A1
  1606. }
  1607. return 1; // 默认一级
  1608. }
  1609. /**
  1610. * 构建题目数据(用于PDF生成)
  1611. */
  1612. private function buildQuestionsData(Paper $paper): array
  1613. {
  1614. $paperQuestions = $paper->questions()->orderBy('question_number')->get();
  1615. $questionsData = [];
  1616. foreach ($paperQuestions as $pq) {
  1617. $questionsData[] = [
  1618. 'id' => $pq->question_bank_id,
  1619. 'kp_code' => $pq->knowledge_point,
  1620. 'question_type' => $pq->question_type ?? 'answer',
  1621. 'stem' => $pq->question_text ?? '题目内容缺失',
  1622. 'solution' => $pq->solution ?? '',
  1623. 'answer' => $pq->correct_answer ?? '',
  1624. 'difficulty' => $pq->difficulty ?? 0.5,
  1625. 'score' => $pq->score ?? 5,
  1626. 'tags' => '',
  1627. 'content' => $pq->question_text ?? '',
  1628. ];
  1629. }
  1630. // 获取完整题目详情
  1631. if (!empty($questionsData)) {
  1632. $questionIds = array_column($questionsData, 'id');
  1633. $questionsResponse = $this->questionServiceApi->getQuestionsByIds($questionIds);
  1634. $responseData = $questionsResponse['data'] ?? [];
  1635. if (!empty($responseData)) {
  1636. $responseDataMap = [];
  1637. foreach ($responseData as $respQ) {
  1638. $responseDataMap[$respQ['id']] = $respQ;
  1639. }
  1640. $questionsData = array_map(function($q) use ($responseDataMap) {
  1641. if (isset($responseDataMap[$q['id']])) {
  1642. $apiData = $responseDataMap[$q['id']];
  1643. $q['stem'] = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  1644. $q['content'] = $q['stem'];
  1645. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  1646. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  1647. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  1648. $q['options'] = $apiData['options'] ?? [];
  1649. }
  1650. return $q;
  1651. }, $questionsData);
  1652. }
  1653. }
  1654. // 按题型分类
  1655. $classified = ['choice' => [], 'fill' => [], 'answer' => []];
  1656. foreach ($questionsData as $q) {
  1657. $type = $this->determineQuestionType($q);
  1658. $classified[$type][] = (object) $q;
  1659. }
  1660. return $classified;
  1661. }
  1662. /**
  1663. * 获取学生信息
  1664. */
  1665. private function getStudentInfo(?string $studentId): array
  1666. {
  1667. if (!$studentId) {
  1668. return [
  1669. 'name' => '未知学生',
  1670. 'grade' => '未知年级',
  1671. 'class' => '未知班级'
  1672. ];
  1673. }
  1674. try {
  1675. $student = DB::table('students')
  1676. ->where('student_id', $studentId)
  1677. ->first();
  1678. if ($student) {
  1679. return [
  1680. 'name' => $student->name ?? $studentId,
  1681. 'grade' => $student->grade ?? '未知',
  1682. 'class' => $student->class ?? '未知'
  1683. ];
  1684. }
  1685. } catch (\Exception $e) {
  1686. Log::warning('获取学生信息失败', [
  1687. 'student_id' => $studentId,
  1688. 'error' => $e->getMessage()
  1689. ]);
  1690. }
  1691. return [
  1692. 'name' => $studentId,
  1693. 'grade' => '未知',
  1694. 'class' => '未知'
  1695. ];
  1696. }
  1697. /**
  1698. * 获取教师信息
  1699. */
  1700. private function getTeacherInfo(?string $teacherId): array
  1701. {
  1702. if (!$teacherId) {
  1703. return [
  1704. 'name' => '未知老师',
  1705. 'subject' => '数学'
  1706. ];
  1707. }
  1708. try {
  1709. $teacher = DB::table('teachers')
  1710. ->where('teacher_id', $teacherId)
  1711. ->first();
  1712. if ($teacher) {
  1713. return [
  1714. 'name' => $teacher->name ?? $teacherId,
  1715. 'subject' => $teacher->subject ?? '数学'
  1716. ];
  1717. }
  1718. } catch (\Exception $e) {
  1719. Log::warning('获取教师信息失败', [
  1720. 'teacher_id' => $teacherId,
  1721. 'error' => $e->getMessage()
  1722. ]);
  1723. }
  1724. return [
  1725. 'name' => $teacherId,
  1726. 'subject' => '数学'
  1727. ];
  1728. }
  1729. /**
  1730. * 判断题目类型
  1731. */
  1732. private function determineQuestionType(array $question): string
  1733. {
  1734. $stem = $question['stem'] ?? $question['content'] ?? '';
  1735. $tags = $question['tags'] ?? '';
  1736. // 根据题干内容判断选择题
  1737. if (is_string($stem)) {
  1738. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  1739. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  1740. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  1741. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  1742. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0);
  1743. if ($optionCount >= 2) {
  1744. return 'choice';
  1745. }
  1746. // 检查是否有填空标记
  1747. if (preg_match('/(\s*)|\(\s*\)/', $stem)) {
  1748. return 'fill';
  1749. }
  1750. }
  1751. // 根据已有类型字段判断
  1752. if (!empty($question['question_type'])) {
  1753. $type = strtolower(trim($question['question_type']));
  1754. if (in_array($type, ['choice', '选择题'])) return 'choice';
  1755. if (in_array($type, ['fill', '填空题'])) return 'fill';
  1756. if (in_array($type, ['answer', '解答题'])) return 'answer';
  1757. }
  1758. // 默认返回解答题
  1759. return 'answer';
  1760. }
  1761. }