ExamPdfController.php 65 KB

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