ExamPdfExportService.php 72 KB

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