ExamPdfExportService.php 61 KB

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