QuestionManagement.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. <?php
  2. namespace App\Filament\Pages;
  3. use App\Services\QuestionServiceApi;
  4. use App\Services\KnowledgeGraphService;
  5. use App\Services\QuestionBankService;
  6. use App\Services\PromptService;
  7. use BackedEnum;
  8. use Filament\Actions;
  9. use Filament\Notifications\Notification;
  10. use Filament\Pages\Page;
  11. use UnitEnum;
  12. use Livewire\Attributes\Computed;
  13. use Livewire\Attributes\On;
  14. class QuestionManagement extends Page
  15. {
  16. protected static ?string $title = '题库管理';
  17. protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-rectangle-stack';
  18. protected static string|UnitEnum|null $navigationGroup = '题库系统';
  19. protected static ?string $navigationLabel = '题库管理';
  20. protected static ?int $navigationSort = 2;
  21. protected string $view = 'filament.pages.question-management';
  22. public ?string $search = null;
  23. public ?string $selectedKpCode = null;
  24. public ?string $selectedDifficulty = null;
  25. public int $currentPage = 1;
  26. public int $perPage = 25;
  27. // 生成题目相关属性
  28. public ?string $generateKpCode = null;
  29. public array $selectedSkills = [];
  30. public int $questionCount = 100;
  31. public ?string $promptTemplate = null;
  32. public bool $showGenerateModal = false;
  33. public bool $showPromptModal = false;
  34. // 异步任务相关属性
  35. public ?string $currentTaskId = null;
  36. public ?string $currentTaskStatus = null;
  37. public int $currentTaskProgress = 0;
  38. public ?string $currentTaskMessage = null;
  39. public bool $isGenerating = false;
  40. /**
  41. * 计算属性:从 API 获取题目列表
  42. */
  43. #[Computed]
  44. public function questions(): array
  45. {
  46. $service = app(QuestionServiceApi::class);
  47. $filters = array_filter([
  48. 'kp_code' => $this->selectedKpCode,
  49. 'difficulty' => $this->selectedDifficulty,
  50. 'search' => $this->search,
  51. ], fn ($value) => filled($value));
  52. $response = $service->listQuestions($this->currentPage, $this->perPage, $filters);
  53. return $response['data'] ?? [];
  54. }
  55. /**
  56. * 计算属性:分页信息
  57. */
  58. #[Computed]
  59. public function meta(): array
  60. {
  61. $service = app(QuestionServiceApi::class);
  62. $filters = array_filter([
  63. 'kp_code' => $this->selectedKpCode,
  64. 'difficulty' => $this->selectedDifficulty,
  65. 'search' => $this->search,
  66. ], fn ($value) => filled($value));
  67. $response = $service->listQuestions($this->currentPage, $this->perPage, $filters);
  68. return $response['meta'] ?? [
  69. 'page' => 1,
  70. 'per_page' => 25,
  71. 'total' => 0,
  72. 'total_pages' => 0,
  73. ];
  74. }
  75. /**
  76. * 计算属性:统计数据
  77. */
  78. #[Computed]
  79. public function statistics(): array
  80. {
  81. $service = app(QuestionServiceApi::class);
  82. return $service->getStatistics();
  83. }
  84. /**
  85. * 计算属性:知识点选项
  86. */
  87. #[Computed]
  88. public function knowledgePointOptions(): array
  89. {
  90. $service = app(QuestionServiceApi::class);
  91. return $service->getKnowledgePointOptions();
  92. }
  93. /**
  94. * 计算属性:根据知识点获取技能列表
  95. */
  96. #[Computed]
  97. public function skillsOptions(): array
  98. {
  99. if (!$this->generateKpCode) {
  100. return [];
  101. }
  102. $service = app(KnowledgeGraphService::class);
  103. return $service->getSkillsByKnowledgePoint($this->generateKpCode);
  104. }
  105. /**
  106. * 计算属性:提示词模板
  107. */
  108. #[Computed]
  109. public function promptTemplateData(): array
  110. {
  111. $service = app(PromptService::class);
  112. try {
  113. $response = $service->listPrompts();
  114. if (!empty($response)) {
  115. return $response;
  116. }
  117. } catch (\Exception $e) {
  118. // 使用默认提示词
  119. }
  120. // 返回默认提示词模板
  121. return [[
  122. 'id' => 'default',
  123. 'template_name' => 'AI题目生成_增强版',
  124. 'template_content' => $service->getDefaultPromptTemplate(),
  125. 'version' => 2,
  126. 'is_active' => true,
  127. 'description' => '增强版AI题目生成模板,支持精确的难度和题型分布控制',
  128. 'tags' => 'AI生成,增强版,智能分布'
  129. ]];
  130. }
  131. /**
  132. * 打开生成题目模态框
  133. */
  134. public function openGenerateModal(): void
  135. {
  136. $this->showGenerateModal = true;
  137. }
  138. /**
  139. * 关闭生成题目模态框
  140. */
  141. public function closeGenerateModal(): void
  142. {
  143. $this->showGenerateModal = false;
  144. $this->reset(['generateKpCode', 'selectedSkills', 'questionCount']);
  145. }
  146. /**
  147. * 打开提示词编辑模态框
  148. */
  149. public function openPromptModal(): void
  150. {
  151. $templates = $this->promptTemplateData;
  152. if (!empty($templates)) {
  153. $this->promptTemplate = $templates[0]['template_content'] ?? null;
  154. }
  155. $this->showPromptModal = true;
  156. }
  157. /**
  158. * 关闭提示词编辑模态框
  159. */
  160. public function closePromptModal(): void
  161. {
  162. $this->showPromptModal = false;
  163. $this->reset('promptTemplate');
  164. }
  165. /**
  166. * 全选/取消全选技能
  167. */
  168. public function toggleAllSkills(): void
  169. {
  170. $skills = $this->skillsOptions;
  171. if (count($this->selectedSkills) === count($skills)) {
  172. $this->selectedSkills = [];
  173. } else {
  174. $this->selectedSkills = array_column($skills, 'code');
  175. }
  176. }
  177. /**
  178. * 监听知识点选择变化
  179. */
  180. public function updatedGenerateKpCode(): void
  181. {
  182. // 选择新知识点时重置技能选择
  183. $this->selectedSkills = [];
  184. // 重新计算skillsOptions会自动触发(通过#[Computed])
  185. }
  186. /**
  187. * 监听技能选择变化
  188. */
  189. public function updatedSelectedSkills(): void
  190. {
  191. // 可选:在这里添加其他逻辑
  192. }
  193. /**
  194. * 搜索更新处理
  195. */
  196. public function updatedSearch(): void
  197. {
  198. $this->currentPage = 1;
  199. }
  200. /**
  201. * 知识点筛选更新处理
  202. */
  203. public function updatedSelectedKpCode(): void
  204. {
  205. $this->currentPage = 1;
  206. }
  207. /**
  208. * 难度筛选更新处理
  209. */
  210. public function updatedSelectedDifficulty(): void
  211. {
  212. $this->currentPage = 1;
  213. }
  214. /**
  215. * 每页数量更新处理
  216. */
  217. public function updatedPerPage(): void
  218. {
  219. $this->currentPage = 1;
  220. }
  221. /**
  222. * 刷新数据
  223. */
  224. #[On('refresh-data')]
  225. public function refreshData(): void
  226. {
  227. $this->resetCache();
  228. Notification::make()
  229. ->title('数据已刷新')
  230. ->success()
  231. ->send();
  232. }
  233. /**
  234. * AI 生成题目
  235. */
  236. #[On('ai-generate')]
  237. public function aiGenerate(): void
  238. {
  239. // 打开生成模态框
  240. $this->openGenerateModal();
  241. }
  242. /**
  243. * 执行生成题目(异步模式)
  244. */
  245. #[On('execute-generate')]
  246. public function executeGenerate(): void
  247. {
  248. if (!$this->generateKpCode) {
  249. Notification::make()
  250. ->title('请选择知识点')
  251. ->danger()
  252. ->send();
  253. return;
  254. }
  255. if (empty($this->selectedSkills)) {
  256. Notification::make()
  257. ->title('请至少选择一个技能')
  258. ->danger()
  259. ->send();
  260. return;
  261. }
  262. try {
  263. $service = app(QuestionBankService::class);
  264. // 构建回调 URL
  265. $callbackUrl = route('api.questions.callback');
  266. $result = $service->generateIntelligentQuestions([
  267. 'kp_code' => $this->generateKpCode,
  268. 'skills' => $this->selectedSkills,
  269. 'count' => $this->questionCount,
  270. 'prompt_template' => $this->promptTemplate
  271. ], $callbackUrl);
  272. if ($result['success'] ?? false) {
  273. // 获取task_id
  274. $this->currentTaskId = $result['task_id'] ?? null;
  275. // 关闭模态框
  276. $this->showGenerateModal = false;
  277. // 显示提示消息
  278. Notification::make()
  279. ->title('任务已创建')
  280. ->body("任务 ID: {$this->currentTaskId}\n题目生成完成后将自动刷新列表")
  281. ->info()
  282. ->send();
  283. // 不再轮询,等待回调
  284. } else {
  285. $error = $result['message'] ?? '未知错误';
  286. Notification::make()
  287. ->title('创建任务失败')
  288. ->body($error)
  289. ->danger()
  290. ->send();
  291. }
  292. } catch (\Exception $e) {
  293. Notification::make()
  294. ->title('生成异常')
  295. ->body($e->getMessage())
  296. ->danger()
  297. ->send();
  298. }
  299. }
  300. /**
  301. * 轮询任务状态
  302. */
  303. public function pollTaskStatus(): void
  304. {
  305. if (!$this->currentTaskId) {
  306. return;
  307. }
  308. try {
  309. $service = app(QuestionBankService::class);
  310. $taskStatus = $service->getTaskStatus($this->currentTaskId);
  311. if ($taskStatus) {
  312. $this->currentTaskStatus = $taskStatus['status'] ?? 'unknown';
  313. $this->currentTaskProgress = $taskStatus['progress'] ?? 0;
  314. $this->currentTaskMessage = $this->getTaskStatusMessage($taskStatus);
  315. // 如果任务完成或失败,停止轮询
  316. if (in_array($this->currentTaskStatus, ['completed', 'failed'])) {
  317. $this->isGenerating = false;
  318. if ($this->currentTaskStatus === 'completed') {
  319. $result = $taskStatus['result'] ?? null;
  320. $total = $result['total'] ?? $this->questionCount;
  321. Notification::make()
  322. ->title('生成完成')
  323. ->body("已为知识点 {$this->generateKpCode} 成功生成 {$total} 道题目")
  324. ->success()
  325. ->send();
  326. // 刷新数据
  327. $this->refreshData();
  328. } else {
  329. $error = $taskStatus['error_message'] ?? '未知错误';
  330. Notification::make()
  331. ->title('生成失败')
  332. ->body($error)
  333. ->danger()
  334. ->send();
  335. }
  336. // 重置任务状态
  337. $this->currentTaskId = null;
  338. $this->currentTaskStatus = null;
  339. $this->currentTaskProgress = 0;
  340. $this->currentTaskMessage = null;
  341. } else {
  342. // 继续轮询
  343. $this->dispatch('$refresh');
  344. $this->dispatch('poll-task');
  345. }
  346. }
  347. } catch (\Exception $e) {
  348. $this->isGenerating = false;
  349. Notification::make()
  350. ->title('查询任务状态失败')
  351. ->body($e->getMessage())
  352. ->danger()
  353. ->send();
  354. }
  355. }
  356. /**
  357. * 获取任务状态消息
  358. */
  359. private function getTaskStatusMessage(array $taskStatus): string
  360. {
  361. $status = $taskStatus['status'] ?? 'unknown';
  362. $progress = $taskStatus['progress'] ?? 0;
  363. return match ($status) {
  364. 'pending' => '任务已创建,等待开始...',
  365. 'processing' => "正在生成题目... {$progress}%",
  366. 'completed' => '生成完成',
  367. 'failed' => '生成失败',
  368. default => '未知状态',
  369. };
  370. }
  371. /**
  372. * 取消生成任务
  373. */
  374. #[On('cancel-generate')]
  375. public function cancelGenerate(): void
  376. {
  377. $this->isGenerating = false;
  378. $this->currentTaskId = null;
  379. $this->currentTaskStatus = null;
  380. $this->currentTaskProgress = 0;
  381. $this->currentTaskMessage = null;
  382. Notification::make()
  383. ->title('已取消生成任务')
  384. ->warning()
  385. ->send();
  386. }
  387. /**
  388. * 保存提示词
  389. */
  390. #[On('save-prompt')]
  391. public function savePrompt(): void
  392. {
  393. if (!$this->promptTemplate) {
  394. Notification::make()
  395. ->title('提示词不能为空')
  396. ->danger()
  397. ->send();
  398. return;
  399. }
  400. try {
  401. $service = app(PromptService::class);
  402. $result = $service->savePrompt([
  403. 'template_name' => 'AI题目生成_增强版',
  404. 'template_type' => '题目生成',
  405. 'template_content' => $this->promptTemplate,
  406. 'version' => 2,
  407. 'is_active' => true,
  408. 'description' => '增强版AI题目生成模板,支持精确的难度和题型分布控制',
  409. 'tags' => 'AI生成,增强版,智能分布'
  410. ]);
  411. if ($result['success'] ?? false) {
  412. Notification::make()
  413. ->title('提示词保存成功')
  414. ->success()
  415. ->send();
  416. } else {
  417. Notification::make()
  418. ->title('保存失败')
  419. ->body($result['message'] ?? '未知错误')
  420. ->danger()
  421. ->send();
  422. }
  423. $this->closePromptModal();
  424. } catch (\Exception $e) {
  425. Notification::make()
  426. ->title('保存异常')
  427. ->body($e->getMessage())
  428. ->danger()
  429. ->send();
  430. }
  431. }
  432. /**
  433. * 删除题目
  434. */
  435. public function deleteQuestion(string $questionCode): void
  436. {
  437. try {
  438. $service = app(QuestionBankService::class);
  439. $result = $service->deleteQuestion($questionCode);
  440. if ($result) {
  441. // 显示成功消息
  442. Notification::make()
  443. ->title('删除成功')
  444. ->body("题目 {$questionCode} 已删除")
  445. ->success()
  446. ->send();
  447. // 延迟1秒后刷新页面,确保用户体验好
  448. $this->dispatch('show-message', [
  449. 'type' => 'success',
  450. 'message' => "题目 {$questionCode} 已删除"
  451. ]);
  452. // 强制刷新页面
  453. $this->dispatch('refresh-page');
  454. } else {
  455. Notification::make()
  456. ->title('删除失败')
  457. ->body("题目 {$questionCode} 不存在或已被删除")
  458. ->warning()
  459. ->send();
  460. }
  461. } catch (\Exception $e) {
  462. Notification::make()
  463. ->title('删除异常')
  464. ->body($e->getMessage())
  465. ->danger()
  466. ->send();
  467. }
  468. }
  469. /**
  470. * 智能搜索
  471. */
  472. #[On('smart-search')]
  473. public function smartSearch(): void
  474. {
  475. Notification::make()
  476. ->title('智能搜索功能')
  477. ->body('请使用搜索框输入关键词')
  478. ->info()
  479. ->send();
  480. }
  481. /**
  482. * 跳转到指定页
  483. */
  484. public function gotoPage(int $page): void
  485. {
  486. $this->currentPage = $page;
  487. }
  488. /**
  489. * 上一页
  490. */
  491. public function previousPage(): void
  492. {
  493. if ($this->currentPage > 1) {
  494. $this->currentPage--;
  495. }
  496. }
  497. /**
  498. * 下一页
  499. */
  500. public function nextPage(): void
  501. {
  502. if ($this->currentPage < ($this->meta['total_pages'] ?? 1)) {
  503. $this->currentPage++;
  504. }
  505. }
  506. /**
  507. * 获取页码数组(用于分页器)
  508. */
  509. public function getPages(): array
  510. {
  511. $totalPages = $this->meta['total_pages'] ?? 1;
  512. $currentPage = $this->currentPage;
  513. $pages = [];
  514. $start = max(1, $currentPage - 2);
  515. $end = min($totalPages, $currentPage + 2);
  516. for ($i = $start; $i <= $end; $i++) {
  517. $pages[] = $i;
  518. }
  519. return $pages;
  520. }
  521. /**
  522. * 头部操作按钮已在视图中直接添加
  523. */
  524. }