ExamPdfController.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Services\QuestionBankService;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\Log;
  8. class ExamPdfController extends Controller
  9. {
  10. /**
  11. * 标准化选项格式为数组值列表
  12. * 支持格式:
  13. * 1. {"A": "0", "B": "5", "C": "-3", "D": "12"} -> ["0", "5", "-3", "12"]
  14. * 2. [["label": "A", "text": "选项A"], ...] -> ["选项A", "选项B", ...]
  15. * 3. ["A", "B", "C", "D"] -> ["A", "B", "C", "D"]
  16. */
  17. private function normalizeOptions($options): array
  18. {
  19. if (empty($options)) {
  20. return [];
  21. }
  22. // 如果是对象格式 {"A": "值1", "B": "值2", ...}
  23. if (is_array($options) && !isset($options[0])) {
  24. return array_values($options);
  25. }
  26. // 如果是AI生成格式 [{"label": "A", "text": "选项A"}, ...]
  27. if (is_array($options) && isset($options[0]) && is_array($options[0])) {
  28. // 提取text字段,如果不存在则使用整个数组元素
  29. $normalized = [];
  30. foreach ($options as $opt) {
  31. if (isset($opt['text'])) {
  32. $normalized[] = $opt['text'];
  33. } elseif (isset($opt['value'])) {
  34. $normalized[] = $opt['value'];
  35. } else {
  36. // 如果既没有text也没有value,取数组的第一个值
  37. $normalized[] = is_array($opt) ? (string) reset($opt) : (string) $opt;
  38. }
  39. }
  40. return $normalized;
  41. }
  42. // 如果已经是简单数组格式 ["A", "B", "C", "D"]
  43. if (is_array($options)) {
  44. return array_values($options);
  45. }
  46. // 其他情况返回空数组
  47. return [];
  48. }
  49. /**
  50. * 根据题目内容或类型字段判断题型
  51. */
  52. private function determineQuestionType(array $question): string
  53. {
  54. // 优先根据题目内容判断(而不是数据库字段)
  55. $stem = $question['stem'] ?? $question['content'] ?? '';
  56. $tags = $question['tags'] ?? '';
  57. $skills = $question['skills'] ?? [];
  58. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  59. if (is_string($stem)) {
  60. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  61. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  62. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  63. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  64. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  65. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  66. // 至少有2个选项就认为是选择题(降低阈值)
  67. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  68. if ($optionCount >= 2) {
  69. return 'choice';
  70. }
  71. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  72. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  73. return 'choice';
  74. }
  75. }
  76. // 2. 根据技能点判断
  77. if (is_array($skills)) {
  78. $skillsStr = implode(',', $skills);
  79. if (strpos($skillsStr, '选择题') !== false) return 'choice';
  80. if (strpos($skillsStr, '填空题') !== false) return 'fill';
  81. if (strpos($skillsStr, '解答题') !== false) return 'answer';
  82. }
  83. // 3. 根据题目已有类型字段判断(作为后备)
  84. if (!empty($question['question_type'])) {
  85. $type = strtolower(trim($question['question_type']));
  86. if (in_array($type, ['choice', '选择题', 'choice question'])) return 'choice';
  87. if (in_array($type, ['fill', '填空题', 'fill in the blank'])) return 'fill';
  88. if (in_array($type, ['answer', '解答题', 'calculation', '简答题'])) return 'answer';
  89. }
  90. if (!empty($question['type'])) {
  91. $type = strtolower(trim($question['type']));
  92. if (in_array($type, ['choice', '选择题', 'choice question'])) return 'choice';
  93. if (in_array($type, ['fill', '填空题', 'fill in the blank'])) return 'fill';
  94. if (in_array($type, ['answer', '解答题', 'calculation', '简答题'])) return 'answer';
  95. }
  96. // 4. 根据标签判断
  97. if (is_string($tags)) {
  98. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  99. return 'choice';
  100. }
  101. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  102. return 'fill';
  103. }
  104. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  105. return 'answer';
  106. }
  107. }
  108. // 5. 填空题特征:连续下划线或明显的填空括号
  109. if (is_string($stem)) {
  110. // 检查填空题特征:连续下划线
  111. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  112. return 'fill';
  113. }
  114. // 空括号填空
  115. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  116. return 'fill';
  117. }
  118. }
  119. // 6. 根据题干内容关键词判断
  120. if (is_string($stem)) {
  121. // 有证明、解答、计算、求证等关键词的是解答题
  122. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  123. return 'answer';
  124. }
  125. }
  126. // 默认是解答题(更安全的默认值)
  127. return 'answer';
  128. }
  129. private function normalizeQuestionTypeValue(string $type): string
  130. {
  131. $type = trim($type);
  132. $lower = strtolower($type);
  133. if (in_array($lower, ['choice', 'single_choice', 'multiple_choice'], true)) {
  134. return 'choice';
  135. }
  136. if (in_array($lower, ['fill', 'blank', 'fill_in_the_blank'], true)) {
  137. return 'fill';
  138. }
  139. if (in_array($lower, ['answer', 'calculation', 'word_problem', 'proof'], true)) {
  140. return 'answer';
  141. }
  142. if (in_array($type, ['CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  143. return 'choice';
  144. }
  145. if (in_array($type, ['FILL', 'FILL_IN_THE_BLANK'], true)) {
  146. return 'fill';
  147. }
  148. if (in_array($type, ['CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
  149. return 'answer';
  150. }
  151. if (in_array($type, ['选择题'], true)) {
  152. return 'choice';
  153. }
  154. if (in_array($type, ['填空题'], true)) {
  155. return 'fill';
  156. }
  157. if (in_array($type, ['解答题', '计算题'], true)) {
  158. return 'answer';
  159. }
  160. return $lower ?: 'answer';
  161. }
  162. /**
  163. * 从题目内容中提取选项
  164. */
  165. private function extractOptions(string $content): array
  166. {
  167. $options = [];
  168. // 【修复】先移除SVG内容,避免误匹配SVG注释中的 BD:DC、A:B 等内容
  169. $contentWithoutSvg = preg_replace('/<svg[^>]*>.*?<\/svg>/is', '[SVG_PLACEHOLDER]', $content);
  170. // 1. 尝试匹配多种格式的选项:A. / A、/ A: / A.(中文句点)/ A.(无空格)
  171. // 【修复】选项标记必须在行首或空白后,避免误匹配 SVG 注释中的 BD:DC 等内容
  172. $pattern = '/(?:^|\s)([A-D])[\.、:.:]\s*(.+?)(?=(?:^|\s)[A-D][\.、:.:]|$)/su';
  173. if (preg_match_all($pattern, $contentWithoutSvg, $matches, PREG_SET_ORDER)) {
  174. foreach ($matches as $match) {
  175. $optionText = trim($match[2]);
  176. // 移除末尾的换行和空白
  177. $optionText = preg_replace('/\s+$/', '', $optionText);
  178. // 清理 LaTeX 格式但保留内容
  179. $optionText = preg_replace('/^\$\$\s*/', '', $optionText);
  180. $optionText = preg_replace('/\s*\$\$$/', '', $optionText);
  181. if (!empty($optionText)) {
  182. $options[] = $optionText;
  183. }
  184. }
  185. }
  186. // 2. 如果上面没提取到,尝试按换行分割
  187. if (empty($options)) {
  188. $lines = preg_split('/[\r\n]+/', $contentWithoutSvg);
  189. foreach ($lines as $line) {
  190. $line = trim($line);
  191. // 【修复】行首匹配选项标记
  192. if (preg_match('/^([A-D])[\.、:.:]\s*(.+)$/u', $line, $match)) {
  193. $optionText = trim($match[2]);
  194. if (!empty($optionText)) {
  195. $options[] = $optionText;
  196. }
  197. }
  198. }
  199. }
  200. Log::debug('选项提取结果', [
  201. 'content_preview' => mb_substr($content, 0, 150),
  202. 'options_count' => count($options),
  203. 'options' => $options
  204. ]);
  205. return $options;
  206. }
  207. /**
  208. * 分离题干内容和选项
  209. */
  210. private function separateStemAndOptions(string $content): array
  211. {
  212. // 【修复】先移除SVG内容,避免误匹配SVG注释中的 BD:DC、A:B 等内容
  213. $contentWithoutSvg = preg_replace('/<svg[^>]*>.*?<\/svg>/is', '[SVG_PLACEHOLDER]', $content);
  214. // 【修复】检测是否有选项时,要求选项标记在行首或空白后
  215. $hasOptions = preg_match('/(?:^|\s)[A-D][\.、:.:]/u', $contentWithoutSvg);
  216. if (!$hasOptions) {
  217. return [$content, []];
  218. }
  219. // 提取选项
  220. $options = $this->extractOptions($content);
  221. // 如果提取到选项,分离题干
  222. if (!empty($options)) {
  223. // 【修复】找到第一个选项的位置,要求选项标记在行首或空白后
  224. if (preg_match('/^(.+?)(?=(?:^|\s)[A-D][\.、:.:])/su', $contentWithoutSvg, $match)) {
  225. $stem = trim($match[1]);
  226. // 如果题干中有SVG占位符,从原始内容中提取对应部分
  227. if (strpos($stem, '[SVG_PLACEHOLDER]') !== false) {
  228. // 找到原始内容中对应位置的题干
  229. $stemLength = mb_strlen(str_replace('[SVG_PLACEHOLDER]', '', $stem));
  230. // 使用更精确的方法:找到第一个有效选项标记的位置
  231. foreach (['A.', 'A、', 'A:', 'A.', 'A:'] as $marker) {
  232. // 只匹配在空白后的选项标记
  233. if (preg_match('/\s' . preg_quote($marker, '/') . '/', $content, $m, PREG_OFFSET_CAPTURE)) {
  234. $pos = $m[0][1];
  235. if ($pos > 0) {
  236. $stem = trim(mb_substr($content, 0, $pos));
  237. break;
  238. }
  239. }
  240. }
  241. }
  242. } else {
  243. // 如果正则失败,尝试按位置分割
  244. $stem = $content;
  245. foreach (['A.', 'A、', 'A:', 'A.', 'A:'] as $marker) {
  246. // 【修复】只匹配在空白后的选项标记
  247. if (preg_match('/\s' . preg_quote($marker, '/') . '/', $content, $m, PREG_OFFSET_CAPTURE)) {
  248. $pos = $m[0][1];
  249. if ($pos > 0) {
  250. $stem = trim(mb_substr($content, 0, $pos));
  251. break;
  252. }
  253. }
  254. }
  255. }
  256. // 移除末尾的括号或空白
  257. $stem = preg_replace('/()\s*$/', '', $stem);
  258. $stem = trim($stem);
  259. return [$stem, $options];
  260. }
  261. return [$content, []];
  262. }
  263. /**
  264. * 根据题型获取默认分数
  265. */
  266. private function getQuestionScore(string $type): int
  267. {
  268. switch ($type) {
  269. case 'choice':
  270. return 5; // 选择题5分
  271. case 'fill':
  272. return 5; // 填空题5分
  273. case 'answer':
  274. return 10; // 解答题10分
  275. default:
  276. return 5;
  277. }
  278. }
  279. /**
  280. * 获取学生信息
  281. */
  282. private function getStudentInfo(?string $studentId): array
  283. {
  284. if (!$studentId) {
  285. return [
  286. 'name' => '未知学生',
  287. 'grade' => '未知年级',
  288. 'class' => '未知班级'
  289. ];
  290. }
  291. try {
  292. $student = DB::table('students')
  293. ->where('student_id', $studentId)
  294. ->first();
  295. if ($student) {
  296. return [
  297. 'name' => $student->name ?? $studentId,
  298. 'grade' => $student->grade ?? '未知',
  299. 'class' => $student->class ?? '未知'
  300. ];
  301. }
  302. } catch (\Exception $e) {
  303. Log::warning('获取学生信息失败', [
  304. 'student_id' => $studentId,
  305. 'error' => $e->getMessage()
  306. ]);
  307. }
  308. return [
  309. 'name' => $studentId,
  310. 'grade' => '未知',
  311. 'class' => '未知'
  312. ];
  313. }
  314. /**
  315. * 为 PDF 预览筛选题目(简化版)
  316. */
  317. private function selectBestQuestionsForPdf(array $questions, int $targetCount, string $difficultyCategory): array
  318. {
  319. if (count($questions) <= $targetCount) {
  320. return $questions;
  321. }
  322. // 1. 按题型分类题目
  323. $categorizedQuestions = [
  324. 'choice' => [],
  325. 'fill' => [],
  326. 'answer' => [],
  327. ];
  328. foreach ($questions as $question) {
  329. $type = $this->determineQuestionType($question);
  330. if (!isset($categorizedQuestions[$type])) {
  331. $type = 'answer';
  332. }
  333. $categorizedQuestions[$type][] = $question;
  334. }
  335. // 2. 默认题型配比
  336. $typeRatio = [
  337. '选择题' => 50, // 50%
  338. '填空题' => 30, // 30%
  339. '解答题' => 20, // 20%
  340. ];
  341. // 3. 根据配比选择题目
  342. $selectedQuestions = [];
  343. foreach ($typeRatio as $type => $ratio) {
  344. $typeKey = $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer');
  345. $countForType = floor($targetCount * $ratio / 100);
  346. if ($countForType > 0 && !empty($categorizedQuestions[$typeKey])) {
  347. $availableCount = count($categorizedQuestions[$typeKey]);
  348. $takeCount = min($countForType, $availableCount, $targetCount - count($selectedQuestions));
  349. // 随机选择题目
  350. $keys = array_keys($categorizedQuestions[$typeKey]);
  351. shuffle($keys);
  352. $selectedKeys = array_slice($keys, 0, $takeCount);
  353. foreach ($selectedKeys as $key) {
  354. $selectedQuestions[] = $categorizedQuestions[$typeKey][$key];
  355. }
  356. }
  357. }
  358. // 4. 如果数量不足,随机补充
  359. while (count($selectedQuestions) < $targetCount) {
  360. $randomQuestion = $questions[array_rand($questions)];
  361. if (!in_array($randomQuestion, $selectedQuestions)) {
  362. $selectedQuestions[] = $randomQuestion;
  363. }
  364. }
  365. // 5. 限制数量并打乱
  366. shuffle($selectedQuestions);
  367. return array_slice($selectedQuestions, 0, $targetCount);
  368. }
  369. /**
  370. * 获取教师信息
  371. */
  372. private function getTeacherInfo(?string $teacherId): array
  373. {
  374. if (!$teacherId) {
  375. return [
  376. 'name' => '未知教师'
  377. ];
  378. }
  379. try {
  380. $teacher = DB::table('teachers')
  381. ->where('teacher_id', $teacherId)
  382. ->first();
  383. if ($teacher) {
  384. return [
  385. 'name' => $teacher->name ?? $teacherId
  386. ];
  387. }
  388. } catch (\Exception $e) {
  389. Log::warning('获取教师信息失败', [
  390. 'teacher_id' => $teacherId,
  391. 'error' => $e->getMessage()
  392. ]);
  393. }
  394. return [
  395. 'name' => $teacherId
  396. ];
  397. }
  398. public function show(Request $request, $paper_id)
  399. {
  400. // 获取是否显示答案的参数,默认为true
  401. $includeAnswer = $request->query('answer', 'true') !== 'false';
  402. // 使用 Eloquent 模型获取试卷数据
  403. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  404. if (!$paper) {
  405. // 尝试从缓存中获取生成的试卷数据(用于 demo 试卷)
  406. $cached = Cache::get('generated_exam_' . $paper_id);
  407. if ($cached) {
  408. Log::info('从缓存获取试卷数据', [
  409. 'paper_id' => $paper_id,
  410. 'cached_count' => count($cached['questions'] ?? []),
  411. 'cached_question_types' => array_column($cached['questions'] ?? [], 'question_type')
  412. ]);
  413. // 构造临时 Paper 对象
  414. $paper = (object)[
  415. 'paper_id' => $paper_id,
  416. 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
  417. 'student_id' => $cached['student_id'] ?? null,
  418. 'teacher_id' => $cached['teacher_id'] ?? null,
  419. ];
  420. // 对于 demo 试卷,需要检查题目数量并限制为用户要求的数量
  421. $questionsData = $cached['questions'] ?? [];
  422. $totalQuestions = $cached['total_questions'] ?? count($questionsData);
  423. $difficultyCategory = $cached['difficulty_category'] ?? '中等';
  424. // 为 demo 试卷获取完整的题目详情(包括选项)
  425. if (!empty($questionsData)) {
  426. $questionBankService = app(QuestionBankService::class);
  427. $questionIds = array_column($questionsData, 'id');
  428. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  429. $responseData = $questionsResponse['data'] ?? [];
  430. if (!empty($responseData)) {
  431. $responseDataMap = [];
  432. foreach ($responseData as $respQ) {
  433. $responseDataMap[$respQ['id']] = $respQ;
  434. }
  435. // 合并题库数据
  436. $questionsData = array_map(function($q) use ($responseDataMap) {
  437. if (isset($responseDataMap[$q['id']])) {
  438. $apiData = $responseDataMap[$q['id']];
  439. $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  440. // 分离题干和选项
  441. list($stem, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  442. $q['stem'] = $stem;
  443. $q['content'] = $stem; // 同时设置content字段
  444. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  445. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  446. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  447. // 优先使用API选项,支持多种数据格式
  448. $apiOptions = $apiData['options'] ?? null;
  449. if (!empty($apiOptions)) {
  450. // 标准化options格式为数组值列表
  451. $q['options'] = $this->normalizeOptions($apiOptions);
  452. Log::debug('使用标准化API options', [
  453. 'question_id' => $q['id'],
  454. 'raw_options' => $apiOptions,
  455. 'normalized_options' => $q['options']
  456. ]);
  457. } else {
  458. // 备选:从题干中提取的选项
  459. $q['options'] = $extractedOptions;
  460. Log::debug('使用提取的options', [
  461. 'question_id' => $q['id'],
  462. 'extracted_options' => $extractedOptions
  463. ]);
  464. }
  465. }
  466. return $q;
  467. }, $questionsData);
  468. }
  469. }
  470. if (count($questionsData) > $totalQuestions) {
  471. Log::info('PDF预览时发现题目过多,进行筛选', [
  472. 'paper_id' => $paper_id,
  473. 'cached_count' => count($questionsData),
  474. 'required_count' => $totalQuestions
  475. ]);
  476. $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
  477. Log::info('筛选后题目数据', [
  478. 'paper_id' => $paper_id,
  479. 'filtered_count' => count($questionsData),
  480. 'filtered_types' => array_column($questionsData, 'question_type')
  481. ]);
  482. }
  483. } else {
  484. abort(404, '试卷未找到');
  485. }
  486. } else {
  487. // 获取试卷题目
  488. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
  489. ->orderBy('question_number')
  490. ->get();
  491. Log::info('从数据库获取题目', [
  492. 'paper_id' => $paper_id,
  493. 'question_count' => $paperQuestions->count()
  494. ]);
  495. // 将 paper_questions 表的数据转换为题库格式
  496. $questionsData = [];
  497. foreach ($paperQuestions as $pq) {
  498. $questionsData[] = [
  499. 'id' => $pq->question_bank_id,
  500. 'question_number' => $pq->question_number, // 【关键】保留题目序号,用于排序
  501. 'kp_code' => $pq->knowledge_point,
  502. 'question_type' => $pq->question_type ?? 'answer', // 包含题目类型
  503. 'stem' => $pq->question_text ?? '题目内容缺失', // 如果有存储题目文本
  504. 'solution' => $pq->solution ?? '', // 保存解题思路!
  505. 'answer' => $pq->correct_answer ?? '', // 保存正确答案
  506. 'difficulty' => $pq->difficulty ?? 0.5,
  507. 'score' => $pq->score ?? 5, // 包含已计算的分值
  508. 'tags' => '',
  509. 'content' => $pq->question_text ?? '',
  510. ];
  511. }
  512. Log::info('paper_questions表原始数据', [
  513. 'paper_id' => $paper_id,
  514. 'sample_questions' => array_slice($questionsData, 0, 3),
  515. 'all_types' => array_column($questionsData, 'question_type')
  516. ]);
  517. // 如果需要完整题目详情(stem等),可以从题库获取
  518. // 但要严格限制只获取这8道题
  519. if (!empty($questionsData)) {
  520. $questionBankService = app(QuestionBankService::class);
  521. $questionIds = array_column($questionsData, 'id');
  522. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  523. $responseData = $questionsResponse['data'] ?? [];
  524. // 确保只返回请求的ID对应的题目,并保留数据库中的 question_type
  525. if (!empty($responseData)) {
  526. // 创建题库返回数据的映射
  527. $responseDataMap = [];
  528. foreach ($responseData as $respQ) {
  529. $responseDataMap[$respQ['id']] = $respQ;
  530. }
  531. // 遍历所有数据库中的题目,合并题库返回的数据
  532. $questionsData = array_map(function($q) use ($responseDataMap, $paperQuestions) {
  533. // 从题库API获取的详细数据(如果有)
  534. if (isset($responseDataMap[$q['id']])) {
  535. $apiData = $responseDataMap[$q['id']];
  536. $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
  537. // 分离题干和选项
  538. list($stem, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  539. // 合并数据,优先使用题库API的 stem、answer、solution、options
  540. $q['stem'] = $stem;
  541. $q['content'] = $stem; // 同时设置content字段
  542. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  543. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  544. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  545. // 优先使用API选项,支持多种数据格式
  546. $apiOptions = $apiData['options'] ?? null;
  547. if (!empty($apiOptions)) {
  548. // 标准化options格式为数组值列表
  549. $q['options'] = $this->normalizeOptions($apiOptions);
  550. Log::debug('使用标准化API options', [
  551. 'question_id' => $q['id'],
  552. 'raw_options' => $apiOptions,
  553. 'normalized_options' => $q['options']
  554. ]);
  555. } else {
  556. // 备选:从题干中提取的选项
  557. $q['options'] = $extractedOptions;
  558. Log::debug('使用提取的options', [
  559. 'question_id' => $q['id'],
  560. 'extracted_options' => $extractedOptions
  561. ]);
  562. }
  563. }
  564. // 从数据库 paper_questions 表中获取 question_type(已在前面设置,这里确保有值)
  565. if (!isset($q['question_type']) || empty($q['question_type'])) {
  566. $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
  567. if ($dbQuestion && $dbQuestion->question_type) {
  568. $q['question_type'] = $dbQuestion->question_type;
  569. }
  570. }
  571. return $q;
  572. }, $questionsData);
  573. }
  574. }
  575. }
  576. // 按题型分类(使用标准的中学数学试卷格式)
  577. $questions = ['choice' => [], 'fill' => [], 'answer' => []];
  578. foreach ($questionsData as $q) {
  579. // 题库API返回的是 stem 字段,不是 content
  580. $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
  581. // 分离题干和选项
  582. list($content, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  583. // 如果从题库API获取了选项,优先使用
  584. $options = $q['options'] ?? $extractedOptions;
  585. $answer = $q['answer'] ?? '';
  586. $solution = $q['solution'] ?? '';
  587. // 优先使用 question_type 字段,如果没有则根据内容智能判断
  588. $type = isset($q['question_type'])
  589. ? $this->normalizeQuestionTypeValue((string) $q['question_type'])
  590. : $this->determineQuestionType($q);
  591. // 详细调试:记录题目类型判断结果
  592. Log::info('题目类型判断', [
  593. 'question_id' => $q['id'] ?? '',
  594. 'has_question_type' => isset($q['question_type']),
  595. 'question_type_value' => $q['question_type'] ?? null,
  596. 'tags' => $q['tags'] ?? '',
  597. 'stem_length' => mb_strlen($content),
  598. 'stem_preview' => mb_substr($content, 0, 100),
  599. 'has_extracted_options' => !empty($extractedOptions),
  600. 'extracted_options_count' => count($extractedOptions),
  601. 'has_api_options' => isset($q['options']) && !empty($q['options']),
  602. 'api_options_count' => isset($q['options']) ? count($q['options']) : 0,
  603. 'final_options_count' => count($options),
  604. 'determined_type' => $type
  605. ]);
  606. if (!isset($questions[$type])) {
  607. $type = 'answer';
  608. }
  609. // 统一处理数学公式和选项数据
  610. $questionData = [
  611. 'id' => $q['id'] ?? $q['question_bank_id'] ?? null,
  612. 'question_number' => $q['question_number'] ?? null, // 【关键】保留题目序号
  613. 'content' => $content,
  614. 'stem' => $content, // 同时提供stem字段
  615. 'answer' => $answer,
  616. 'solution' => $solution,
  617. 'difficulty' => $q['difficulty'] ?? 0.5,
  618. 'kp_code' => $q['kp_code'] ?? '',
  619. 'tags' => $q['tags'] ?? '',
  620. 'options' => $options, // 使用分离后的选项
  621. 'score' => $q['score'] ?? $this->getQuestionScore($type),
  622. 'question_type' => $type,
  623. ];
  624. // 统一处理数学公式 - 标记已处理,避免模板中重复处理
  625. $questionData = \App\Services\MathFormulaProcessor::processQuestionData($questionData);
  626. $questionData['math_processed'] = true; // 添加标记
  627. $qData = (object) $questionData;
  628. $questions[$type][] = $qData;
  629. }
  630. // 【关键】确保每个题型内的题目按 question_number 排序
  631. foreach (['choice', 'fill', 'answer'] as $type) {
  632. if (!empty($questions[$type])) {
  633. usort($questions[$type], function($a, $b) {
  634. $aNum = $a->question_number ?? 0;
  635. $bNum = $b->question_number ?? 0;
  636. return $aNum <=> $bNum;
  637. });
  638. }
  639. }
  640. // 调试:记录最终分类结果
  641. Log::info('最终分类结果', [
  642. 'paper_id' => $paper_id,
  643. 'choice_count' => count($questions['choice']),
  644. 'fill_count' => count($questions['fill']),
  645. 'answer_count' => count($questions['answer']),
  646. 'total' => count($questions['choice']) + count($questions['fill']) + count($questions['answer'])
  647. ]);
  648. // 渲染视图
  649. $viewName = $includeAnswer ? 'pdf.exam-grading' : 'pdf.exam-paper';
  650. return view($viewName, [
  651. 'paper' => $paper,
  652. 'questions' => $questions,
  653. 'student' => $this->getStudentInfo($paper->student_id),
  654. 'teacher' => $this->getTeacherInfo($paper->teacher_id),
  655. 'includeAnswer' => $includeAnswer
  656. ]);
  657. }
  658. /**
  659. * 判卷视图:题目前带方框,题后附"正确答案+解题思路"
  660. */
  661. public function showGrading(Request $request, $paper_id)
  662. {
  663. // 复用现有逻辑获取题目分类
  664. $includeAnswer = true;
  665. // 直接调用 show 的前置逻辑(简化复用)
  666. $request->merge(['answer' => 'true']);
  667. // 复用 show() 内逻辑获取 questions/paper
  668. // 为避免重复代码,简单调用 showData 方法(拆分为私有方法?暂直接重用现有方法流程)
  669. // 这里直接复制 show 的主体以保持兼容
  670. // 使用 Eloquent 模型获取试卷数据
  671. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  672. if (!$paper) {
  673. $cached = Cache::get('generated_exam_' . $paper_id);
  674. if (!$cached) {
  675. abort(404, '试卷未找到');
  676. }
  677. $paper = (object)[
  678. 'paper_id' => $paper_id,
  679. 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
  680. 'student_id' => $cached['student_id'] ?? null,
  681. 'teacher_id' => $cached['teacher_id'] ?? null,
  682. ];
  683. $questionsData = $cached['questions'] ?? [];
  684. $totalQuestions = $cached['total_questions'] ?? count($questionsData);
  685. $difficultyCategory = $cached['difficulty_category'] ?? '中等';
  686. if (!empty($questionsData)) {
  687. $questionBankService = app(QuestionBankService::class);
  688. $questionIds = array_column($questionsData, 'id');
  689. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  690. $responseData = $questionsResponse['data'] ?? [];
  691. if (!empty($responseData)) {
  692. $responseDataMap = [];
  693. foreach ($responseData as $respQ) {
  694. $responseDataMap[$respQ['id']] = $respQ;
  695. }
  696. $questionsData = array_map(function($q) use ($responseDataMap) {
  697. if (isset($responseDataMap[$q['id']])) {
  698. $apiData = $responseDataMap[$q['id']];
  699. $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  700. list($stem, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  701. $q['stem'] = $stem;
  702. $q['content'] = $stem; // 同时设置content字段
  703. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  704. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  705. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  706. // 优先使用API选项,支持多种数据格式
  707. $apiOptions = $apiData['options'] ?? null;
  708. if (!empty($apiOptions)) {
  709. // 标准化options格式为数组值列表
  710. $q['options'] = $this->normalizeOptions($apiOptions);
  711. Log::debug('使用标准化API options', [
  712. 'question_id' => $q['id'],
  713. 'raw_options' => $apiOptions,
  714. 'normalized_options' => $q['options']
  715. ]);
  716. } else {
  717. // 备选:从题干中提取的选项
  718. $q['options'] = $extractedOptions;
  719. Log::debug('使用提取的options', [
  720. 'question_id' => $q['id'],
  721. 'extracted_options' => $extractedOptions
  722. ]);
  723. }
  724. }
  725. return $q;
  726. }, $questionsData);
  727. }
  728. }
  729. if (count($questionsData) > $totalQuestions) {
  730. $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
  731. }
  732. } else {
  733. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
  734. ->orderBy('question_number')
  735. ->get();
  736. $questionsData = [];
  737. foreach ($paperQuestions as $pq) {
  738. $questionsData[] = [
  739. 'id' => $pq->question_bank_id,
  740. 'question_number' => $pq->question_number, // 【关键】保留题目序号
  741. 'kp_code' => $pq->knowledge_point,
  742. 'question_type' => $pq->question_type ?? 'answer',
  743. 'stem' => $pq->question_text ?? '题目内容缺失',
  744. 'solution' => $pq->solution ?? '', // 保存解题思路!
  745. 'answer' => $pq->correct_answer ?? '', // 保存正确答案
  746. 'difficulty' => $pq->difficulty ?? 0.5,
  747. 'score' => $pq->score ?? 5,
  748. 'tags' => '',
  749. 'content' => $pq->question_text ?? '',
  750. ];
  751. }
  752. if (!empty($questionsData)) {
  753. $questionBankService = app(QuestionBankService::class);
  754. $questionIds = array_column($questionsData, 'id');
  755. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  756. $responseData = $questionsResponse['data'] ?? [];
  757. if (!empty($responseData)) {
  758. $responseDataMap = [];
  759. foreach ($responseData as $respQ) {
  760. $responseDataMap[$respQ['id']] = $respQ;
  761. }
  762. $questionsData = array_map(function($q) use ($responseDataMap, $paperQuestions) {
  763. if (isset($responseDataMap[$q['id']])) {
  764. $apiData = $responseDataMap[$q['id']];
  765. $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
  766. list($stem, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  767. $q['stem'] = $stem;
  768. $q['content'] = $stem; // 同时设置content字段
  769. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  770. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  771. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  772. // 优先使用API选项,支持多种数据格式
  773. $apiOptions = $apiData['options'] ?? null;
  774. if (!empty($apiOptions)) {
  775. // 标准化options格式为数组值列表
  776. $q['options'] = $this->normalizeOptions($apiOptions);
  777. Log::debug('使用标准化API options', [
  778. 'question_id' => $q['id'],
  779. 'raw_options' => $apiOptions,
  780. 'normalized_options' => $q['options']
  781. ]);
  782. } else {
  783. // 备选:从题干中提取的选项
  784. $q['options'] = $extractedOptions;
  785. Log::debug('使用提取的options', [
  786. 'question_id' => $q['id'],
  787. 'extracted_options' => $extractedOptions
  788. ]);
  789. }
  790. }
  791. if (!isset($q['question_type']) || empty($q['question_type'])) {
  792. $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
  793. if ($dbQuestion && $dbQuestion->question_type) {
  794. $q['question_type'] = $dbQuestion->question_type;
  795. }
  796. }
  797. return $q;
  798. }, $questionsData);
  799. }
  800. }
  801. }
  802. $questions = ['choice' => [], 'fill' => [], 'answer' => []];
  803. foreach ($questionsData as $q) {
  804. $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
  805. list($content, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  806. $options = $q['options'] ?? $extractedOptions;
  807. $answer = $q['answer'] ?? '';
  808. $solution = $q['solution'] ?? '';
  809. $type = isset($q['question_type'])
  810. ? $this->normalizeQuestionTypeValue((string) $q['question_type'])
  811. : $this->determineQuestionType($q);
  812. if (!isset($questions[$type])) {
  813. $type = 'answer';
  814. }
  815. // 统一处理数学公式和选项数据
  816. $questionData = [
  817. 'id' => $q['id'] ?? $q['question_bank_id'] ?? null,
  818. 'question_number' => $q['question_number'] ?? null, // 【关键】保留题目序号
  819. 'content' => $content,
  820. 'stem' => $content, // 同时提供stem字段
  821. 'answer' => $answer,
  822. 'solution' => $solution,
  823. 'difficulty' => $q['difficulty'] ?? 0.5,
  824. 'kp_code' => $q['kp_code'] ?? '',
  825. 'tags' => $q['tags'] ?? '',
  826. 'options' => $options,
  827. 'score' => $q['score'] ?? $this->getQuestionScore($type),
  828. 'question_type' => $type,
  829. ];
  830. // 统一处理数学公式 - 标记已处理,避免模板中重复处理
  831. $questionData = \App\Services\MathFormulaProcessor::processQuestionData($questionData);
  832. $questionData['math_processed'] = true; // 添加标记
  833. $qData = (object) $questionData;
  834. $questions[$type][] = $qData;
  835. }
  836. // 【关键】确保每个题型内的题目按 question_number 排序
  837. foreach (['choice', 'fill', 'answer'] as $type) {
  838. if (!empty($questions[$type])) {
  839. usort($questions[$type], function($a, $b) {
  840. $aNum = $a->question_number ?? 0;
  841. $bNum = $b->question_number ?? 0;
  842. return $aNum <=> $bNum;
  843. });
  844. }
  845. }
  846. return view('pdf.exam-grading', [
  847. 'paper' => $paper,
  848. 'questions' => $questions,
  849. 'student' => $this->getStudentInfo($paper->student_id),
  850. 'teacher' => $this->getTeacherInfo($paper->teacher_id),
  851. 'includeAnswer' => true,
  852. ]);
  853. }
  854. }