ExamPdfController.php 32 KB

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