IntelligentExamGeneration.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  1. <?php
  2. namespace App\Filament\Pages;
  3. use App\Filament\Traits\HasUserRole;
  4. use App\Services\KnowledgeGraphService;
  5. use App\Services\LearningAnalyticsService;
  6. use App\Services\QuestionBankService;
  7. use App\Models\Student;
  8. use BackedEnum;
  9. use Filament\Notifications\Notification;
  10. use Filament\Pages\Page;
  11. use UnitEnum;
  12. use Livewire\Attributes\Computed;
  13. use Livewire\Attributes\On;
  14. use Livewire\Attributes\Reactive;
  15. use Livewire\Component;
  16. use Illuminate\Support\Facades\Cache; // Add Cache import
  17. class IntelligentExamGeneration extends Page
  18. {
  19. use HasUserRole;
  20. protected static ?string $title = '智能出卷';
  21. protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-document-duplicate';
  22. protected static ?string $navigationLabel = '智能出卷';
  23. protected static string|UnitEnum|null $navigationGroup = '操作';
  24. protected static ?int $navigationSort = 1;
  25. protected string $view = 'filament.pages.intelligent-exam-generation-simple';
  26. // 基本配置
  27. public ?string $paperName = '';
  28. public ?string $paperDescription = '';
  29. public ?string $difficultyCategory = '基础'; // 基础/进阶/竞赛
  30. public int $totalQuestions = 20;
  31. public int $totalScore = 100;
  32. // 知识点和技能点选择
  33. public array $selectedKpCodes = [];
  34. public array $selectedSkills = [];
  35. // 题型配比
  36. public array $questionTypeRatio = [
  37. '选择题' => 40, // 百分比
  38. '填空题' => 30,
  39. '解答题' => 30,
  40. ];
  41. // 难度配比
  42. public array $difficultyRatio = [
  43. '基础' => 50, // 百分比
  44. '中等' => 35,
  45. '拔高' => 15,
  46. ];
  47. // 教师和学生相关
  48. public ?string $selectedTeacherId = null;
  49. public ?string $selectedStudentId = null;
  50. public bool $filterByStudentWeakness = false;
  51. // 状态
  52. public bool $isGenerating = false;
  53. public array $generatedQuestions = [];
  54. public ?string $generatedPaperId = null;
  55. #[Computed]
  56. public function canGenerate(): bool
  57. {
  58. return !$this->isGenerating
  59. && $this->totalQuestions >= 6
  60. && !empty($this->selectedTeacherId)
  61. && !empty($this->selectedStudentId)
  62. && count($this->selectedKpCodes) > 0;
  63. }
  64. public function mount(): void
  65. {
  66. // 初始化用户角色检查
  67. $this->initializeUserRole();
  68. // 如果是老师,自动选择当前老师
  69. if ($this->isTeacher) {
  70. $teacherId = $this->getCurrentTeacherId();
  71. if ($teacherId) {
  72. $this->selectedTeacherId = $teacherId;
  73. }
  74. } else {
  75. // 管理员模式:从 URL 参数获取
  76. $this->selectedTeacherId = request()->query('teacher_id', $this->selectedTeacherId);
  77. }
  78. $this->selectedStudentId = request()->query('student_id', $this->selectedStudentId);
  79. // 如果只传了 student_id,补全 teacher_id 以便学生下拉加载
  80. if ($this->selectedStudentId && !$this->selectedTeacherId) {
  81. $student = Student::find($this->selectedStudentId);
  82. if ($student && $student->teacher_id) {
  83. $this->selectedTeacherId = (string) $student->teacher_id;
  84. }
  85. }
  86. }
  87. #[Computed(cache: false)]
  88. public function knowledgePoints(): array
  89. {
  90. try {
  91. $result = app(KnowledgeGraphService::class)->listKnowledgePoints(1, 1000);
  92. $knowledgePoints = $result['data'] ?? [];
  93. \Illuminate\Support\Facades\Log::info('知识点列表获取成功', [
  94. 'count' => count($knowledgePoints),
  95. 'first_item' => !empty($knowledgePoints) ? $knowledgePoints[0] : null
  96. ]);
  97. return $knowledgePoints;
  98. } catch (\Exception $e) {
  99. \Illuminate\Support\Facades\Log::error('获取知识点列表失败', [
  100. 'error' => $e->getMessage()
  101. ]);
  102. return [];
  103. }
  104. }
  105. #[Computed(cache: false)]
  106. public function skills(): array
  107. {
  108. if (empty($this->selectedKpCodes)) {
  109. return [];
  110. }
  111. $allSkills = [];
  112. foreach ($this->selectedKpCodes as $kpCode) {
  113. $kpSkills = app(KnowledgeGraphService::class)->getSkillsByKnowledgePoint($kpCode);
  114. $allSkills = array_merge($allSkills, $kpSkills);
  115. }
  116. return $allSkills;
  117. }
  118. /**
  119. * 获取当前选择的教师名称
  120. */
  121. public function getSelectedTeacherName(): string
  122. {
  123. if (empty($this->selectedTeacherId)) {
  124. return '未选择';
  125. }
  126. try {
  127. $teacher = \App\Models\Teacher::query()
  128. ->leftJoin('users as u', 'teachers.teacher_id', '=', 'u.user_id')
  129. ->where('teachers.teacher_id', $this->selectedTeacherId)
  130. ->select(
  131. 'teachers.name',
  132. 'teachers.subject',
  133. 'u.username'
  134. )
  135. ->first();
  136. if ($teacher) {
  137. $name = trim($teacher->name ?? $this->selectedTeacherId);
  138. $subject = $teacher->subject ? " ({$teacher->subject})" : '';
  139. $username = $teacher->username ? " [{$teacher->username}]" : '';
  140. return "{$name}{$subject}{$username}";
  141. }
  142. return $this->selectedTeacherId;
  143. } catch (\Exception $e) {
  144. return $this->selectedTeacherId;
  145. }
  146. }
  147. /**
  148. * 获取当前选择的学生名称
  149. */
  150. public function getSelectedStudentName(): string
  151. {
  152. if (empty($this->selectedStudentId) || empty($this->selectedTeacherId)) {
  153. return '未选择';
  154. }
  155. try {
  156. $student = \App\Models\Student::query()
  157. ->leftJoin('users as u', 'students.student_id', '=', 'u.user_id')
  158. ->where('students.student_id', $this->selectedStudentId)
  159. ->where('students.teacher_id', $this->selectedTeacherId)
  160. ->select(
  161. 'students.name',
  162. 'students.grade',
  163. 'students.class_name',
  164. 'u.username'
  165. )
  166. ->first();
  167. if ($student) {
  168. $name = trim($student->name ?? $this->selectedStudentId);
  169. $gradeClass = trim("{$student->grade} - {$student->class_name}");
  170. $username = $student->username ? " [{$student->username}]" : '';
  171. return "{$name} ({$gradeClass}){$username}";
  172. }
  173. return $this->selectedStudentId;
  174. } catch (\Exception $e) {
  175. return $this->selectedStudentId;
  176. }
  177. }
  178. #[Computed(cache: false)]
  179. public function teachers(): array
  180. {
  181. try {
  182. $query = \App\Models\Teacher::query()->from('teachers as t')
  183. ->leftJoin('users as u', 't.teacher_id', '=', 'u.user_id')
  184. ->select(
  185. 't.teacher_id',
  186. 't.name',
  187. 't.subject',
  188. 'u.username',
  189. 'u.email'
  190. );
  191. // 如果是老师,只返回自己
  192. if ($this->isTeacher) {
  193. $teacherId = $this->getCurrentTeacherId();
  194. if ($teacherId) {
  195. $query->where('t.teacher_id', $teacherId);
  196. }
  197. }
  198. $teachers = $query->orderBy('t.name')->get();
  199. // 如果有学生但没有对应的老师记录,添加一个"未知老师"条目
  200. $teacherIds = $teachers->pluck('teacher_id')->toArray();
  201. $missingTeacherIds = \App\Models\Student::query()->from('students as s')
  202. ->distinct()
  203. ->whereNotIn('s.teacher_id', $teacherIds)
  204. ->pluck('teacher_id')
  205. ->toArray();
  206. // 转换 Collection 为数组以便合并和排序
  207. $teachersArray = $teachers->all();
  208. if (!empty($missingTeacherIds)) {
  209. foreach ($missingTeacherIds as $missingId) {
  210. $teachersArray[] = (object) [
  211. 'teacher_id' => $missingId,
  212. 'name' => '未知老师 (' . $missingId . ')',
  213. 'subject' => '未知',
  214. 'username' => null,
  215. 'email' => null
  216. ];
  217. }
  218. // 重新排序
  219. usort($teachersArray, function($a, $b) {
  220. return strcmp($a->name, $b->name);
  221. });
  222. return $teachersArray;
  223. }
  224. return $teachersArray;
  225. } catch (\Exception $e) {
  226. \Illuminate\Support\Facades\Log::error('加载老师列表失败', [
  227. 'error' => $e->getMessage()
  228. ]);
  229. return [];
  230. }
  231. }
  232. #[Computed(cache: false)]
  233. public function students(): array
  234. {
  235. if (empty($this->selectedTeacherId)) {
  236. return [];
  237. }
  238. try {
  239. $students = \App\Models\Student::query()->from('students as s')
  240. ->leftJoin('users as u', 's.student_id', '=', 'u.user_id')
  241. ->where('s.teacher_id', $this->selectedTeacherId)
  242. ->select(
  243. 's.student_id',
  244. 's.name',
  245. 's.grade',
  246. 's.class_name',
  247. 'u.username',
  248. 'u.email'
  249. )
  250. ->orderBy('s.grade')
  251. ->orderBy('s.class_name')
  252. ->orderBy('s.name')
  253. ->get()
  254. ->all();
  255. \Illuminate\Support\Facades\Log::info('智能出题页面加载学生列表', [
  256. 'teacher_id' => $this->selectedTeacherId,
  257. 'student_count' => count($students)
  258. ]);
  259. return $students;
  260. } catch (\Exception $e) {
  261. \Illuminate\Support\Facades\Log::error('加载学生列表失败', [
  262. 'teacher_id' => $this->selectedTeacherId,
  263. 'error' => $e->getMessage()
  264. ]);
  265. return [];
  266. }
  267. }
  268. #[Computed(cache: false)]
  269. public function studentWeaknesses(): array
  270. {
  271. if (!$this->selectedStudentId || !$this->filterByStudentWeakness) {
  272. \Illuminate\Support\Facades\Log::info('学生薄弱点未加载', [
  273. 'student_id' => $this->selectedStudentId,
  274. 'filter_enabled' => $this->filterByStudentWeakness
  275. ]);
  276. return [];
  277. }
  278. try {
  279. $weaknesses = app(LearningAnalyticsService::class)->getStudentWeaknesses($this->selectedStudentId);
  280. \Illuminate\Support\Facades\Log::info('获取学生薄弱点成功', [
  281. 'student_id' => $this->selectedStudentId,
  282. 'weakness_count' => count($weaknesses),
  283. 'weaknesses' => $weaknesses
  284. ]);
  285. return $weaknesses;
  286. } catch (\Exception $e) {
  287. \Illuminate\Support\Facades\Log::error('获取学生薄弱点失败', [
  288. 'student_id' => $this->selectedStudentId,
  289. 'error' => $e->getMessage()
  290. ]);
  291. return [];
  292. }
  293. }
  294. public function updatedSelectedTeacherId($value)
  295. {
  296. // 当教师选择变化时,清空之前选择的学生
  297. $this->selectedStudentId = null;
  298. }
  299. /**
  300. * 全选所有薄弱知识点
  301. */
  302. public function selectAllWeaknesses(): void
  303. {
  304. $weaknesses = $this->studentWeaknesses;
  305. if (empty($weaknesses)) {
  306. Notification::make()
  307. ->title('提示')
  308. ->body('暂无薄弱知识点数据')
  309. ->warning()
  310. ->send();
  311. return;
  312. }
  313. // 获取所有薄弱知识点的代码
  314. $kpCodes = array_column($weaknesses, 'kp_code');
  315. // 合并到已选择的知识点中(去重)
  316. $this->selectedKpCodes = array_unique(array_merge($this->selectedKpCodes, $kpCodes));
  317. Notification::make()
  318. ->title('成功')
  319. ->body('已全选 ' . count($kpCodes) . ' 个薄弱知识点')
  320. ->success()
  321. ->send();
  322. \Illuminate\Support\Facades\Log::info('全选薄弱知识点', [
  323. 'student_id' => $this->selectedStudentId,
  324. 'selected_kp_codes' => $kpCodes,
  325. 'total_selected' => count($this->selectedKpCodes)
  326. ]);
  327. }
  328. /**
  329. * 去重题目:基于ID和内容相似度去重
  330. */
  331. protected function deduplicateQuestions(array $questions): array
  332. {
  333. $uniqueQuestions = [];
  334. $seenIds = [];
  335. $seenStems = [];
  336. foreach ($questions as $question) {
  337. $id = $question['id'] ?? $question['question_id'] ?? null;
  338. $stem = $question['stem'] ?? $question['content'] ?? $question['question_text'] ?? '';
  339. $difficulty = $question['difficulty'] ?? 0.5;
  340. $kpCode = $question['kp_code'] ?? '';
  341. // 规范化题干:移除多余空白和换行
  342. $normalizedStem = preg_replace('/\s+/', ' ', trim($stem));
  343. $normalizedStem = preg_replace('/^\d+\.\s*/', '', $normalizedStem); // 移除题号
  344. // 创建唯一键:ID + 题干哈希 + 知识点
  345. $key = ($id ? "id:{$id}" : "stem:" . md5($normalizedStem)) . "kp:{$kpCode}";
  346. // 如果是选择题,进一步检查选项是否相同
  347. if ($this->determineQuestionType($question) === 'choice') {
  348. $options = $question['options'] ?? [];
  349. if (!empty($options) && is_array($options)) {
  350. $optionsKey = md5(implode('|', $options));
  351. $key .= "opt:{$optionsKey}";
  352. }
  353. }
  354. // 检查是否已存在
  355. if (isset($seenIds[$key]) || in_array($normalizedStem, $seenStems)) {
  356. \Illuminate\Support\Facades\Log::debug("跳过重复题目", [
  357. 'id' => $id,
  358. 'stem_preview' => mb_substr($normalizedStem, 0, 50)
  359. ]);
  360. continue;
  361. }
  362. // 记录并保留
  363. $seenIds[$key] = true;
  364. $seenStems[] = $normalizedStem;
  365. $uniqueQuestions[] = $question;
  366. }
  367. \Illuminate\Support\Facades\Log::info("题目去重完成", [
  368. 'original_count' => count($questions),
  369. 'unique_count' => count($uniqueQuestions),
  370. 'removed_count' => count($questions) - count($uniqueQuestions)
  371. ]);
  372. return array_values($uniqueQuestions);
  373. }
  374. /**
  375. * 清空所有选择的知识点
  376. */
  377. public function clearSelection(): void
  378. {
  379. $this->selectedKpCodes = [];
  380. Notification::make()
  381. ->title('成功')
  382. ->body('已清空所有选择的知识点')
  383. ->info()
  384. ->send();
  385. \Illuminate\Support\Facades\Log::info('清空知识点选择', [
  386. 'student_id' => $this->selectedStudentId
  387. ]);
  388. }
  389. public function updatedSelectedStudentId($value)
  390. {
  391. // 选择学生后,不要清空知识点选择,保持步骤3的选择有效
  392. // $this->selectedKpCodes = []; // 注释掉这行,避免清空用户选择
  393. // 如果启用了薄弱点筛选,加载但不自动勾选
  394. if ($this->filterByStudentWeakness && $value) {
  395. $weaknesses = $this->studentWeaknesses;
  396. if (empty($weaknesses)) {
  397. Notification::make()
  398. ->title('提示')
  399. ->body('该学生暂无薄弱点数据,您可以在步骤3中手动选择知识点')
  400. ->warning()
  401. ->send();
  402. } else {
  403. Notification::make()
  404. ->title('提示')
  405. ->body('已加载' . count($weaknesses) . '个薄弱知识点,您可以在下方或步骤3中选择要练习的知识点')
  406. ->info()
  407. ->send();
  408. }
  409. }
  410. }
  411. /**
  412. * 监听知识点选择变化
  413. */
  414. public function updatedSelectedKpCodes($value)
  415. {
  416. // 记录调试信息
  417. \Illuminate\Support\Facades\Log::info('selectedKpCodes updated', [
  418. 'count' => count($this->selectedKpCodes),
  419. 'codes' => $this->selectedKpCodes,
  420. 'type' => gettype($value),
  421. 'value' => $value
  422. ]);
  423. }
  424. public function generateExam()
  425. {
  426. \Illuminate\Support\Facades\Log::info('generateExam called with studentId=' . ($this->selectedStudentId ?? 'null'));
  427. $this->validate([
  428. // 'paperName' => 'required|string|max:255', // 已移除必填
  429. 'totalQuestions' => 'required|integer|min:6|max:100',
  430. 'selectedTeacherId' => 'nullable|string', // 可选老师
  431. 'selectedStudentId' => 'nullable|string', // 可选学生
  432. ]);
  433. // 确保题目数量至少6题
  434. if ($this->totalQuestions < 6) {
  435. \Illuminate\Support\Facades\Log::warning('题目数量少于6题,已自动调整为6题', ['original' => $this->totalQuestions]);
  436. $this->totalQuestions = 6;
  437. }
  438. if (empty($this->selectedTeacherId) || empty($this->selectedStudentId)) {
  439. Notification::make()
  440. ->title('请选择教师与学生')
  441. ->body('请选择出卷对应的教师与学生后再生成试卷,确保个性化规则生效。')
  442. ->danger()
  443. ->send();
  444. return;
  445. }
  446. if (empty($this->selectedKpCodes)) {
  447. Notification::make()
  448. ->title('请选择知识点')
  449. ->body('请至少选择 1 个知识点后再生成试卷。可勾选学生薄弱点或手动选择知识点。')
  450. ->danger()
  451. ->send();
  452. return;
  453. }
  454. // 自动生成试卷名称
  455. if (empty($this->paperName)) {
  456. $studentName = '学生' . ($this->selectedStudentId ?? '未选择');
  457. // 如果有选择学生,尝试从数据库获取真实姓名
  458. if ($this->selectedStudentId) {
  459. try {
  460. $student = \App\Models\Student::where('student_id', $this->selectedStudentId)->first();
  461. if ($student && $student->name) {
  462. $studentName = $student->name;
  463. }
  464. } catch (\Exception $e) {
  465. \Illuminate\Support\Facades\Log::warning('获取学生姓名失败', [
  466. 'student_id' => $this->selectedStudentId,
  467. 'error' => $e->getMessage()
  468. ]);
  469. }
  470. }
  471. $this->paperName = $studentName . '_' . now()->format('Ymd_His') . '_智能试卷';
  472. }
  473. $this->isGenerating = true;
  474. try {
  475. // 使用LearningAnalyticsService进行智能出卷
  476. $learningAnalyticsService = app(LearningAnalyticsService::class);
  477. // 准备出卷参数
  478. $examParams = [
  479. 'student_id' => $this->selectedStudentId,
  480. 'total_questions' => $this->totalQuestions,
  481. 'kp_codes' => $this->selectedKpCodes,
  482. 'skills' => $this->selectedSkills,
  483. 'question_type_ratio' => $this->questionTypeRatio,
  484. 'difficulty_ratio' => $this->difficultyRatio,
  485. ];
  486. // 调用智能出卷API
  487. $result = $learningAnalyticsService->generateIntelligentExam($examParams);
  488. if (!$result['success']) {
  489. throw new \Exception($result['message']);
  490. }
  491. $questions = $result['questions'];
  492. if (count($questions) < $this->totalQuestions) {
  493. // 题库不足时,批量生成题目(使用题库的多AI模型并行生成功能)
  494. $neededCount = $this->totalQuestions - count($questions);
  495. // 生成比需求更多的题目,储备起来供后续使用
  496. $generateCount = max($neededCount, 20); // 至少生成20道题作为储备
  497. \Illuminate\Support\Facades\Log::info("题库题目不足,需要补充 {$neededCount} 道题,准备批量生成 {$generateCount} 道题", [
  498. 'current_count' => count($questions),
  499. 'needed' => $neededCount,
  500. 'will_generate' => $generateCount
  501. ]);
  502. // 只生成一次,生成足够多的题目(题库服务支持多AI模型并行)
  503. $this->batchGenerateQuestions($generateCount);
  504. // 重新从题库获取题目
  505. $questionBankService = app(QuestionBankService::class);
  506. $params = [
  507. 'kp_codes' => implode(',', $this->selectedKpCodes),
  508. 'limit' => $this->totalQuestions * 2 // 获取更多题目用于筛选
  509. ];
  510. if (!empty($this->selectedSkills)) {
  511. $params['skills'] = implode(',', $this->selectedSkills);
  512. }
  513. if ($this->selectedStudentId) {
  514. $params['exclude_student_questions'] = $this->selectedStudentId;
  515. }
  516. $newResponse = $questionBankService->filterQuestions($params);
  517. // 合并题目并去重
  518. if (!empty($newResponse['data'])) {
  519. $existingIds = array_column($questions, 'id');
  520. foreach ($newResponse['data'] as $newQ) {
  521. if (!in_array($newQ['id'], $existingIds)) {
  522. $questions[] = $newQ;
  523. }
  524. }
  525. }
  526. \Illuminate\Support\Facades\Log::info("批量生成完成,当前题库题目数量: " . count($questions), [
  527. 'generated_count' => $generateCount,
  528. 'total_in_bank' => count($questions)
  529. ]);
  530. }
  531. // 2. 最终去重:确保没有重复题目
  532. $questions = $this->deduplicateQuestions($questions);
  533. \Illuminate\Support\Facades\Log::info("去重后题目数量: " . count($questions));
  534. // 3. 限制试卷题目数量为用户要求的数量
  535. if (count($questions) > $this->totalQuestions) {
  536. // 根据题型配比和难度配比对题目进行筛选和排序
  537. $questions = $this->selectBestQuestions(
  538. $questions,
  539. $this->totalQuestions,
  540. $this->difficultyCategory,
  541. $this->totalScore,
  542. $this->questionTypeRatio
  543. );
  544. \Illuminate\Support\Facades\Log::info("从 " . count($questions) . " 道题中筛选出 " . count($questions) . " 道题,难度分类: {$this->difficultyCategory}, 总分: {$this->totalScore}");
  545. }
  546. // 3. 检查题型完整性(至少保证每种题型都有题目)
  547. $checkResult = $this->ensureQuestionTypeCompleteness($questions, $this->totalQuestions);
  548. if ($checkResult['missing_types']) {
  549. \Illuminate\Support\Facades\Log::warning("检测到缺失题型,将自动生成", [
  550. 'missing_types' => $checkResult['missing_types'],
  551. 'current_count' => $checkResult['current_count']
  552. ]);
  553. // 批量生成缺失题型的题目
  554. $this->batchGenerateMissingTypes($checkResult['missing_types']);
  555. // 重新获取题目
  556. $questionBankService = app(QuestionBankService::class);
  557. $params = [
  558. 'kp_codes' => implode(',', $this->selectedKpCodes),
  559. 'limit' => $this->totalQuestions * 2
  560. ];
  561. if (!empty($this->selectedSkills)) {
  562. $params['skills'] = implode(',', $this->selectedSkills);
  563. }
  564. if ($this->selectedStudentId) {
  565. $params['exclude_student_questions'] = $this->selectedStudentId;
  566. }
  567. $newResponse = $questionBankService->filterQuestions($params);
  568. if (!empty($newResponse['data'])) {
  569. $questions = array_merge($questions, $newResponse['data']);
  570. }
  571. // 再次筛选
  572. $questions = $this->selectBestQuestions(
  573. $questions,
  574. $this->totalQuestions,
  575. $this->difficultyCategory,
  576. $this->totalScore,
  577. $this->questionTypeRatio
  578. );
  579. }
  580. // 2. 为题目添加类型信息(如果缺失)
  581. foreach ($questions as &$question) {
  582. if (!isset($question['question_type'])) {
  583. $question['question_type'] = $this->determineQuestionType($question);
  584. \Illuminate\Support\Facades\Log::debug('为题目添加类型', [
  585. 'question_id' => $question['id'] ?? '',
  586. 'added_type' => $question['question_type']
  587. ]);
  588. }
  589. }
  590. unset($question); // 释放引用
  591. // 3. 生成试卷数据
  592. $examData = [
  593. 'paper_name' => $this->paperName,
  594. 'paper_description' => $this->paperDescription,
  595. 'difficulty_category' => $this->difficultyCategory,
  596. 'questions' => $questions,
  597. 'total_score' => $this->totalScore,
  598. 'total_questions' => count($questions),
  599. 'student_id' => $this->selectedStudentId,
  600. 'teacher_id' => $this->selectedTeacherId,
  601. ];
  602. // 4. 保存到数据库
  603. $questionBankService = app(QuestionBankService::class);
  604. $paperId = $questionBankService->saveExamToDatabase($examData);
  605. // 如果保存返回 null,使用默认占位 ID,防止 UI 不显示
  606. if (empty($paperId)) {
  607. $paperId = 'demo_' . $this->selectedStudentId . '_' . now()->format('YmdHis');
  608. }
  609. \Illuminate\Support\Facades\Log::info('Generated paper ID: ' . $paperId);
  610. $this->generatedPaperId = $paperId;
  611. // 将生成的试卷数据缓存,以便 PDF 预览时使用(缓存 1 小时)
  612. \Illuminate\Support\Facades\Log::info('缓存试卷数据', [
  613. 'paper_id' => $paperId,
  614. 'question_count' => count($questions),
  615. 'question_types' => array_column($questions, 'question_type')
  616. ]);
  617. Cache::put('generated_exam_' . $paperId, $examData, now()->addHour());
  618. $this->generatedQuestions = $questions;
  619. $stats = $result['stats'] ?? [];
  620. $message = "已生成包含 " . count($questions) . " 道题的试卷";
  621. if (!empty($stats['weakness_targeted'])) {
  622. $message .= ",其中针对薄弱点 " . $stats['weakness_targeted'] . " 题";
  623. }
  624. Notification::make()
  625. ->title('试卷生成成功')
  626. ->body($message)
  627. ->success()
  628. ->send();
  629. } catch (\Exception $e) {
  630. // 记录错误并提供回退的试卷 ID,防止 UI 无显示
  631. \Illuminate\Support\Facades\Log::error('生成试卷失败', ['error' => $e->getMessage()]);
  632. $fallbackId = 'demo_' . $this->selectedStudentId . '_' . now()->format('YmdHis');
  633. $this->generatedPaperId = $fallbackId;
  634. $this->generatedQuestions = [];
  635. Notification::make()
  636. ->title('试卷生成失败,使用默认试卷')
  637. ->body('错误: ' . $e->getMessage() . "\n已生成默认试卷 ID: $fallbackId")
  638. ->warning()
  639. ->send();
  640. } finally {
  641. $this->isGenerating = false;
  642. }
  643. }
  644. /**
  645. * 批量生成题目(使用题库的多AI模型并行功能)
  646. */
  647. protected function batchGenerateQuestions(int $count)
  648. {
  649. // 增加PHP脚本执行时间到120秒,给足够时间启动异步任务和等待完成
  650. set_time_limit(120);
  651. $questionBankService = app(QuestionBankService::class);
  652. $generatedTasks = [];
  653. // 只生成一次,使用所有选中的知识点
  654. $allKpCodes = $this->selectedKpCodes;
  655. if (empty($allKpCodes)) {
  656. // 如果没有选中知识点,使用默认知识点
  657. $allKpCodes = ['R01']; // 默认知识点
  658. }
  659. // 对每个知识点生成题目
  660. foreach ($allKpCodes as $kpCode) {
  661. \Illuminate\Support\Facades\Log::info("为知识点 {$kpCode} 生成题目", [
  662. 'count' => $count,
  663. 'skills' => $this->selectedSkills
  664. ]);
  665. $result = $questionBankService->generateIntelligentQuestions([
  666. 'kp_code' => $kpCode,
  667. 'skills' => $this->selectedSkills,
  668. 'count' => $count,
  669. 'difficulty_distribution' => $this->difficultyRatio,
  670. ]);
  671. if ($result['success'] && isset($result['task_id'])) {
  672. $generatedTasks[] = [
  673. 'task_id' => $result['task_id'],
  674. 'kp_code' => $kpCode
  675. ];
  676. \Illuminate\Support\Facades\Log::info("已启动生成任务: {$result['task_id']} for {$kpCode}");
  677. } else {
  678. \Illuminate\Support\Facades\Log::warning("生成任务启动失败", [
  679. 'kp_code' => $kpCode,
  680. 'result' => $result
  681. ]);
  682. }
  683. }
  684. // 等待所有任务完成(最多等待60秒)
  685. if (!empty($generatedTasks)) {
  686. $maxWaitTime = 60; // 增加最大等待时间
  687. $startTime = time();
  688. \Illuminate\Support\Facades\Log::info("等待 {$maxWaitTime} 秒,所有生成任务完成", [
  689. 'tasks' => array_column($generatedTasks, 'task_id')
  690. ]);
  691. while (time() - $startTime < $maxWaitTime) {
  692. $allCompleted = true;
  693. $completedTasks = [];
  694. $runningTasks = [];
  695. foreach ($generatedTasks as $task) {
  696. $taskStatus = $questionBankService->getTaskStatus($task['task_id']);
  697. if (!$taskStatus) {
  698. $allCompleted = false;
  699. $runningTasks[] = $task['task_id'];
  700. continue;
  701. }
  702. $status = $taskStatus['status'] ?? '';
  703. if ($status === 'completed') {
  704. $completedTasks[] = $task['task_id'];
  705. } elseif ($status === 'failed') {
  706. \Illuminate\Support\Facades\Log::error("生成任务失败", [
  707. 'task_id' => $task['task_id'],
  708. 'error' => $taskStatus['error'] ?? '未知错误'
  709. ]);
  710. // 任务失败继续等待其他任务
  711. } else {
  712. $allCompleted = false;
  713. $runningTasks[] = $task['task_id'];
  714. }
  715. }
  716. if ($allCompleted) {
  717. \Illuminate\Support\Facades\Log::info('所有AI生成任务已完成', [
  718. 'completed' => $completedTasks,
  719. 'tasks' => $generatedTasks
  720. ]);
  721. break;
  722. }
  723. // 每10秒输出一次进度
  724. $elapsed = time() - $startTime;
  725. if ($elapsed % 10 < 2) {
  726. \Illuminate\Support\Facades\Log::info("生成进度", [
  727. 'elapsed' => $elapsed,
  728. 'completed' => count($completedTasks),
  729. 'running' => count($runningTasks),
  730. 'total' => count($generatedTasks)
  731. ]);
  732. }
  733. // 等待3秒后重试
  734. sleep(3);
  735. }
  736. $waitTime = time() - $startTime;
  737. \Illuminate\Support\Facades\Log::info('AI生成任务等待完成', [
  738. 'wait_time' => $waitTime,
  739. 'tasks' => $generatedTasks
  740. ]);
  741. }
  742. }
  743. /**
  744. * 根据题型配比和难度配比,从大量题目中筛选出最佳题目
  745. */
  746. protected function selectBestQuestions(
  747. array $questions,
  748. int $targetCount,
  749. string $difficultyCategory,
  750. float $totalScore,
  751. array $questionTypeRatio
  752. ): array {
  753. // 去重:确保输入题目列表没有重复ID
  754. $uniqueQuestions = [];
  755. foreach ($questions as $q) {
  756. $id = $q['id'] ?? $q['question_id'] ?? null;
  757. if ($id && !isset($uniqueQuestions[$id])) {
  758. $uniqueQuestions[$id] = $q;
  759. }
  760. }
  761. $questions = array_values($uniqueQuestions);
  762. if (count($questions) <= $targetCount) {
  763. return $questions;
  764. }
  765. \Illuminate\Support\Facades\Log::info("开始筛选题目", [
  766. 'total_available' => count($questions),
  767. 'target_count' => $targetCount,
  768. 'difficulty_category' => $difficultyCategory,
  769. 'total_score' => $totalScore,
  770. 'type_ratio' => $questionTypeRatio
  771. ]);
  772. // 1. 按题型分类题目
  773. $categorizedQuestions = [
  774. 'choice' => [], // 选择题
  775. 'fill' => [], // 填空题
  776. 'answer' => [], // 解答题
  777. ];
  778. foreach ($questions as $question) {
  779. $type = $this->determineQuestionType($question);
  780. if (!isset($categorizedQuestions[$type])) {
  781. $type = 'answer';
  782. }
  783. $categorizedQuestions[$type][] = $question;
  784. }
  785. // 2. 根据难度分类筛选题目
  786. $difficultyFilteredQuestions = $this->filterByDifficulty($categorizedQuestions, $difficultyCategory);
  787. // 3. 根据题型配比计算每种题型应选择的题目数量
  788. $selectedQuestions = [];
  789. $selectedIds = []; // 用于追踪已选题目ID
  790. // 优先保证每种题型至少一题(适用于总题目数>=3的情况)
  791. if ($targetCount >= 3) {
  792. foreach (['choice', 'fill', 'answer'] as $typeKey) {
  793. if (!empty($difficultyFilteredQuestions[$typeKey])) {
  794. // 随机选择1道该题型的题目
  795. $randomIndex = array_rand($difficultyFilteredQuestions[$typeKey]);
  796. $q = $difficultyFilteredQuestions[$typeKey][$randomIndex];
  797. $id = $q['id'] ?? $q['question_id'];
  798. if (!in_array($id, $selectedIds)) {
  799. $selectedQuestions[] = $q;
  800. $selectedIds[] = $id;
  801. }
  802. \Illuminate\Support\Facades\Log::info("保证题型最少题目: {$typeKey}", [
  803. 'selected_index' => $randomIndex
  804. ]);
  805. } else {
  806. \Illuminate\Support\Facades\Log::warning("题型缺失: {$typeKey},需要从其他题型补充");
  807. }
  808. }
  809. }
  810. // 根据题型配比计算每种题型应选择的题目数量
  811. foreach ($questionTypeRatio as $type => $ratio) {
  812. $typeKey = $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer');
  813. // 计算该类型目标数量
  814. $targetTypeCount = floor($targetCount * $ratio / 100);
  815. // 调整目标数量:如果总数>=3,需要考虑已经选了的题目
  816. // 简单起见,我们计算总共需要的数量,然后减去已经选了的数量
  817. // 但这里为了保证比例,我们还是尽量多选
  818. if ($targetTypeCount <= 0) continue;
  819. if (!empty($difficultyFilteredQuestions[$typeKey])) {
  820. $availableQuestions = $difficultyFilteredQuestions[$typeKey];
  821. // 过滤掉已选的
  822. $availableQuestions = array_filter($availableQuestions, function($q) use ($selectedIds) {
  823. $id = $q['id'] ?? $q['question_id'];
  824. return !in_array($id, $selectedIds);
  825. });
  826. // 如果没有可用题目了,跳过
  827. if (empty($availableQuestions)) continue;
  828. $availableCount = count($availableQuestions);
  829. // 还需要选多少:目标数量 - 已选该类型的数量
  830. $currentTypeCount = 0;
  831. foreach ($selectedQuestions as $sq) {
  832. if ($this->determineQuestionType($sq) === $typeKey) {
  833. $currentTypeCount++;
  834. }
  835. }
  836. $needToSelect = $targetTypeCount - $currentTypeCount;
  837. if ($needToSelect > 0) {
  838. $takeCount = min($needToSelect, $availableCount, $targetCount - count($selectedQuestions));
  839. if ($takeCount > 0) {
  840. $randomKeys = array_rand($availableQuestions, $takeCount);
  841. if (!is_array($randomKeys)) {
  842. $randomKeys = [$randomKeys];
  843. }
  844. foreach ($randomKeys as $key) {
  845. $q = $availableQuestions[$key];
  846. $selectedQuestions[] = $q;
  847. $selectedIds[] = $q['id'] ?? $q['question_id'];
  848. }
  849. }
  850. }
  851. }
  852. }
  853. // 4. 如果还有空缺,随机补充其他题型
  854. if (count($selectedQuestions) < $targetCount) {
  855. // 从所有题目中过滤掉已选的
  856. $remainingQuestions = array_filter($questions, function($q) use ($selectedIds) {
  857. $id = $q['id'] ?? $q['question_id'];
  858. return !in_array($id, $selectedIds);
  859. });
  860. if (!empty($remainingQuestions)) {
  861. $needed = $targetCount - count($selectedQuestions);
  862. $take = min($needed, count($remainingQuestions));
  863. $randomKeys = array_rand($remainingQuestions, $take);
  864. if (!is_array($randomKeys)) {
  865. $randomKeys = [$randomKeys];
  866. }
  867. foreach ($randomKeys as $key) {
  868. $selectedQuestions[] = $remainingQuestions[$key];
  869. }
  870. }
  871. }
  872. // 5. 打乱题目顺序
  873. shuffle($selectedQuestions);
  874. $finalQuestions = array_slice($selectedQuestions, 0, $targetCount);
  875. \Illuminate\Support\Facades\Log::info("题目筛选完成", [
  876. 'selected_count' => count($finalQuestions),
  877. 'difficulty_category' => $difficultyCategory,
  878. 'total_score' => $totalScore
  879. ]);
  880. return $finalQuestions;
  881. }
  882. /**
  883. * 检查题型完整性,确保每种题型至少有一题
  884. */
  885. protected function ensureQuestionTypeCompleteness(array $questions, int $targetCount): array
  886. {
  887. $result = [
  888. 'missing_types' => [],
  889. 'current_count' => count($questions),
  890. 'has_choice' => false,
  891. 'has_fill' => false,
  892. 'has_answer' => false,
  893. ];
  894. // 统计各题型数量
  895. $choiceCount = $fillCount = $answerCount = 0;
  896. foreach ($questions as $q) {
  897. $type = $this->determineQuestionType($q);
  898. if ($type === 'choice') {
  899. $choiceCount++;
  900. $result['has_choice'] = true;
  901. } elseif ($type === 'fill') {
  902. $fillCount++;
  903. $result['has_fill'] = true;
  904. } elseif ($type === 'answer') {
  905. $answerCount++;
  906. $result['has_answer'] = true;
  907. }
  908. }
  909. // 如果题目数量>=3,确保每种题型至少1题
  910. if ($targetCount >= 3) {
  911. if (!$result['has_choice']) {
  912. $result['missing_types'][] = 'choice';
  913. }
  914. if (!$result['has_fill']) {
  915. $result['missing_types'][] = 'fill';
  916. }
  917. if (!$result['has_answer']) {
  918. $result['missing_types'][] = 'answer';
  919. }
  920. }
  921. \Illuminate\Support\Facades\Log::info("题型完整性检查", [
  922. 'choice_count' => $choiceCount,
  923. 'fill_count' => $fillCount,
  924. 'answer_count' => $answerCount,
  925. 'missing_types' => $result['missing_types']
  926. ]);
  927. return $result;
  928. }
  929. /**
  930. * 批量生成缺失题型的题目
  931. */
  932. protected function batchGenerateMissingTypes(array $missingTypes): void
  933. {
  934. if (empty($missingTypes)) {
  935. return;
  936. }
  937. // 增加PHP脚本执行时间到120秒,给足够时间启动异步任务
  938. set_time_limit(120);
  939. \Illuminate\Support\Facades\Log::info("开始生成缺失题型题目", ['missing_types' => $missingTypes]);
  940. // 为每个缺失题型生成3-5道题
  941. foreach ($missingTypes as $type) {
  942. $generateCount = 5; // 每个缺失题型生成5道题
  943. \Illuminate\Support\Facades\Log::info("为缺失题型 {$type} 生成 {$generateCount} 道题");
  944. foreach ($this->selectedKpCodes as $kpCode) {
  945. $questionBankService = app(QuestionBankService::class);
  946. // 根据题型设置特定的技能点
  947. $skills = $this->selectedSkills;
  948. if ($type === 'choice') {
  949. $skills[] = '选择题专项练习';
  950. } elseif ($type === 'fill') {
  951. $skills[] = '填空题专项练习';
  952. } elseif ($type === 'answer') {
  953. $skills[] = '解答题专项练习';
  954. }
  955. $result = $questionBankService->generateIntelligentQuestions([
  956. 'kp_code' => $kpCode,
  957. 'skills' => $skills,
  958. 'count' => $generateCount,
  959. 'difficulty_distribution' => $this->difficultyRatio,
  960. ]);
  961. if ($result['success'] && isset($result['task_id'])) {
  962. \Illuminate\Support\Facades\Log::info("已启动生成任务", [
  963. 'type' => $type,
  964. 'task_id' => $result['task_id'],
  965. 'kp_code' => $kpCode
  966. ]);
  967. }
  968. }
  969. }
  970. // 缺失题型生成任务已启动,由于题目生成是异步的,
  971. // 将在预览时动态获取最新生成的题目
  972. \Illuminate\Support\Facades\Log::info("缺失题型生成任务已启动,将在预览时动态获取");
  973. }
  974. /**
  975. * 根据难度分类筛选题目
  976. */
  977. protected function filterByDifficulty(array $categorizedQuestions, string $difficultyCategory): array
  978. {
  979. $filtered = [];
  980. $difficultyRanges = [
  981. '基础' => [0, 0.4],
  982. '中等' => [0.3, 0.7],
  983. '拔高' => [0.6, 1.0]
  984. ];
  985. $targetRange = $difficultyRanges[$difficultyCategory] ?? [0, 1.0];
  986. foreach ($categorizedQuestions as $type => $questions) {
  987. $filtered[$type] = [];
  988. foreach ($questions as $question) {
  989. $difficulty = floatval($question['difficulty'] ?? 0.5);
  990. if ($difficulty >= $targetRange[0] && $difficulty <= $targetRange[1]) {
  991. $filtered[$type][] = $question;
  992. } else {
  993. // 保留部分越界题目(如果该难度题目不足)
  994. if (count($filtered[$type]) < 2) {
  995. $filtered[$type][] = $question;
  996. }
  997. }
  998. }
  999. }
  1000. \Illuminate\Support\Facades\Log::info("难度筛选结果", [
  1001. 'difficulty_category' => $difficultyCategory,
  1002. 'difficulty_range' => $targetRange,
  1003. 'choice_count' => count($filtered['choice']),
  1004. 'fill_count' => count($filtered['fill']),
  1005. 'answer_count' => count($filtered['answer'])
  1006. ]);
  1007. return $filtered;
  1008. }
  1009. /**
  1010. * 根据题目标签或内容判断题型
  1011. */
  1012. protected function determineQuestionType(array $question): string
  1013. {
  1014. // 0. 如果题目已有明确类型,直接返回
  1015. if (!empty($question['type'])) {
  1016. if ($question['type'] === 'choice' || $question['type'] === '选择题') return 'choice';
  1017. if ($question['type'] === 'fill' || $question['type'] === '填空题') return 'fill';
  1018. if ($question['type'] === 'answer' || $question['type'] === '解答题') return 'answer';
  1019. }
  1020. $tags = $question['tags'] ?? '';
  1021. $stem = $question['stem'] ?? $question['content'] ?? '';
  1022. // 1. 根据标签判断
  1023. if (is_string($tags)) {
  1024. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  1025. return 'choice';
  1026. }
  1027. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  1028. return 'fill';
  1029. }
  1030. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  1031. return 'answer';
  1032. }
  1033. }
  1034. // 2. 根据题干内容判断 - 填空题优先(有下划线)
  1035. // 填空题特征:连续的下划线,或者括号中明显是填空的(通常不会有选项)
  1036. if (is_string($stem)) {
  1037. // 检查填空题特征:连续下划线
  1038. if (strpos($stem, '____') !== false || strpos($stem, '______') !== false) {
  1039. return 'fill';
  1040. }
  1041. }
  1042. // 3. 根据题干内容判断 - 选择题
  1043. // 选择题特征:必须包含选项 A. B. C. D.
  1044. if (is_string($stem)) {
  1045. // 检查选项格式 A. B. C. D.(支持跨行匹配)
  1046. // 更严格的正则:A. 后面跟内容,或者 (A) 后面跟内容
  1047. if (preg_match('/[A-D]\s*\./', $stem) || preg_match('/\([A-D]\)/', $stem)) {
  1048. // 再次确认是否包含多个选项,防止误判
  1049. if (preg_match('/A\./', $stem) && preg_match('/B\./', $stem)) {
  1050. return 'choice';
  1051. }
  1052. }
  1053. // 如果只有括号但没有选项,可能是填空题
  1054. // 比如 "计算:(1) ... (2) ..." 这种是解答题
  1055. // "若 x > 0,则 x + 1 ( )" 这种可能是填空也可能是选择,取决于是否有选项
  1056. // 这里我们保守一点,如果没有选项特征,就不认为是选择题
  1057. }
  1058. // 4. 再次检查填空题特征(括号填空)
  1059. if (is_string($stem)) {
  1060. // 只有括号且没有选项,通常是填空
  1061. if ((strpos($stem, '()') !== false || strpos($stem, '()') !== false) && !preg_match('/[A-D]\./', $stem)) {
  1062. return 'fill';
  1063. }
  1064. }
  1065. // 5. 根据题干长度和内容判断(启发式)
  1066. if (is_string($stem)) {
  1067. // 有证明、解答、计算、求证等关键词的是解答题
  1068. if (strpos($stem, '证明') !== false || strpos($stem, '求证') !== false || strpos($stem, '解方程') !== false || strpos($stem, '计算:') !== false) {
  1069. return 'answer';
  1070. }
  1071. }
  1072. // 默认是解答题
  1073. return 'answer';
  1074. }
  1075. /**
  1076. * 保留旧方法以兼容(但不再使用)
  1077. */
  1078. protected function autoGenerateQuestions(int $count)
  1079. {
  1080. // 调用新的批量生成方法
  1081. $this->batchGenerateQuestions($count);
  1082. }
  1083. public function exportToPdf()
  1084. {
  1085. if (!$this->generatedPaperId) {
  1086. Notification::make()
  1087. ->title('错误')
  1088. ->body('请先生成试卷')
  1089. ->danger()
  1090. ->send();
  1091. return;
  1092. }
  1093. // 调用PDF导出API
  1094. return redirect()->route('filament.admin.auth.intelligent-exam.pdf', [
  1095. 'paper_id' => $this->generatedPaperId
  1096. ]);
  1097. }
  1098. public function resetForm()
  1099. {
  1100. $this->reset([
  1101. 'paperName', 'paperDescription', 'selectedKpCodes', 'selectedSkills',
  1102. 'selectedTeacherId', 'selectedStudentId', 'filterByStudentWeakness', 'generatedQuestions', 'generatedPaperId'
  1103. ]);
  1104. $this->questionTypeRatio = [
  1105. '选择题' => 40,
  1106. '填空题' => 30,
  1107. '解答题' => 30,
  1108. ];
  1109. $this->difficultyRatio = [
  1110. '基础' => 50,
  1111. '中等' => 35,
  1112. '拔高' => 15,
  1113. ];
  1114. }
  1115. /**
  1116. * 监听TeacherStudentSelector组件的老师变化事件
  1117. */
  1118. #[On('teacherChanged')]
  1119. public function onTeacherChanged(string $teacherId): void
  1120. {
  1121. \Illuminate\Support\Facades\Log::info('智能出题页面收到教师变更事件', [
  1122. 'teacher_id' => $teacherId
  1123. ]);
  1124. $this->selectedTeacherId = $teacherId;
  1125. // 清空学生选择和相关的筛选
  1126. $this->selectedStudentId = null;
  1127. $this->filterByStudentWeakness = false;
  1128. }
  1129. /**
  1130. * 监听TeacherStudentSelector组件的学生变化事件
  1131. */
  1132. #[On('studentChanged')]
  1133. public function onStudentChanged(string $teacherId, string $studentId): void
  1134. {
  1135. \Illuminate\Support\Facades\Log::info('智能出题页面收到学生变更事件', [
  1136. 'teacher_id' => $teacherId,
  1137. 'student_id' => $studentId
  1138. ]);
  1139. $this->selectedTeacherId = $teacherId;
  1140. $this->selectedStudentId = $studentId;
  1141. // ✅ 如果有学生选择,自动启用学生薄弱点筛选(但暂不勾选知识点)
  1142. if ($studentId) {
  1143. $this->filterByStudentWeakness = true;
  1144. \Illuminate\Support\Facades\Log::info('已自动启用薄弱点筛选', [
  1145. 'student_id' => $studentId,
  1146. 'filter_enabled' => $this->filterByStudentWeakness
  1147. ]);
  1148. // 不立即触发,让用户自己选择
  1149. } else {
  1150. // 如果清空了学生选择,也清空薄弱点筛选
  1151. $this->filterByStudentWeakness = false;
  1152. }
  1153. }
  1154. }