ExamPdfExportService.php 72 KB

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