ExamPdfController.php 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\Paper;
  4. use App\Support\PaperNaming;
  5. use App\Services\QuestionBankService;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Support\Facades\Cache;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Log;
  10. class ExamPdfController extends Controller
  11. {
  12. /**
  13. * 标准化选项格式为数组值列表
  14. * 支持格式:
  15. * 1. {"A": "0", "B": "5", "C": "-3", "D": "12"} -> ["0", "5", "-3", "12"]
  16. * 2. [["label": "A", "text": "选项A"], ...] -> ["选项A", "选项B", ...]
  17. * 3. ["A", "B", "C", "D"] -> ["A", "B", "C", "D"]
  18. */
  19. private function normalizeOptions($options): array
  20. {
  21. if (empty($options)) {
  22. return [];
  23. }
  24. // 如果是对象格式 {"A": "值1", "B": "值2", ...}
  25. if (is_array($options) && ! isset($options[0])) {
  26. return array_values($options);
  27. }
  28. // 如果是AI生成格式 [{"label": "A", "text": "选项A"}, ...]
  29. if (is_array($options) && isset($options[0]) && is_array($options[0])) {
  30. // 提取text字段,如果不存在则使用整个数组元素
  31. $normalized = [];
  32. foreach ($options as $opt) {
  33. if (isset($opt['text'])) {
  34. $normalized[] = $opt['text'];
  35. } elseif (isset($opt['value'])) {
  36. $normalized[] = $opt['value'];
  37. } else {
  38. // 如果既没有text也没有value,取数组的第一个值
  39. $normalized[] = is_array($opt) ? (string) reset($opt) : (string) $opt;
  40. }
  41. }
  42. return $normalized;
  43. }
  44. // 如果已经是简单数组格式 ["A", "B", "C", "D"]
  45. if (is_array($options)) {
  46. return array_values($options);
  47. }
  48. // 其他情况返回空数组
  49. return [];
  50. }
  51. /**
  52. * 根据题目内容或类型字段判断题型
  53. */
  54. private function determineQuestionType(array $question): string
  55. {
  56. // 优先根据题目内容判断(而不是数据库字段)
  57. $stem = $question['stem'] ?? $question['content'] ?? '';
  58. $tags = $question['tags'] ?? '';
  59. $skills = $question['skills'] ?? [];
  60. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  61. if (is_string($stem)) {
  62. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  63. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  64. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  65. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  66. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  67. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  68. // 至少有2个选项就认为是选择题(降低阈值)
  69. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  70. if ($optionCount >= 2) {
  71. return 'choice';
  72. }
  73. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  74. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  75. return 'choice';
  76. }
  77. }
  78. // 2. 根据技能点判断
  79. if (is_array($skills)) {
  80. $skillsStr = implode(',', $skills);
  81. if (strpos($skillsStr, '选择题') !== false) {
  82. return 'choice';
  83. }
  84. if (strpos($skillsStr, '填空题') !== false) {
  85. return 'fill';
  86. }
  87. if (strpos($skillsStr, '解答题') !== false) {
  88. return 'answer';
  89. }
  90. }
  91. // 3. 根据题目已有类型字段判断(作为后备)
  92. if (! empty($question['question_type'])) {
  93. $type = strtolower(trim($question['question_type']));
  94. if (in_array($type, ['choice', '选择题', 'choice question'])) {
  95. return 'choice';
  96. }
  97. if (in_array($type, ['fill', '填空题', 'fill in the blank'])) {
  98. return 'fill';
  99. }
  100. if (in_array($type, ['answer', '解答题', 'calculation', '简答题'])) {
  101. return 'answer';
  102. }
  103. }
  104. if (! empty($question['type'])) {
  105. $type = strtolower(trim($question['type']));
  106. if (in_array($type, ['choice', '选择题', 'choice question'])) {
  107. return 'choice';
  108. }
  109. if (in_array($type, ['fill', '填空题', 'fill in the blank'])) {
  110. return 'fill';
  111. }
  112. if (in_array($type, ['answer', '解答题', 'calculation', '简答题'])) {
  113. return 'answer';
  114. }
  115. }
  116. // 4. 根据标签判断
  117. if (is_string($tags)) {
  118. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  119. return 'choice';
  120. }
  121. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  122. return 'fill';
  123. }
  124. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  125. return 'answer';
  126. }
  127. }
  128. // 5. 填空题特征:连续下划线或明显的填空括号
  129. if (is_string($stem)) {
  130. // 检查填空题特征:连续下划线
  131. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  132. return 'fill';
  133. }
  134. // 空括号填空
  135. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  136. return 'fill';
  137. }
  138. }
  139. // 6. 根据题干内容关键词判断
  140. if (is_string($stem)) {
  141. // 有证明、解答、计算、求证等关键词的是解答题
  142. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  143. return 'answer';
  144. }
  145. }
  146. // 默认是解答题(更安全的默认值)
  147. return 'answer';
  148. }
  149. private function normalizeQuestionTypeValue(string $type): string
  150. {
  151. $type = trim($type);
  152. $lower = strtolower($type);
  153. if (in_array($lower, ['choice', 'single_choice', 'multiple_choice'], true)) {
  154. return 'choice';
  155. }
  156. if (in_array($lower, ['fill', 'blank', 'fill_in_the_blank'], true)) {
  157. return 'fill';
  158. }
  159. if (in_array($lower, ['answer', 'calculation', 'word_problem', 'proof'], true)) {
  160. return 'answer';
  161. }
  162. if (in_array($type, ['CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  163. return 'choice';
  164. }
  165. if (in_array($type, ['FILL', 'FILL_IN_THE_BLANK'], true)) {
  166. return 'fill';
  167. }
  168. if (in_array($type, ['CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
  169. return 'answer';
  170. }
  171. if (in_array($type, ['选择题'], true)) {
  172. return 'choice';
  173. }
  174. if (in_array($type, ['填空题'], true)) {
  175. return 'fill';
  176. }
  177. if (in_array($type, ['解答题', '计算题'], true)) {
  178. return 'answer';
  179. }
  180. return $lower ?: 'answer';
  181. }
  182. /**
  183. * 从题目内容中提取选项
  184. */
  185. private function extractOptions(string $content): array
  186. {
  187. $options = [];
  188. // 【修复】先移除SVG内容,避免误匹配SVG注释中的 BD:DC、A:B 等内容
  189. $contentWithoutSvg = preg_replace('/<svg[^>]*>.*?<\/svg>/is', '[SVG_PLACEHOLDER]', $content);
  190. // 1. 尝试匹配多种格式的选项:A. / A、/ A: / A.(中文句点)/ A.(无空格)
  191. // 【修复】选项标记必须在行首或空白后,避免误匹配 SVG 注释中的 BD:DC 等内容
  192. $pattern = '/(?:^|\s)([A-D])[\.、:.:]\s*(.+?)(?=(?:^|\s)[A-D][\.、:.:]|$)/su';
  193. if (preg_match_all($pattern, $contentWithoutSvg, $matches, PREG_SET_ORDER)) {
  194. foreach ($matches as $match) {
  195. $optionText = trim($match[2]);
  196. // 移除末尾的换行和空白
  197. $optionText = preg_replace('/\s+$/', '', $optionText);
  198. // 清理 LaTeX 格式但保留内容
  199. $optionText = preg_replace('/^\$\$\s*/', '', $optionText);
  200. $optionText = preg_replace('/\s*\$\$$/', '', $optionText);
  201. if (! empty($optionText)) {
  202. $options[] = $optionText;
  203. }
  204. }
  205. }
  206. // 2. 如果上面没提取到,尝试按换行分割
  207. if (empty($options)) {
  208. $lines = preg_split('/[\r\n]+/', $contentWithoutSvg);
  209. foreach ($lines as $line) {
  210. $line = trim($line);
  211. // 【修复】行首匹配选项标记
  212. if (preg_match('/^([A-D])[\.、:.:]\s*(.+)$/u', $line, $match)) {
  213. $optionText = trim($match[2]);
  214. if (! empty($optionText)) {
  215. $options[] = $optionText;
  216. }
  217. }
  218. }
  219. }
  220. Log::debug('选项提取结果', [
  221. 'content_preview' => mb_substr($content, 0, 150),
  222. 'options_count' => count($options),
  223. 'options' => $options,
  224. ]);
  225. return $options;
  226. }
  227. /**
  228. * 分离题干内容和选项
  229. */
  230. private function separateStemAndOptions(string $content): array
  231. {
  232. // 【修复】先移除SVG内容,避免误匹配SVG注释中的 BD:DC、A:B 等内容
  233. $contentWithoutSvg = preg_replace('/<svg[^>]*>.*?<\/svg>/is', '[SVG_PLACEHOLDER]', $content);
  234. // 【修复】检测是否有选项时,要求选项标记在行首或空白后
  235. $hasOptions = preg_match('/(?:^|\s)[A-D][\.、:.:]/u', $contentWithoutSvg);
  236. if (! $hasOptions) {
  237. return [$content, []];
  238. }
  239. // 提取选项
  240. $options = $this->extractOptions($content);
  241. // 如果提取到选项,分离题干
  242. if (! empty($options)) {
  243. // 【修复】找到第一个选项的位置,要求选项标记在行首或空白后
  244. if (preg_match('/^(.+?)(?=(?:^|\s)[A-D][\.、:.:])/su', $contentWithoutSvg, $match)) {
  245. $stem = trim($match[1]);
  246. // 如果题干中有SVG占位符,从原始内容中提取对应部分
  247. if (strpos($stem, '[SVG_PLACEHOLDER]') !== false) {
  248. // 找到原始内容中对应位置的题干
  249. $stemLength = mb_strlen(str_replace('[SVG_PLACEHOLDER]', '', $stem));
  250. // 使用更精确的方法:找到第一个有效选项标记的位置
  251. foreach (['A.', 'A、', 'A:', 'A.', 'A:'] as $marker) {
  252. // 只匹配在空白后的选项标记
  253. if (preg_match('/\s'.preg_quote($marker, '/').'/', $content, $m, PREG_OFFSET_CAPTURE)) {
  254. $pos = $m[0][1];
  255. if ($pos > 0) {
  256. $stem = trim(mb_substr($content, 0, $pos));
  257. break;
  258. }
  259. }
  260. }
  261. }
  262. } else {
  263. // 如果正则失败,尝试按位置分割
  264. $stem = $content;
  265. foreach (['A.', 'A、', 'A:', 'A.', 'A:'] as $marker) {
  266. // 【修复】只匹配在空白后的选项标记
  267. if (preg_match('/\s'.preg_quote($marker, '/').'/', $content, $m, PREG_OFFSET_CAPTURE)) {
  268. $pos = $m[0][1];
  269. if ($pos > 0) {
  270. $stem = trim(mb_substr($content, 0, $pos));
  271. break;
  272. }
  273. }
  274. }
  275. }
  276. // 移除末尾的括号或空白
  277. $stem = preg_replace('/()\s*$/', '', $stem);
  278. $stem = trim($stem);
  279. return [$stem, $options];
  280. }
  281. return [$content, []];
  282. }
  283. /**
  284. * 根据题型获取默认分数
  285. */
  286. private function getQuestionScore(string $type): int
  287. {
  288. switch ($type) {
  289. case 'choice':
  290. return 5; // 选择题5分
  291. case 'fill':
  292. return 5; // 填空题5分
  293. case 'answer':
  294. return 10; // 解答题10分
  295. default:
  296. return 5;
  297. }
  298. }
  299. /**
  300. * 获取学生信息
  301. */
  302. private function getStudentInfo(?string $studentId): array
  303. {
  304. if (! $studentId) {
  305. return [
  306. 'name' => '未知学生',
  307. 'grade' => '未知年级',
  308. 'class' => '未知班级',
  309. ];
  310. }
  311. try {
  312. $student = DB::table('students')
  313. ->where('student_id', $studentId)
  314. ->first();
  315. if ($student) {
  316. return [
  317. 'name' => $student->name ?? $studentId,
  318. 'grade' => $student->grade ?? '未知',
  319. 'class' => $student->class ?? '未知',
  320. ];
  321. }
  322. } catch (\Exception $e) {
  323. Log::warning('获取学生信息失败', [
  324. 'student_id' => $studentId,
  325. 'error' => $e->getMessage(),
  326. ]);
  327. }
  328. return [
  329. 'name' => $studentId,
  330. 'grade' => '未知',
  331. 'class' => '未知',
  332. ];
  333. }
  334. /**
  335. * 为 PDF 预览筛选题目(简化版)
  336. */
  337. private function selectBestQuestionsForPdf(array $questions, int $targetCount, string $difficultyCategory): array
  338. {
  339. if (count($questions) <= $targetCount) {
  340. return $questions;
  341. }
  342. // 1. 按题型分类题目
  343. $categorizedQuestions = [
  344. 'choice' => [],
  345. 'fill' => [],
  346. 'answer' => [],
  347. ];
  348. foreach ($questions as $question) {
  349. $type = $this->determineQuestionType($question);
  350. if (! isset($categorizedQuestions[$type])) {
  351. $type = 'answer';
  352. }
  353. $categorizedQuestions[$type][] = $question;
  354. }
  355. // 2. 默认题型配比
  356. $typeRatio = [
  357. '选择题' => 50, // 50%
  358. '填空题' => 30, // 30%
  359. '解答题' => 20, // 20%
  360. ];
  361. // 3. 根据配比选择题目
  362. $selectedQuestions = [];
  363. foreach ($typeRatio as $type => $ratio) {
  364. $typeKey = $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer');
  365. $countForType = floor($targetCount * $ratio / 100);
  366. if ($countForType > 0 && ! empty($categorizedQuestions[$typeKey])) {
  367. $availableCount = count($categorizedQuestions[$typeKey]);
  368. $takeCount = min($countForType, $availableCount, $targetCount - count($selectedQuestions));
  369. // 随机选择题目
  370. $keys = array_keys($categorizedQuestions[$typeKey]);
  371. shuffle($keys);
  372. $selectedKeys = array_slice($keys, 0, $takeCount);
  373. foreach ($selectedKeys as $key) {
  374. $selectedQuestions[] = $categorizedQuestions[$typeKey][$key];
  375. }
  376. }
  377. }
  378. // 4. 如果数量不足,随机补充
  379. while (count($selectedQuestions) < $targetCount) {
  380. $randomQuestion = $questions[array_rand($questions)];
  381. if (! in_array($randomQuestion, $selectedQuestions)) {
  382. $selectedQuestions[] = $randomQuestion;
  383. }
  384. }
  385. // 5. 限制数量并打乱
  386. shuffle($selectedQuestions);
  387. return array_slice($selectedQuestions, 0, $targetCount);
  388. }
  389. /**
  390. * 获取教师信息
  391. */
  392. private function getTeacherInfo(?string $teacherId): array
  393. {
  394. if (! $teacherId) {
  395. return [
  396. 'name' => '未知教师',
  397. ];
  398. }
  399. try {
  400. $teacher = DB::table('teachers')
  401. ->where('teacher_id', $teacherId)
  402. ->first();
  403. if ($teacher) {
  404. return [
  405. 'name' => $teacher->name ?? $teacherId,
  406. ];
  407. }
  408. } catch (\Exception $e) {
  409. Log::warning('获取教师信息失败', [
  410. 'teacher_id' => $teacherId,
  411. 'error' => $e->getMessage(),
  412. ]);
  413. }
  414. return [
  415. 'name' => $teacherId,
  416. ];
  417. }
  418. private function buildPdfMeta(object $paper, string $fallbackPaperId, ?array $studentInfo = null): array
  419. {
  420. $rawPaperId = (string) ($paper->paper_id ?? $fallbackPaperId);
  421. $assembleType = isset($paper->paper_type) && $paper->paper_type !== '' && $paper->paper_type !== null
  422. ? (int) $paper->paper_type
  423. : null;
  424. $examCode = PaperNaming::extractExamCode($rawPaperId);
  425. $studentName = $studentInfo['name'] ?? ($paper->student_id ?? '________');
  426. try {
  427. $assembleTypeLabel = $assembleType !== null ? PaperNaming::assembleTypeLabel($assembleType) : '未知类型';
  428. } catch (\Throwable $e) {
  429. $assembleTypeLabel = '未知类型';
  430. }
  431. $headerTitle = $examCode;
  432. return [
  433. 'student_name' => $studentName,
  434. 'exam_code' => $examCode,
  435. 'assemble_type_label' => $assembleTypeLabel,
  436. 'header_title' => $headerTitle,
  437. 'exam_pdf_title' => "试卷_{$headerTitle}",
  438. 'grading_pdf_title' => "判卷_{$headerTitle}",
  439. 'knowledge_pdf_title' => "知识点讲解_{$headerTitle}",
  440. ];
  441. }
  442. public function show(Request $request, $paper_id)
  443. {
  444. // 获取是否显示答案的参数,默认为true
  445. $includeAnswer = $request->query('answer', 'true') !== 'false';
  446. // 使用 Eloquent 模型获取试卷数据
  447. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  448. if (! $paper) {
  449. // 尝试从缓存中获取生成的试卷数据(用于 demo 试卷)
  450. $cached = Cache::get('generated_exam_'.$paper_id);
  451. if ($cached) {
  452. Log::info('从缓存获取试卷数据', [
  453. 'paper_id' => $paper_id,
  454. 'cached_count' => count($cached['questions'] ?? []),
  455. 'cached_question_types' => array_column($cached['questions'] ?? [], 'question_type'),
  456. ]);
  457. // 构造临时 Paper 对象
  458. $paper = (object) [
  459. 'paper_id' => $paper_id,
  460. 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
  461. 'student_id' => $cached['student_id'] ?? null,
  462. 'teacher_id' => $cached['teacher_id'] ?? null,
  463. 'paper_type' => $cached['assemble_type'] ?? null,
  464. ];
  465. // 对于 demo 试卷,需要检查题目数量并限制为用户要求的数量
  466. $questionsData = $cached['questions'] ?? [];
  467. $totalQuestions = $cached['total_questions'] ?? count($questionsData);
  468. $difficultyCategory = $cached['difficulty_category'] ?? '中等';
  469. // 为 demo 试卷获取完整的题目详情(包括选项)
  470. if (! empty($questionsData)) {
  471. $questionBankService = app(QuestionBankService::class);
  472. $questionIds = array_column($questionsData, 'id');
  473. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  474. $responseData = $questionsResponse['data'] ?? [];
  475. if (! empty($responseData)) {
  476. $responseDataMap = [];
  477. foreach ($responseData as $respQ) {
  478. $responseDataMap[$respQ['id']] = $respQ;
  479. }
  480. // 合并题库数据
  481. $questionsData = array_map(function ($q) use ($responseDataMap) {
  482. if (isset($responseDataMap[$q['id']])) {
  483. $apiData = $responseDataMap[$q['id']];
  484. $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  485. // 分离题干和选项
  486. [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  487. $q['stem'] = $stem;
  488. $q['content'] = $stem; // 同时设置content字段
  489. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  490. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  491. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  492. // 优先使用API选项,支持多种数据格式
  493. $apiOptions = $apiData['options'] ?? null;
  494. if (! empty($apiOptions)) {
  495. // 标准化options格式为数组值列表
  496. $q['options'] = $this->normalizeOptions($apiOptions);
  497. Log::debug('使用标准化API options', [
  498. 'question_id' => $q['id'],
  499. 'raw_options' => $apiOptions,
  500. 'normalized_options' => $q['options'],
  501. ]);
  502. } else {
  503. // 备选:从题干中提取的选项
  504. $q['options'] = $extractedOptions;
  505. Log::debug('使用提取的options', [
  506. 'question_id' => $q['id'],
  507. 'extracted_options' => $extractedOptions,
  508. ]);
  509. }
  510. }
  511. return $q;
  512. }, $questionsData);
  513. }
  514. }
  515. if (count($questionsData) > $totalQuestions) {
  516. Log::info('PDF预览时发现题目过多,进行筛选', [
  517. 'paper_id' => $paper_id,
  518. 'cached_count' => count($questionsData),
  519. 'required_count' => $totalQuestions,
  520. ]);
  521. $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
  522. Log::info('筛选后题目数据', [
  523. 'paper_id' => $paper_id,
  524. 'filtered_count' => count($questionsData),
  525. 'filtered_types' => array_column($questionsData, 'question_type'),
  526. ]);
  527. }
  528. } else {
  529. abort(404, '试卷未找到');
  530. }
  531. } else {
  532. // 获取试卷题目
  533. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
  534. ->orderBy('question_number')
  535. ->get();
  536. Log::info('从数据库获取题目', [
  537. 'paper_id' => $paper_id,
  538. 'question_count' => $paperQuestions->count(),
  539. ]);
  540. // 将 paper_questions 表的数据转换为题库格式
  541. $questionsData = [];
  542. foreach ($paperQuestions as $pq) {
  543. $questionsData[] = [
  544. 'id' => $pq->question_bank_id,
  545. 'question_number' => $pq->question_number, // 【关键】保留题目序号,用于排序
  546. 'kp_code' => $pq->knowledge_point,
  547. 'question_type' => $pq->question_type ?? 'answer', // 包含题目类型
  548. 'stem' => $pq->question_text ?? '题目内容缺失', // 如果有存储题目文本
  549. 'solution' => $pq->solution ?? '', // 保存解题思路!
  550. 'answer' => $pq->correct_answer ?? '', // 保存正确答案
  551. 'difficulty' => $pq->difficulty ?? 0.5,
  552. 'score' => $pq->score ?? 5, // 包含已计算的分值
  553. 'tags' => '',
  554. 'content' => $pq->question_text ?? '',
  555. ];
  556. }
  557. Log::info('paper_questions表原始数据', [
  558. 'paper_id' => $paper_id,
  559. 'sample_questions' => array_slice($questionsData, 0, 3),
  560. 'all_types' => array_column($questionsData, 'question_type'),
  561. ]);
  562. // 如果需要完整题目详情(stem等),可以从题库获取
  563. // 但要严格限制只获取这8道题
  564. if (! empty($questionsData)) {
  565. $questionBankService = app(QuestionBankService::class);
  566. $questionIds = array_column($questionsData, 'id');
  567. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  568. $responseData = $questionsResponse['data'] ?? [];
  569. // 确保只返回请求的ID对应的题目,并保留数据库中的 question_type
  570. if (! empty($responseData)) {
  571. // 创建题库返回数据的映射
  572. $responseDataMap = [];
  573. foreach ($responseData as $respQ) {
  574. $responseDataMap[$respQ['id']] = $respQ;
  575. }
  576. // 遍历所有数据库中的题目,合并题库返回的数据
  577. $questionsData = array_map(function ($q) use ($responseDataMap, $paperQuestions) {
  578. // 从题库API获取的详细数据(如果有)
  579. if (isset($responseDataMap[$q['id']])) {
  580. $apiData = $responseDataMap[$q['id']];
  581. $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
  582. // 分离题干和选项
  583. [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  584. // 合并数据,优先使用题库API的 stem、answer、solution、options
  585. $q['stem'] = $stem;
  586. $q['content'] = $stem; // 同时设置content字段
  587. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  588. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  589. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  590. // 优先使用API选项,支持多种数据格式
  591. $apiOptions = $apiData['options'] ?? null;
  592. if (! empty($apiOptions)) {
  593. // 标准化options格式为数组值列表
  594. $q['options'] = $this->normalizeOptions($apiOptions);
  595. Log::debug('使用标准化API options', [
  596. 'question_id' => $q['id'],
  597. 'raw_options' => $apiOptions,
  598. 'normalized_options' => $q['options'],
  599. ]);
  600. } else {
  601. // 备选:从题干中提取的选项
  602. $q['options'] = $extractedOptions;
  603. Log::debug('使用提取的options', [
  604. 'question_id' => $q['id'],
  605. 'extracted_options' => $extractedOptions,
  606. ]);
  607. }
  608. }
  609. // 从数据库 paper_questions 表中获取 question_type(已在前面设置,这里确保有值)
  610. if (! isset($q['question_type']) || empty($q['question_type'])) {
  611. $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
  612. if ($dbQuestion && $dbQuestion->question_type) {
  613. $q['question_type'] = $dbQuestion->question_type;
  614. }
  615. }
  616. return $q;
  617. }, $questionsData);
  618. }
  619. }
  620. }
  621. // 按题型分类(使用标准的中学数学试卷格式)
  622. $questions = ['choice' => [], 'fill' => [], 'answer' => []];
  623. foreach ($questionsData as $q) {
  624. // 题库API返回的是 stem 字段,不是 content
  625. $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
  626. // 分离题干和选项
  627. [$content, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  628. // 如果从题库API获取了选项,优先使用
  629. $options = $q['options'] ?? $extractedOptions;
  630. $answer = $q['answer'] ?? '';
  631. $solution = $q['solution'] ?? '';
  632. // 优先使用 question_type 字段,如果没有则根据内容智能判断
  633. $type = isset($q['question_type'])
  634. ? $this->normalizeQuestionTypeValue((string) $q['question_type'])
  635. : $this->determineQuestionType($q);
  636. // 详细调试:记录题目类型判断结果
  637. Log::info('题目类型判断', [
  638. 'question_id' => $q['id'] ?? '',
  639. 'has_question_type' => isset($q['question_type']),
  640. 'question_type_value' => $q['question_type'] ?? null,
  641. 'tags' => $q['tags'] ?? '',
  642. 'stem_length' => mb_strlen($content),
  643. 'stem_preview' => mb_substr($content, 0, 100),
  644. 'has_extracted_options' => ! empty($extractedOptions),
  645. 'extracted_options_count' => count($extractedOptions),
  646. 'has_api_options' => isset($q['options']) && ! empty($q['options']),
  647. 'api_options_count' => isset($q['options']) ? count($q['options']) : 0,
  648. 'final_options_count' => count($options),
  649. 'determined_type' => $type,
  650. ]);
  651. if (! isset($questions[$type])) {
  652. $type = 'answer';
  653. }
  654. // 统一处理数学公式和选项数据
  655. $questionData = [
  656. 'id' => $q['id'] ?? $q['question_bank_id'] ?? null,
  657. 'question_number' => $q['question_number'] ?? null, // 【关键】保留题目序号
  658. 'content' => $content,
  659. 'stem' => $content, // 同时提供stem字段
  660. 'answer' => $answer,
  661. 'solution' => $solution,
  662. 'difficulty' => $q['difficulty'] ?? 0.5,
  663. 'kp_code' => $q['kp_code'] ?? '',
  664. 'tags' => $q['tags'] ?? '',
  665. 'options' => $options, // 使用分离后的选项
  666. 'score' => $q['score'] ?? $this->getQuestionScore($type),
  667. 'question_type' => $type,
  668. ];
  669. // 统一处理数学公式 - 标记已处理,避免模板中重复处理
  670. $questionData = \App\Services\MathFormulaProcessor::processQuestionData($questionData);
  671. $questionData['math_processed'] = true; // 添加标记
  672. $qData = (object) $questionData;
  673. $questions[$type][] = $qData;
  674. }
  675. // 【关键】确保每个题型内的题目按 question_number 排序
  676. foreach (['choice', 'fill', 'answer'] as $type) {
  677. if (! empty($questions[$type])) {
  678. usort($questions[$type], function ($a, $b) {
  679. $aNum = $a->question_number ?? 0;
  680. $bNum = $b->question_number ?? 0;
  681. return $aNum <=> $bNum;
  682. });
  683. }
  684. }
  685. // 调试:记录最终分类结果
  686. Log::info('最终分类结果', [
  687. 'paper_id' => $paper_id,
  688. 'choice_count' => count($questions['choice']),
  689. 'fill_count' => count($questions['fill']),
  690. 'answer_count' => count($questions['answer']),
  691. 'total' => count($questions['choice']) + count($questions['fill']) + count($questions['answer']),
  692. ]);
  693. // 渲染视图
  694. $viewName = $includeAnswer ? 'pdf.exam-grading' : 'pdf.exam-paper';
  695. $studentInfo = $this->getStudentInfo($paper->student_id);
  696. $teacherInfo = $this->getTeacherInfo($paper->teacher_id);
  697. $pdfMeta = $this->buildPdfMeta($paper, (string) $paper_id, $studentInfo);
  698. return view($viewName, [
  699. 'paper' => $paper,
  700. 'questions' => $questions,
  701. 'student' => $studentInfo,
  702. 'teacher' => $teacherInfo,
  703. 'includeAnswer' => $includeAnswer,
  704. 'pdfMeta' => $pdfMeta,
  705. ]);
  706. }
  707. /**
  708. * 判卷视图:题目前带方框,题后附"正确答案+解题思路"
  709. */
  710. public function showGrading(Request $request, $paper_id)
  711. {
  712. // 复用现有逻辑获取题目分类
  713. $includeAnswer = true;
  714. // 直接调用 show 的前置逻辑(简化复用)
  715. $request->merge(['answer' => 'true']);
  716. // 复用 show() 内逻辑获取 questions/paper
  717. // 为避免重复代码,简单调用 showData 方法(拆分为私有方法?暂直接重用现有方法流程)
  718. // 这里直接复制 show 的主体以保持兼容
  719. // 使用 Eloquent 模型获取试卷数据
  720. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  721. if (! $paper) {
  722. $cached = Cache::get('generated_exam_'.$paper_id);
  723. if (! $cached) {
  724. abort(404, '试卷未找到');
  725. }
  726. $paper = (object) [
  727. 'paper_id' => $paper_id,
  728. 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
  729. 'student_id' => $cached['student_id'] ?? null,
  730. 'teacher_id' => $cached['teacher_id'] ?? null,
  731. 'paper_type' => $cached['assemble_type'] ?? null,
  732. ];
  733. $questionsData = $cached['questions'] ?? [];
  734. $totalQuestions = $cached['total_questions'] ?? count($questionsData);
  735. $difficultyCategory = $cached['difficulty_category'] ?? '中等';
  736. if (! empty($questionsData)) {
  737. $questionBankService = app(QuestionBankService::class);
  738. $questionIds = array_column($questionsData, 'id');
  739. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  740. $responseData = $questionsResponse['data'] ?? [];
  741. if (! empty($responseData)) {
  742. $responseDataMap = [];
  743. foreach ($responseData as $respQ) {
  744. $responseDataMap[$respQ['id']] = $respQ;
  745. }
  746. $questionsData = array_map(function ($q) use ($responseDataMap) {
  747. if (isset($responseDataMap[$q['id']])) {
  748. $apiData = $responseDataMap[$q['id']];
  749. $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  750. [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  751. $q['stem'] = $stem;
  752. $q['content'] = $stem; // 同时设置content字段
  753. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  754. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  755. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  756. // 优先使用API选项,支持多种数据格式
  757. $apiOptions = $apiData['options'] ?? null;
  758. if (! empty($apiOptions)) {
  759. // 标准化options格式为数组值列表
  760. $q['options'] = $this->normalizeOptions($apiOptions);
  761. Log::debug('使用标准化API options', [
  762. 'question_id' => $q['id'],
  763. 'raw_options' => $apiOptions,
  764. 'normalized_options' => $q['options'],
  765. ]);
  766. } else {
  767. // 备选:从题干中提取的选项
  768. $q['options'] = $extractedOptions;
  769. Log::debug('使用提取的options', [
  770. 'question_id' => $q['id'],
  771. 'extracted_options' => $extractedOptions,
  772. ]);
  773. }
  774. }
  775. return $q;
  776. }, $questionsData);
  777. }
  778. }
  779. if (count($questionsData) > $totalQuestions) {
  780. $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
  781. }
  782. } else {
  783. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
  784. ->orderBy('question_number')
  785. ->get();
  786. $questionsData = [];
  787. foreach ($paperQuestions as $pq) {
  788. $questionsData[] = [
  789. 'id' => $pq->question_bank_id,
  790. 'question_number' => $pq->question_number, // 【关键】保留题目序号
  791. 'kp_code' => $pq->knowledge_point,
  792. 'question_type' => $pq->question_type ?? 'answer',
  793. 'stem' => $pq->question_text ?? '题目内容缺失',
  794. 'solution' => $pq->solution ?? '', // 保存解题思路!
  795. 'answer' => $pq->correct_answer ?? '', // 保存正确答案
  796. 'difficulty' => $pq->difficulty ?? 0.5,
  797. 'score' => $pq->score ?? 5,
  798. 'tags' => '',
  799. 'content' => $pq->question_text ?? '',
  800. ];
  801. }
  802. if (! empty($questionsData)) {
  803. $questionBankService = app(QuestionBankService::class);
  804. $questionIds = array_column($questionsData, 'id');
  805. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  806. $responseData = $questionsResponse['data'] ?? [];
  807. if (! empty($responseData)) {
  808. $responseDataMap = [];
  809. foreach ($responseData as $respQ) {
  810. $responseDataMap[$respQ['id']] = $respQ;
  811. }
  812. $questionsData = array_map(function ($q) use ($responseDataMap, $paperQuestions) {
  813. if (isset($responseDataMap[$q['id']])) {
  814. $apiData = $responseDataMap[$q['id']];
  815. $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
  816. [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  817. $q['stem'] = $stem;
  818. $q['content'] = $stem; // 同时设置content字段
  819. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  820. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  821. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  822. // 优先使用API选项,支持多种数据格式
  823. $apiOptions = $apiData['options'] ?? null;
  824. if (! empty($apiOptions)) {
  825. // 标准化options格式为数组值列表
  826. $q['options'] = $this->normalizeOptions($apiOptions);
  827. Log::debug('使用标准化API options', [
  828. 'question_id' => $q['id'],
  829. 'raw_options' => $apiOptions,
  830. 'normalized_options' => $q['options'],
  831. ]);
  832. } else {
  833. // 备选:从题干中提取的选项
  834. $q['options'] = $extractedOptions;
  835. Log::debug('使用提取的options', [
  836. 'question_id' => $q['id'],
  837. 'extracted_options' => $extractedOptions,
  838. ]);
  839. }
  840. }
  841. if (! isset($q['question_type']) || empty($q['question_type'])) {
  842. $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
  843. if ($dbQuestion && $dbQuestion->question_type) {
  844. $q['question_type'] = $dbQuestion->question_type;
  845. }
  846. }
  847. return $q;
  848. }, $questionsData);
  849. }
  850. }
  851. }
  852. $questions = ['choice' => [], 'fill' => [], 'answer' => []];
  853. foreach ($questionsData as $q) {
  854. $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
  855. [$content, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  856. $options = $q['options'] ?? $extractedOptions;
  857. $answer = $q['answer'] ?? '';
  858. $solution = $q['solution'] ?? '';
  859. $type = isset($q['question_type'])
  860. ? $this->normalizeQuestionTypeValue((string) $q['question_type'])
  861. : $this->determineQuestionType($q);
  862. if (! isset($questions[$type])) {
  863. $type = 'answer';
  864. }
  865. // 统一处理数学公式和选项数据
  866. $questionData = [
  867. 'id' => $q['id'] ?? $q['question_bank_id'] ?? null,
  868. 'question_number' => $q['question_number'] ?? null, // 【关键】保留题目序号
  869. 'content' => $content,
  870. 'stem' => $content, // 同时提供stem字段
  871. 'answer' => $answer,
  872. 'solution' => $solution,
  873. 'difficulty' => $q['difficulty'] ?? 0.5,
  874. 'kp_code' => $q['kp_code'] ?? '',
  875. 'tags' => $q['tags'] ?? '',
  876. 'options' => $options,
  877. 'score' => $q['score'] ?? $this->getQuestionScore($type),
  878. 'question_type' => $type,
  879. ];
  880. // 统一处理数学公式 - 标记已处理,避免模板中重复处理
  881. $questionData = \App\Services\MathFormulaProcessor::processQuestionData($questionData);
  882. $questionData['math_processed'] = true; // 添加标记
  883. $qData = (object) $questionData;
  884. $questions[$type][] = $qData;
  885. }
  886. // 【关键】确保每个题型内的题目按 question_number 排序
  887. foreach (['choice', 'fill', 'answer'] as $type) {
  888. if (! empty($questions[$type])) {
  889. usort($questions[$type], function ($a, $b) {
  890. $aNum = $a->question_number ?? 0;
  891. $bNum = $b->question_number ?? 0;
  892. return $aNum <=> $bNum;
  893. });
  894. }
  895. }
  896. $studentInfo = $this->getStudentInfo($paper->student_id);
  897. $teacherInfo = $this->getTeacherInfo($paper->teacher_id);
  898. $pdfMeta = $this->buildPdfMeta($paper, (string) $paper_id, $studentInfo);
  899. $appendScanSheet = config('exam.pdf_grading_append_scan_sheet', false);
  900. $gradingView = $appendScanSheet ? 'pdf.exam-answer-detail' : 'pdf.exam-grading';
  901. return view($gradingView, [
  902. 'paper' => $paper,
  903. 'questions' => $questions,
  904. 'student' => $studentInfo,
  905. 'teacher' => $teacherInfo,
  906. 'includeAnswer' => true,
  907. 'pdfMeta' => $pdfMeta,
  908. ]);
  909. }
  910. /**
  911. * 知识点讲解视图
  912. */
  913. public function showKnowledgeExplanation(Request $request, $paper_id)
  914. {
  915. // 获取试卷数据
  916. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  917. if (! $paper) {
  918. abort(404, '试卷未找到');
  919. }
  920. $studentInfo = $this->getStudentInfo($paper->student_id);
  921. $pdfMeta = $this->buildPdfMeta($paper, (string) $paper_id, $studentInfo);
  922. $studentName = $pdfMeta['student_name'];
  923. // 生成时间(格式:2026年01月30日 15:04:05)
  924. $generateDateTime = now()->format('Y年m月d日 H:i:s');
  925. // 优先使用 paper 中保存的 explanation_kp_codes(组卷时指定的知识点,最多2个)
  926. $kpCodes = $paper->explanation_kp_codes ?? [];
  927. // 如果没有保存 explanation_kp_codes,回退到从题目中提取(兼容旧数据)
  928. if (empty($kpCodes)) {
  929. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)->get();
  930. $seen = [];
  931. $questionBankIds = $paperQuestions
  932. ->pluck('question_bank_id')
  933. ->filter()
  934. ->unique()
  935. ->values();
  936. $questionKpMap = [];
  937. if ($questionBankIds->isNotEmpty()) {
  938. $questionKpMap = \App\Models\Question::whereIn('id', $questionBankIds)
  939. ->pluck('kp_code', 'id')
  940. ->toArray();
  941. }
  942. foreach ($paperQuestions as $pq) {
  943. $kpCode = trim((string) ($pq->knowledge_point ?? ''));
  944. if ($kpCode === '' && ! empty($pq->question_bank_id)) {
  945. $kpCode = trim((string) ($questionKpMap[$pq->question_bank_id] ?? ''));
  946. }
  947. if ($kpCode === '') {
  948. continue;
  949. }
  950. if (isset($seen[$kpCode])) {
  951. continue;
  952. }
  953. $seen[$kpCode] = true;
  954. $kpCodes[] = $kpCode;
  955. }
  956. }
  957. // 使用 ExamPdfExportService 构建知识点数据
  958. $pdfService = app(\App\Services\ExamPdfExportService::class);
  959. // 批量获取知识点讲解
  960. $knowledgePoints = $pdfService->buildExplanations($kpCodes);
  961. return view('pdf.exam-knowledge-explanation', [
  962. 'paperId' => $paper_id,
  963. 'examCode' => $pdfMeta['exam_code'],
  964. 'studentName' => $studentName,
  965. 'generateDateTime' => $generateDateTime,
  966. 'knowledgePoints' => $knowledgePoints,
  967. 'pdfMeta' => $pdfMeta,
  968. ]);
  969. }
  970. /**
  971. * 服务端渲染预览 - 试卷(与 PDF 生成效果一致,用于调试)
  972. */
  973. public function showServerRendered(Request $request, $paper_id)
  974. {
  975. // 强制不显示答案(试卷模式)
  976. $request->merge(['answer' => 'false']);
  977. // 复用 show() 获取 HTML
  978. $view = $this->show($request, $paper_id);
  979. $html = $view->render();
  980. // 使用 KatexRenderer 服务端渲染公式
  981. $katexRenderer = new \App\Services\KatexRenderer();
  982. $rendered = $katexRenderer->disableCache()->renderHtml($html);
  983. return response($rendered);
  984. }
  985. /**
  986. * 服务端渲染预览 - 判卷(与 PDF 生成效果一致,用于调试)
  987. */
  988. public function showGradingServerRendered(Request $request, $paper_id)
  989. {
  990. // 复用 showGrading() 获取 HTML
  991. $view = $this->showGrading($request, $paper_id);
  992. $html = $view->render();
  993. // 使用 KatexRenderer 服务端渲染公式
  994. $katexRenderer = new \App\Services\KatexRenderer();
  995. $rendered = $katexRenderer->disableCache()->renderHtml($html);
  996. return response($rendered);
  997. }
  998. /**
  999. * 重新生成 PDF(统一生成卷子和判卷)
  1000. *
  1001. * @param string $paper_id
  1002. * @return \Illuminate\Http\JsonResponse
  1003. */
  1004. public function regeneratePdf(Request $request, $paper_id)
  1005. {
  1006. Log::info('RegeneratePdf: 开始重新生成PDF', ['paper_id' => $paper_id]);
  1007. // 验证 paper_id 格式
  1008. if (empty($paper_id) || ! preg_match('/^paper_\d+$/', $paper_id)) {
  1009. return response()->json([
  1010. 'success' => false,
  1011. 'message' => '无效的试卷ID格式',
  1012. 'paper_id' => $paper_id,
  1013. ], 400);
  1014. }
  1015. try {
  1016. // 【修复】首先检查试卷是否存在
  1017. $paperModel = Paper::with('questions')->find($paper_id);
  1018. if (! $paperModel || $paperModel->questions->isEmpty()) {
  1019. return response()->json([
  1020. 'success' => false,
  1021. 'message' => '无效的试卷',
  1022. 'paper_id' => $paper_id,
  1023. ], 400);
  1024. }
  1025. // 根据 config 或 env 配置决定是否包含知识点讲解
  1026. // 还需要判断如果摸底(paper_type =0)的时候也是不需要插入知识点讲解内容
  1027. $includeKpExplain = null;
  1028. if ($request->has('include_kp_explain')) {
  1029. $includeKpExplain = filter_var(
  1030. $request->input('include_kp_explain'),
  1031. FILTER_VALIDATE_BOOLEAN,
  1032. FILTER_NULL_ON_FAILURE
  1033. );
  1034. } elseif ($paperModel->paper_type === 0) {
  1035. $includeKpExplain = false;
  1036. }
  1037. info("includekpexplain", [$includeKpExplain]);
  1038. // 调用 PDF 生成服务
  1039. $pdfService = app(\App\Services\ExamPdfExportService::class);
  1040. // 生成统一 PDF(卷子 + 判卷)
  1041. $pdfUrl = $pdfService->generateUnifiedPdf($paper_id, $includeKpExplain);
  1042. if ($pdfUrl) {
  1043. Log::info('RegeneratePdf: PDF重新生成成功', [
  1044. 'paper_id' => $paper_id,
  1045. 'url' => $pdfUrl,
  1046. ]);
  1047. return response()->json([
  1048. 'success' => true,
  1049. 'message' => 'PDF重新生成成功',
  1050. 'paper_id' => $paper_id,
  1051. 'pdf_url' => $pdfUrl,
  1052. ]);
  1053. }
  1054. Log::error('RegeneratePdf: PDF生成失败', ['paper_id' => $paper_id]);
  1055. return response()->json([
  1056. 'success' => false,
  1057. 'message' => 'PDF生成失败',
  1058. 'paper_id' => $paper_id,
  1059. ], 500);
  1060. } catch (\Exception $e) {
  1061. Log::error('RegeneratePdf: 异常错误', [
  1062. 'paper_id' => $paper_id,
  1063. 'error' => $e->getMessage(),
  1064. 'trace' => $e->getTraceAsString(),
  1065. ]);
  1066. return response()->json([
  1067. 'success' => false,
  1068. 'message' => 'PDF生成异常:'.$e->getMessage(),
  1069. 'paper_id' => $paper_id,
  1070. ], 500);
  1071. }
  1072. }
  1073. /**
  1074. * 重新生成试卷 PDF(不含答案)
  1075. *
  1076. * @param string $paper_id
  1077. * @return \Illuminate\Http\JsonResponse
  1078. */
  1079. public function regenerateExamPdf(Request $request, $paper_id)
  1080. {
  1081. Log::info('RegenerateExamPdf: 开始重新生成试卷PDF', ['paper_id' => $paper_id]);
  1082. if (empty($paper_id) || ! preg_match('/^paper_\d+$/', $paper_id)) {
  1083. return response()->json([
  1084. 'success' => false,
  1085. 'message' => '无效的试卷ID格式',
  1086. 'paper_id' => $paper_id,
  1087. ], 400);
  1088. }
  1089. try {
  1090. $pdfService = app(\App\Services\ExamPdfExportService::class);
  1091. $pdfUrl = $pdfService->generateExamPdf($paper_id);
  1092. if ($pdfUrl) {
  1093. return response()->json([
  1094. 'success' => true,
  1095. 'message' => '试卷PDF重新生成成功',
  1096. 'paper_id' => $paper_id,
  1097. 'pdf_url' => $pdfUrl,
  1098. ]);
  1099. }
  1100. return response()->json([
  1101. 'success' => false,
  1102. 'message' => '试卷PDF生成失败',
  1103. 'paper_id' => $paper_id,
  1104. ], 500);
  1105. } catch (\Exception $e) {
  1106. Log::error('RegenerateExamPdf: 异常错误', [
  1107. 'paper_id' => $paper_id,
  1108. 'error' => $e->getMessage(),
  1109. ]);
  1110. return response()->json([
  1111. 'success' => false,
  1112. 'message' => 'PDF生成异常:'.$e->getMessage(),
  1113. 'paper_id' => $paper_id,
  1114. ], 500);
  1115. }
  1116. }
  1117. /**
  1118. * 重新生成判卷 PDF(含答案)
  1119. *
  1120. * @param string $paper_id
  1121. * @return \Illuminate\Http\JsonResponse
  1122. */
  1123. public function regenerateGradingPdf(Request $request, $paper_id)
  1124. {
  1125. Log::info('RegenerateGradingPdf: 开始重新生成判卷PDF', ['paper_id' => $paper_id]);
  1126. if (empty($paper_id) || ! preg_match('/^paper_\d+$/', $paper_id)) {
  1127. return response()->json([
  1128. 'success' => false,
  1129. 'message' => '无效的试卷ID格式',
  1130. 'paper_id' => $paper_id,
  1131. ], 400);
  1132. }
  1133. try {
  1134. $pdfService = app(\App\Services\ExamPdfExportService::class);
  1135. $pdfUrl = $pdfService->generateGradingPdf($paper_id);
  1136. if ($pdfUrl) {
  1137. return response()->json([
  1138. 'success' => true,
  1139. 'message' => '判卷PDF重新生成成功',
  1140. 'paper_id' => $paper_id,
  1141. 'pdf_url' => $pdfUrl,
  1142. ]);
  1143. }
  1144. return response()->json([
  1145. 'success' => false,
  1146. 'message' => '判卷PDF生成失败',
  1147. 'paper_id' => $paper_id,
  1148. ], 500);
  1149. } catch (\Exception $e) {
  1150. Log::error('RegenerateGradingPdf: 异常错误', [
  1151. 'paper_id' => $paper_id,
  1152. 'error' => $e->getMessage(),
  1153. ]);
  1154. return response()->json([
  1155. 'success' => false,
  1156. 'message' => 'PDF生成异常:'.$e->getMessage(),
  1157. 'paper_id' => $paper_id,
  1158. ], 500);
  1159. }
  1160. }
  1161. /**
  1162. * 批量重新生成 PDF:按时间区间遍历 completed_at=NULL 的卷子,使用新的分析重新生成统一 PDF 入库
  1163. *
  1164. * 基于 /api/papers/{paper_id}/regenerate 逻辑,遍历指定时间段创建且未完成的试卷。
  1165. * 时间格式 Y-m-d,start_date 从 00:00:00,end_date 到 23:59:59。
  1166. *
  1167. * @return \Illuminate\Http\JsonResponse
  1168. */
  1169. public function regeneratePdfBatch(Request $request)
  1170. {
  1171. // 批量 PDF 生成耗时较长,解除 30 秒执行限制(Guzzle 等会触发)
  1172. set_time_limit(0);
  1173. $startDate = $request->input('start_date');
  1174. $endDate = $request->input('end_date');
  1175. $limit = (int) $request->input('limit', 100);
  1176. $datePattern = '/^\d{4}-\d{2}-\d{2}$/';
  1177. if (empty($startDate) || ! preg_match($datePattern, $startDate)) {
  1178. return response()->json([
  1179. 'success' => false,
  1180. 'message' => '参数 start_date 必填,格式 Y-m-d(如 2026-03-20)',
  1181. ], 400);
  1182. }
  1183. if (empty($endDate) || ! preg_match($datePattern, $endDate)) {
  1184. return response()->json([
  1185. 'success' => false,
  1186. 'message' => '参数 end_date 必填,格式 Y-m-d(如 2026-03-22)',
  1187. ], 400);
  1188. }
  1189. if ($startDate > $endDate) {
  1190. return response()->json([
  1191. 'success' => false,
  1192. 'message' => 'start_date 不能大于 end_date',
  1193. ], 400);
  1194. }
  1195. $startTime = $startDate.' 00:00:00';
  1196. $endTime = $endDate.' 23:59:59';
  1197. $includeKpExplain = $request->has('include_kp_explain')
  1198. ? filter_var($request->input('include_kp_explain'), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)
  1199. : null;
  1200. Log::info('RegeneratePdfBatch: 开始批量重生成', [
  1201. 'start_date' => $startDate,
  1202. 'end_date' => $endDate,
  1203. 'limit' => $limit,
  1204. ]);
  1205. try {
  1206. $papers = Paper::with('questions')
  1207. ->whereBetween('created_at', [$startTime, $endTime])
  1208. ->whereNull('completed_at')
  1209. ->orderBy('paper_id')
  1210. ->limit($limit)
  1211. ->get();
  1212. if ($papers->isEmpty()) {
  1213. return response()->json([
  1214. 'success' => true,
  1215. 'message' => '未找到符合条件的试卷',
  1216. 'start_date' => $startDate,
  1217. 'end_date' => $endDate,
  1218. 'total' => 0,
  1219. 'success_count' => 0,
  1220. 'fail_count' => 0,
  1221. 'details' => [],
  1222. ]);
  1223. }
  1224. $pdfService = app(\App\Services\ExamPdfExportService::class);
  1225. $successList = [];
  1226. $failList = [];
  1227. foreach ($papers as $paper) {
  1228. if ($paper->questions->isEmpty()) {
  1229. $failList[] = [
  1230. 'paper_id' => $paper->paper_id,
  1231. 'reason' => '无题目',
  1232. ];
  1233. continue;
  1234. }
  1235. $useKpExplain = $includeKpExplain ?? ($paper->paper_type !== 0);
  1236. try {
  1237. $pdfUrl = $pdfService->generateUnifiedPdf($paper->paper_id, $useKpExplain);
  1238. if ($pdfUrl) {
  1239. $successList[] = [
  1240. 'paper_id' => $paper->paper_id,
  1241. 'pdf_url' => $pdfUrl,
  1242. ];
  1243. Log::info('RegeneratePdfBatch: 成功', ['paper_id' => $paper->paper_id]);
  1244. } else {
  1245. $failList[] = [
  1246. 'paper_id' => $paper->paper_id,
  1247. 'reason' => 'generateUnifiedPdf 返回空',
  1248. ];
  1249. }
  1250. } catch (\Exception $e) {
  1251. Log::error('RegeneratePdfBatch: 异常', [
  1252. 'paper_id' => $paper->paper_id,
  1253. 'error' => $e->getMessage(),
  1254. ]);
  1255. $failList[] = [
  1256. 'paper_id' => $paper->paper_id,
  1257. 'reason' => $e->getMessage(),
  1258. ];
  1259. }
  1260. }
  1261. return response()->json([
  1262. 'success' => true,
  1263. 'message' => '批量重生成完成',
  1264. 'start_date' => $startDate,
  1265. 'end_date' => $endDate,
  1266. 'total' => $papers->count(),
  1267. 'success_count' => count($successList),
  1268. 'fail_count' => count($failList),
  1269. 'details' => [
  1270. 'succeeded' => $successList,
  1271. 'failed' => $failList,
  1272. ],
  1273. ]);
  1274. } catch (\Exception $e) {
  1275. Log::error('RegeneratePdfBatch: 批量异常', ['error' => $e->getMessage()]);
  1276. return response()->json([
  1277. 'success' => false,
  1278. 'message' => '批量重生成异常:'.$e->getMessage(),
  1279. ], 500);
  1280. }
  1281. }
  1282. }