IntelligentExamGeneration.php 45 KB

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