ExamPdfController.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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. private function determineQuestionType(array $question): string
  14. {
  15. // 优先根据题目内容判断(而不是数据库字段)
  16. $stem = $question['stem'] ?? $question['content'] ?? '';
  17. $tags = $question['tags'] ?? '';
  18. $skills = $question['skills'] ?? [];
  19. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  20. if (is_string($stem)) {
  21. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  22. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  23. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  24. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  25. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  26. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  27. // 至少有2个选项就认为是选择题(降低阈值)
  28. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  29. if ($optionCount >= 2) {
  30. return 'choice';
  31. }
  32. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  33. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  34. return 'choice';
  35. }
  36. }
  37. // 2. 根据技能点判断
  38. if (is_array($skills)) {
  39. $skillsStr = implode(',', $skills);
  40. if (strpos($skillsStr, '选择题') !== false) return 'choice';
  41. if (strpos($skillsStr, '填空题') !== false) return 'fill';
  42. if (strpos($skillsStr, '解答题') !== false) return 'answer';
  43. }
  44. // 3. 根据题目已有类型字段判断(作为后备)
  45. if (!empty($question['question_type'])) {
  46. $type = strtolower(trim($question['question_type']));
  47. if (in_array($type, ['choice', '选择题', 'choice question'])) return 'choice';
  48. if (in_array($type, ['fill', '填空题', 'fill in the blank'])) return 'fill';
  49. if (in_array($type, ['answer', '解答题', 'calculation', '简答题'])) return 'answer';
  50. }
  51. if (!empty($question['type'])) {
  52. $type = strtolower(trim($question['type']));
  53. if (in_array($type, ['choice', '选择题', 'choice question'])) return 'choice';
  54. if (in_array($type, ['fill', '填空题', 'fill in the blank'])) return 'fill';
  55. if (in_array($type, ['answer', '解答题', 'calculation', '简答题'])) return 'answer';
  56. }
  57. // 4. 根据标签判断
  58. if (is_string($tags)) {
  59. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  60. return 'choice';
  61. }
  62. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  63. return 'fill';
  64. }
  65. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  66. return 'answer';
  67. }
  68. }
  69. // 5. 填空题特征:连续下划线或明显的填空括号
  70. if (is_string($stem)) {
  71. // 检查填空题特征:连续下划线
  72. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  73. return 'fill';
  74. }
  75. // 空括号填空
  76. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  77. return 'fill';
  78. }
  79. }
  80. // 6. 根据题干内容关键词判断
  81. if (is_string($stem)) {
  82. // 有证明、解答、计算、求证等关键词的是解答题
  83. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  84. return 'answer';
  85. }
  86. }
  87. // 默认是解答题(更安全的默认值)
  88. return 'answer';
  89. }
  90. /**
  91. * 从题目内容中提取选项
  92. */
  93. private function extractOptions(string $content): array
  94. {
  95. $options = [];
  96. // 1. 尝试匹配多种格式的选项:A. / A、/ A: / A.(中文句点)/ A.(无空格)
  97. // 支持格式:A.-1 / A. -1 / A、-1 / A:-1
  98. $pattern = '/([A-D])[\.、:.:]\s*(.+?)(?=\s*[A-D][\.、:.:]|$)/su';
  99. if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
  100. foreach ($matches as $match) {
  101. $optionText = trim($match[2]);
  102. // 移除末尾的换行和空白
  103. $optionText = preg_replace('/\s+$/', '', $optionText);
  104. // 清理 LaTeX 格式但保留内容
  105. $optionText = preg_replace('/^\$\$\s*/', '', $optionText);
  106. $optionText = preg_replace('/\s*\$\$$/', '', $optionText);
  107. if (!empty($optionText)) {
  108. $options[] = $optionText;
  109. }
  110. }
  111. }
  112. // 2. 如果上面没提取到,尝试按换行分割
  113. if (empty($options)) {
  114. $lines = preg_split('/[\r\n]+/', $content);
  115. foreach ($lines as $line) {
  116. $line = trim($line);
  117. if (preg_match('/^([A-D])[\.、:.:]\s*(.+)$/u', $line, $match)) {
  118. $optionText = trim($match[2]);
  119. if (!empty($optionText)) {
  120. $options[] = $optionText;
  121. }
  122. }
  123. }
  124. }
  125. Log::debug('选项提取结果', [
  126. 'content_preview' => mb_substr($content, 0, 150),
  127. 'options_count' => count($options),
  128. 'options' => $options
  129. ]);
  130. return $options;
  131. }
  132. /**
  133. * 分离题干内容和选项
  134. */
  135. private function separateStemAndOptions(string $content): array
  136. {
  137. // 检测是否有选项(支持多种格式)
  138. $hasOptions = preg_match('/[A-D][\.、:.:]/u', $content);
  139. if (!$hasOptions) {
  140. return [$content, []];
  141. }
  142. // 提取选项
  143. $options = $this->extractOptions($content);
  144. // 如果提取到选项,分离题干
  145. if (!empty($options)) {
  146. // 找到第一个选项的位置,之前的内容是题干
  147. if (preg_match('/^(.+?)(?=[A-D][\.、:.:])/su', $content, $match)) {
  148. $stem = trim($match[1]);
  149. } else {
  150. // 如果正则失败,尝试按位置分割
  151. $stem = $content;
  152. foreach (['A.', 'A、', 'A:', 'A.', 'A:'] as $marker) {
  153. $pos = mb_strpos($content, $marker);
  154. if ($pos !== false && $pos > 0) {
  155. $stem = trim(mb_substr($content, 0, $pos));
  156. break;
  157. }
  158. }
  159. }
  160. // 移除末尾的括号或空白
  161. $stem = preg_replace('/()\s*$/', '', $stem);
  162. $stem = trim($stem);
  163. return [$stem, $options];
  164. }
  165. return [$content, []];
  166. }
  167. /**
  168. * 根据题型获取默认分数
  169. */
  170. private function getQuestionScore(string $type): int
  171. {
  172. switch ($type) {
  173. case 'choice':
  174. return 5; // 选择题5分
  175. case 'fill':
  176. return 5; // 填空题5分
  177. case 'answer':
  178. return 10; // 解答题10分
  179. default:
  180. return 5;
  181. }
  182. }
  183. /**
  184. * 获取学生信息
  185. */
  186. private function getStudentInfo(?string $studentId): array
  187. {
  188. if (!$studentId) {
  189. return [
  190. 'name' => '未知学生',
  191. 'grade' => '未知年级',
  192. 'class' => '未知班级'
  193. ];
  194. }
  195. try {
  196. $student = DB::table('students')
  197. ->where('student_id', $studentId)
  198. ->first();
  199. if ($student) {
  200. return [
  201. 'name' => $student->name ?? $studentId,
  202. 'grade' => $student->grade ?? '未知',
  203. 'class' => $student->class ?? '未知'
  204. ];
  205. }
  206. } catch (\Exception $e) {
  207. Log::warning('获取学生信息失败', [
  208. 'student_id' => $studentId,
  209. 'error' => $e->getMessage()
  210. ]);
  211. }
  212. return [
  213. 'name' => $studentId,
  214. 'grade' => '未知',
  215. 'class' => '未知'
  216. ];
  217. }
  218. /**
  219. * 为 PDF 预览筛选题目(简化版)
  220. */
  221. private function selectBestQuestionsForPdf(array $questions, int $targetCount, string $difficultyCategory): array
  222. {
  223. if (count($questions) <= $targetCount) {
  224. return $questions;
  225. }
  226. // 1. 按题型分类题目
  227. $categorizedQuestions = [
  228. 'choice' => [],
  229. 'fill' => [],
  230. 'answer' => [],
  231. ];
  232. foreach ($questions as $question) {
  233. $type = $this->determineQuestionType($question);
  234. if (!isset($categorizedQuestions[$type])) {
  235. $type = 'answer';
  236. }
  237. $categorizedQuestions[$type][] = $question;
  238. }
  239. // 2. 默认题型配比
  240. $typeRatio = [
  241. '选择题' => 50, // 50%
  242. '填空题' => 30, // 30%
  243. '解答题' => 20, // 20%
  244. ];
  245. // 3. 根据配比选择题目
  246. $selectedQuestions = [];
  247. foreach ($typeRatio as $type => $ratio) {
  248. $typeKey = $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer');
  249. $countForType = floor($targetCount * $ratio / 100);
  250. if ($countForType > 0 && !empty($categorizedQuestions[$typeKey])) {
  251. $availableCount = count($categorizedQuestions[$typeKey]);
  252. $takeCount = min($countForType, $availableCount, $targetCount - count($selectedQuestions));
  253. // 随机选择题目
  254. $keys = array_keys($categorizedQuestions[$typeKey]);
  255. shuffle($keys);
  256. $selectedKeys = array_slice($keys, 0, $takeCount);
  257. foreach ($selectedKeys as $key) {
  258. $selectedQuestions[] = $categorizedQuestions[$typeKey][$key];
  259. }
  260. }
  261. }
  262. // 4. 如果数量不足,随机补充
  263. while (count($selectedQuestions) < $targetCount) {
  264. $randomQuestion = $questions[array_rand($questions)];
  265. if (!in_array($randomQuestion, $selectedQuestions)) {
  266. $selectedQuestions[] = $randomQuestion;
  267. }
  268. }
  269. // 5. 限制数量并打乱
  270. shuffle($selectedQuestions);
  271. return array_slice($selectedQuestions, 0, $targetCount);
  272. }
  273. /**
  274. * 获取教师信息
  275. */
  276. private function getTeacherInfo(?string $teacherId): array
  277. {
  278. if (!$teacherId) {
  279. return [
  280. 'name' => '未知教师'
  281. ];
  282. }
  283. try {
  284. $teacher = DB::table('teachers')
  285. ->where('teacher_id', $teacherId)
  286. ->first();
  287. if ($teacher) {
  288. return [
  289. 'name' => $teacher->name ?? $teacherId
  290. ];
  291. }
  292. } catch (\Exception $e) {
  293. Log::warning('获取教师信息失败', [
  294. 'teacher_id' => $teacherId,
  295. 'error' => $e->getMessage()
  296. ]);
  297. }
  298. return [
  299. 'name' => $teacherId
  300. ];
  301. }
  302. public function show(Request $request, $paper_id)
  303. {
  304. // 获取是否显示答案的参数,默认为true
  305. $includeAnswer = $request->query('answer', 'true') !== 'false';
  306. // 使用 Eloquent 模型获取试卷数据
  307. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  308. if (!$paper) {
  309. // 尝试从缓存中获取生成的试卷数据(用于 demo 试卷)
  310. $cached = Cache::get('generated_exam_' . $paper_id);
  311. if ($cached) {
  312. Log::info('从缓存获取试卷数据', [
  313. 'paper_id' => $paper_id,
  314. 'cached_count' => count($cached['questions'] ?? []),
  315. 'cached_question_types' => array_column($cached['questions'] ?? [], 'question_type')
  316. ]);
  317. // 构造临时 Paper 对象
  318. $paper = (object)[
  319. 'paper_id' => $paper_id,
  320. 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
  321. 'student_id' => $cached['student_id'] ?? null,
  322. 'teacher_id' => $cached['teacher_id'] ?? null,
  323. ];
  324. // 对于 demo 试卷,需要检查题目数量并限制为用户要求的数量
  325. $questionsData = $cached['questions'] ?? [];
  326. $totalQuestions = $cached['total_questions'] ?? count($questionsData);
  327. $difficultyCategory = $cached['difficulty_category'] ?? '中等';
  328. // 为 demo 试卷获取完整的题目详情(包括选项)
  329. if (!empty($questionsData)) {
  330. $questionBankService = app(QuestionBankService::class);
  331. $questionIds = array_column($questionsData, 'id');
  332. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  333. $responseData = $questionsResponse['data'] ?? [];
  334. if (!empty($responseData)) {
  335. $responseDataMap = [];
  336. foreach ($responseData as $respQ) {
  337. $responseDataMap[$respQ['id']] = $respQ;
  338. }
  339. // 合并题库数据
  340. $questionsData = array_map(function($q) use ($responseDataMap) {
  341. if (isset($responseDataMap[$q['id']])) {
  342. $apiData = $responseDataMap[$q['id']];
  343. $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  344. // 分离题干和选项
  345. list($stem, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  346. $q['stem'] = $stem;
  347. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  348. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  349. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  350. $q['options'] = $apiData['options'] ?? $extractedOptions; // 优先使用API选项,备选提取的选项
  351. }
  352. return $q;
  353. }, $questionsData);
  354. }
  355. }
  356. if (count($questionsData) > $totalQuestions) {
  357. Log::info('PDF预览时发现题目过多,进行筛选', [
  358. 'paper_id' => $paper_id,
  359. 'cached_count' => count($questionsData),
  360. 'required_count' => $totalQuestions
  361. ]);
  362. $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
  363. Log::info('筛选后题目数据', [
  364. 'paper_id' => $paper_id,
  365. 'filtered_count' => count($questionsData),
  366. 'filtered_types' => array_column($questionsData, 'question_type')
  367. ]);
  368. }
  369. } else {
  370. abort(404, '试卷未找到');
  371. }
  372. } else {
  373. // 获取试卷题目
  374. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
  375. ->orderBy('question_number')
  376. ->get();
  377. Log::info('从数据库获取题目', [
  378. 'paper_id' => $paper_id,
  379. 'question_count' => $paperQuestions->count()
  380. ]);
  381. // 将 paper_questions 表的数据转换为题库格式
  382. $questionsData = [];
  383. foreach ($paperQuestions as $pq) {
  384. $questionsData[] = [
  385. 'id' => $pq->question_bank_id,
  386. 'kp_code' => $pq->knowledge_point,
  387. 'question_type' => $pq->question_type ?? 'answer', // 包含题目类型
  388. 'stem' => $pq->question_text ?? '题目内容缺失', // 如果有存储题目文本
  389. 'solution' => $pq->solution ?? '', // 保存解题思路!
  390. 'answer' => $pq->correct_answer ?? '', // 保存正确答案
  391. 'difficulty' => $pq->difficulty ?? 0.5,
  392. 'score' => $pq->score ?? 5, // 包含已计算的分值
  393. 'tags' => '',
  394. 'content' => $pq->question_text ?? '',
  395. ];
  396. }
  397. Log::info('paper_questions表原始数据', [
  398. 'paper_id' => $paper_id,
  399. 'sample_questions' => array_slice($questionsData, 0, 3),
  400. 'all_types' => array_column($questionsData, 'question_type')
  401. ]);
  402. // 如果需要完整题目详情(stem等),可以从题库获取
  403. // 但要严格限制只获取这8道题
  404. if (!empty($questionsData)) {
  405. $questionBankService = app(QuestionBankService::class);
  406. $questionIds = array_column($questionsData, 'id');
  407. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  408. $responseData = $questionsResponse['data'] ?? [];
  409. // 确保只返回请求的ID对应的题目,并保留数据库中的 question_type
  410. if (!empty($responseData)) {
  411. // 创建题库返回数据的映射
  412. $responseDataMap = [];
  413. foreach ($responseData as $respQ) {
  414. $responseDataMap[$respQ['id']] = $respQ;
  415. }
  416. // 遍历所有数据库中的题目,合并题库返回的数据
  417. $questionsData = array_map(function($q) use ($responseDataMap, $paperQuestions) {
  418. // 从题库API获取的详细数据(如果有)
  419. if (isset($responseDataMap[$q['id']])) {
  420. $apiData = $responseDataMap[$q['id']];
  421. $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
  422. // 分离题干和选项
  423. list($stem, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  424. // 合并数据,优先使用题库API的 stem、answer、solution、options
  425. $q['stem'] = $stem;
  426. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  427. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  428. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  429. $q['options'] = $apiData['options'] ?? $extractedOptions; // 优先使用API选项,备选提取的选项
  430. }
  431. // 从数据库 paper_questions 表中获取 question_type(已在前面设置,这里确保有值)
  432. if (!isset($q['question_type']) || empty($q['question_type'])) {
  433. $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
  434. if ($dbQuestion && $dbQuestion->question_type) {
  435. $q['question_type'] = $dbQuestion->question_type;
  436. }
  437. }
  438. return $q;
  439. }, $questionsData);
  440. }
  441. }
  442. }
  443. // 按题型分类(使用标准的中学数学试卷格式)
  444. $questions = ['choice' => [], 'fill' => [], 'answer' => []];
  445. foreach ($questionsData as $q) {
  446. // 题库API返回的是 stem 字段,不是 content
  447. $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
  448. // 分离题干和选项
  449. list($content, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  450. // 如果从题库API获取了选项,优先使用
  451. $options = $q['options'] ?? $extractedOptions;
  452. $answer = $q['answer'] ?? '';
  453. $solution = $q['solution'] ?? '';
  454. // 优先使用 question_type 字段,如果没有则根据内容智能判断
  455. $type = $q['question_type'] ?? $this->determineQuestionType($q);
  456. // 详细调试:记录题目类型判断结果
  457. Log::info('题目类型判断', [
  458. 'question_id' => $q['id'] ?? '',
  459. 'has_question_type' => isset($q['question_type']),
  460. 'question_type_value' => $q['question_type'] ?? null,
  461. 'tags' => $q['tags'] ?? '',
  462. 'stem_length' => mb_strlen($content),
  463. 'stem_preview' => mb_substr($content, 0, 100),
  464. 'has_extracted_options' => !empty($extractedOptions),
  465. 'extracted_options_count' => count($extractedOptions),
  466. 'has_api_options' => isset($q['options']) && !empty($q['options']),
  467. 'api_options_count' => isset($q['options']) ? count($q['options']) : 0,
  468. 'final_options_count' => count($options),
  469. 'determined_type' => $type
  470. ]);
  471. if (!isset($questions[$type])) {
  472. $type = 'answer';
  473. }
  474. $qData = (object)[
  475. 'id' => $q['id'] ?? $q['question_bank_id'] ?? null,
  476. 'content' => $content,
  477. 'answer' => $answer,
  478. 'solution' => $solution,
  479. 'difficulty' => $q['difficulty'] ?? 0.5,
  480. 'kp_code' => $q['kp_code'] ?? '',
  481. 'tags' => $q['tags'] ?? '',
  482. 'options' => $options, // 使用分离后的选项
  483. 'score' => $q['score'] ?? $this->getQuestionScore($type), // 优先使用生成时分配的分数
  484. ];
  485. $questions[$type][] = $qData;
  486. }
  487. // 调试:记录最终分类结果
  488. Log::info('最终分类结果', [
  489. 'paper_id' => $paper_id,
  490. 'choice_count' => count($questions['choice']),
  491. 'fill_count' => count($questions['fill']),
  492. 'answer_count' => count($questions['answer']),
  493. 'total' => count($questions['choice']) + count($questions['fill']) + count($questions['answer'])
  494. ]);
  495. // 渲染视图
  496. return view('pdf.exam-paper', [
  497. 'paper' => $paper,
  498. 'questions' => $questions,
  499. 'student' => $this->getStudentInfo($paper->student_id),
  500. 'teacher' => $this->getTeacherInfo($paper->teacher_id),
  501. 'includeAnswer' => $includeAnswer
  502. ]);
  503. }
  504. /**
  505. * 判卷视图:题目前带方框,题后附“正确答案+解题思路”
  506. */
  507. public function showGrading(Request $request, $paper_id)
  508. {
  509. // 复用现有逻辑获取题目分类
  510. $includeAnswer = true;
  511. // 直接调用 show 的前置逻辑(简化复用)
  512. $request->merge(['answer' => 'true']);
  513. // 复用 show() 内逻辑获取 questions/paper
  514. // 为避免重复代码,简单调用 showData 方法(拆分为私有方法?暂直接重用现有方法流程)
  515. // 这里直接复制 show 的主体以保持兼容
  516. // 使用 Eloquent 模型获取试卷数据
  517. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  518. if (!$paper) {
  519. $cached = Cache::get('generated_exam_' . $paper_id);
  520. if (!$cached) {
  521. abort(404, '试卷未找到');
  522. }
  523. $paper = (object)[
  524. 'paper_id' => $paper_id,
  525. 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
  526. 'student_id' => $cached['student_id'] ?? null,
  527. 'teacher_id' => $cached['teacher_id'] ?? null,
  528. ];
  529. $questionsData = $cached['questions'] ?? [];
  530. $totalQuestions = $cached['total_questions'] ?? count($questionsData);
  531. $difficultyCategory = $cached['difficulty_category'] ?? '中等';
  532. if (!empty($questionsData)) {
  533. $questionBankService = app(QuestionBankService::class);
  534. $questionIds = array_column($questionsData, 'id');
  535. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  536. $responseData = $questionsResponse['data'] ?? [];
  537. if (!empty($responseData)) {
  538. $responseDataMap = [];
  539. foreach ($responseData as $respQ) {
  540. $responseDataMap[$respQ['id']] = $respQ;
  541. }
  542. $questionsData = array_map(function($q) use ($responseDataMap) {
  543. if (isset($responseDataMap[$q['id']])) {
  544. $apiData = $responseDataMap[$q['id']];
  545. $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  546. list($stem, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  547. $q['stem'] = $stem;
  548. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  549. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  550. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  551. $q['options'] = $apiData['options'] ?? $extractedOptions;
  552. }
  553. return $q;
  554. }, $questionsData);
  555. }
  556. }
  557. if (count($questionsData) > $totalQuestions) {
  558. $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
  559. }
  560. } else {
  561. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
  562. ->orderBy('question_number')
  563. ->get();
  564. $questionsData = [];
  565. foreach ($paperQuestions as $pq) {
  566. $questionsData[] = [
  567. 'id' => $pq->question_bank_id,
  568. 'kp_code' => $pq->knowledge_point,
  569. 'question_type' => $pq->question_type ?? 'answer',
  570. 'stem' => $pq->question_text ?? '题目内容缺失',
  571. 'solution' => $pq->solution ?? '', // 保存解题思路!
  572. 'answer' => $pq->correct_answer ?? '', // 保存正确答案
  573. 'difficulty' => $pq->difficulty ?? 0.5,
  574. 'score' => $pq->score ?? 5,
  575. 'tags' => '',
  576. 'content' => $pq->question_text ?? '',
  577. ];
  578. }
  579. if (!empty($questionsData)) {
  580. $questionBankService = app(QuestionBankService::class);
  581. $questionIds = array_column($questionsData, 'id');
  582. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  583. $responseData = $questionsResponse['data'] ?? [];
  584. if (!empty($responseData)) {
  585. $responseDataMap = [];
  586. foreach ($responseData as $respQ) {
  587. $responseDataMap[$respQ['id']] = $respQ;
  588. }
  589. $questionsData = array_map(function($q) use ($responseDataMap, $paperQuestions) {
  590. if (isset($responseDataMap[$q['id']])) {
  591. $apiData = $responseDataMap[$q['id']];
  592. $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
  593. list($stem, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  594. $q['stem'] = $stem;
  595. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  596. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  597. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  598. $q['options'] = $apiData['options'] ?? $extractedOptions;
  599. }
  600. if (!isset($q['question_type']) || empty($q['question_type'])) {
  601. $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
  602. if ($dbQuestion && $dbQuestion->question_type) {
  603. $q['question_type'] = $dbQuestion->question_type;
  604. }
  605. }
  606. return $q;
  607. }, $questionsData);
  608. }
  609. }
  610. }
  611. $questions = ['choice' => [], 'fill' => [], 'answer' => []];
  612. foreach ($questionsData as $q) {
  613. $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
  614. list($content, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  615. $options = $q['options'] ?? $extractedOptions;
  616. $answer = $q['answer'] ?? '';
  617. $solution = $q['solution'] ?? '';
  618. $type = $q['question_type'] ?? $this->determineQuestionType($q);
  619. if (!isset($questions[$type])) {
  620. $type = 'answer';
  621. }
  622. $qData = (object)[
  623. 'id' => $q['id'] ?? $q['question_bank_id'] ?? null,
  624. 'content' => $content,
  625. 'answer' => $answer,
  626. 'solution' => $solution,
  627. 'difficulty' => $q['difficulty'] ?? 0.5,
  628. 'kp_code' => $q['kp_code'] ?? '',
  629. 'tags' => $q['tags'] ?? '',
  630. 'options' => $options,
  631. 'score' => $q['score'] ?? $this->getQuestionScore($type),
  632. ];
  633. $questions[$type][] = $qData;
  634. }
  635. return view('pdf.exam-grading', [
  636. 'paper' => $paper,
  637. 'questions' => $questions,
  638. 'student' => $this->getStudentInfo($paper->student_id),
  639. 'teacher' => $this->getTeacherInfo($paper->teacher_id),
  640. 'includeAnswer' => true,
  641. ]);
  642. }
  643. }