QuestionManagement.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  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. // 分析错误类型并提供解决建议
  331. $suggestion = $this->getErrorSuggestion($error);
  332. Notification::make()
  333. ->title('生成失败')
  334. ->body($error . ($suggestion ? "\n\n建议:{$suggestion}" : ''))
  335. ->danger()
  336. ->persistent() // 让通知持续显示,用户需要手动关闭
  337. ->actions([
  338. \Filament\Notifications\Actions\Action::make('retry')
  339. ->label('重试')
  340. ->color('primary')
  341. ->emit('retryGeneration', [$this->generateKpCode, $this->selectedSkills, $this->questionCount]),
  342. \Filament\Notifications\Actions\Action::make('dismiss')
  343. ->label('关闭')
  344. ->color('gray'),
  345. ])
  346. ->send();
  347. }
  348. // 重置任务状态
  349. $this->currentTaskId = null;
  350. $this->currentTaskStatus = null;
  351. $this->currentTaskProgress = 0;
  352. $this->currentTaskMessage = null;
  353. } else {
  354. // 继续轮询
  355. $this->dispatch('$refresh');
  356. $this->dispatch('poll-task');
  357. }
  358. }
  359. } catch (\Exception $e) {
  360. $this->isGenerating = false;
  361. Notification::make()
  362. ->title('查询任务状态失败')
  363. ->body($e->getMessage())
  364. ->danger()
  365. ->send();
  366. }
  367. }
  368. /**
  369. * 获取任务状态消息
  370. */
  371. private function getTaskStatusMessage(array $taskStatus): string
  372. {
  373. $status = $taskStatus['status'] ?? 'unknown';
  374. $progress = $taskStatus['progress'] ?? 0;
  375. return match ($status) {
  376. 'pending' => '任务已创建,等待开始...',
  377. 'processing' => "正在生成题目... {$progress}%",
  378. 'completed' => '生成完成',
  379. 'failed' => '生成失败',
  380. default => '未知状态',
  381. };
  382. }
  383. /**
  384. * 取消生成任务
  385. */
  386. #[On('cancel-generate')]
  387. public function cancelGenerate(): void
  388. {
  389. $this->isGenerating = false;
  390. $this->currentTaskId = null;
  391. $this->currentTaskStatus = null;
  392. $this->currentTaskProgress = 0;
  393. $this->currentTaskMessage = null;
  394. Notification::make()
  395. ->title('已取消生成任务')
  396. ->warning()
  397. ->send();
  398. }
  399. /**
  400. * 保存提示词
  401. */
  402. #[On('save-prompt')]
  403. public function savePrompt(): void
  404. {
  405. if (!$this->promptTemplate) {
  406. Notification::make()
  407. ->title('提示词不能为空')
  408. ->danger()
  409. ->send();
  410. return;
  411. }
  412. try {
  413. $service = app(PromptService::class);
  414. $result = $service->savePrompt([
  415. 'template_name' => 'AI题目生成_增强版',
  416. 'template_type' => '题目生成',
  417. 'template_content' => $this->promptTemplate,
  418. 'version' => 2,
  419. 'is_active' => true,
  420. 'description' => '增强版AI题目生成模板,支持精确的难度和题型分布控制',
  421. 'tags' => 'AI生成,增强版,智能分布'
  422. ]);
  423. if ($result['success'] ?? false) {
  424. Notification::make()
  425. ->title('提示词保存成功')
  426. ->success()
  427. ->send();
  428. } else {
  429. Notification::make()
  430. ->title('保存失败')
  431. ->body($result['message'] ?? '未知错误')
  432. ->danger()
  433. ->send();
  434. }
  435. $this->closePromptModal();
  436. } catch (\Exception $e) {
  437. Notification::make()
  438. ->title('保存异常')
  439. ->body($e->getMessage())
  440. ->danger()
  441. ->send();
  442. }
  443. }
  444. /**
  445. * 删除题目
  446. */
  447. public function deleteQuestion(string $questionCode): void
  448. {
  449. try {
  450. $service = app(QuestionBankService::class);
  451. $result = $service->deleteQuestion($questionCode);
  452. if ($result) {
  453. // 显示成功消息
  454. Notification::make()
  455. ->title('删除成功')
  456. ->body("题目 {$questionCode} 已删除")
  457. ->success()
  458. ->send();
  459. // 延迟1秒后刷新页面,确保用户体验好
  460. $this->dispatch('show-message', [
  461. 'type' => 'success',
  462. 'message' => "题目 {$questionCode} 已删除"
  463. ]);
  464. // 强制刷新页面
  465. $this->dispatch('refresh-page');
  466. } else {
  467. Notification::make()
  468. ->title('删除失败')
  469. ->body("题目 {$questionCode} 不存在或已被删除")
  470. ->warning()
  471. ->send();
  472. }
  473. } catch (\Exception $e) {
  474. Notification::make()
  475. ->title('删除异常')
  476. ->body($e->getMessage())
  477. ->danger()
  478. ->send();
  479. }
  480. }
  481. /**
  482. * 智能搜索
  483. */
  484. #[On('smart-search')]
  485. public function smartSearch(): void
  486. {
  487. Notification::make()
  488. ->title('智能搜索功能')
  489. ->body('请使用搜索框输入关键词')
  490. ->info()
  491. ->send();
  492. }
  493. /**
  494. * 跳转到指定页
  495. */
  496. public function gotoPage(int $page): void
  497. {
  498. $this->currentPage = $page;
  499. }
  500. /**
  501. * 上一页
  502. */
  503. public function previousPage(): void
  504. {
  505. if ($this->currentPage > 1) {
  506. $this->currentPage--;
  507. }
  508. }
  509. /**
  510. * 下一页
  511. */
  512. public function nextPage(): void
  513. {
  514. if ($this->currentPage < ($this->meta['total_pages'] ?? 1)) {
  515. $this->currentPage++;
  516. }
  517. }
  518. /**
  519. * 获取页码数组(用于分页器)
  520. */
  521. public function getPages(): array
  522. {
  523. $totalPages = $this->meta['total_pages'] ?? 1;
  524. $currentPage = $this->currentPage;
  525. $pages = [];
  526. $start = max(1, $currentPage - 2);
  527. $end = min($totalPages, $currentPage + 2);
  528. for ($i = $start; $i <= $end; $i++) {
  529. $pages[] = $i;
  530. }
  531. return $pages;
  532. }
  533. /**
  534. * 重置缓存数据
  535. */
  536. public function resetCache(): void
  537. {
  538. // 重置分页参数
  539. $this->currentPage = 1;
  540. $this->search = null;
  541. $this->selectedKpCode = null;
  542. $selectedDifficulty = null;
  543. // 重置生成的题目缓存数据
  544. $this->resetQuestionsCache();
  545. // 强制刷新Computed属性
  546. unset($this->questions);
  547. unset($this->meta);
  548. }
  549. /**
  550. * 重置题目缓存
  551. */
  552. private function resetQuestionsCache(): void
  553. {
  554. // 这里可以根据需要添加具体的缓存清理逻辑
  555. // 例如:清除任何本地存储的缓存、Redis缓存等
  556. // 目前简单重置计算属性即可
  557. }
  558. /**
  559. * 获取错误解决建议
  560. */
  561. private function getErrorSuggestion(string $error): string
  562. {
  563. if (str_contains($error, 'peer closed connection') || str_contains($error, 'incomplete chunked read')) {
  564. return '网络连接不稳定,系统已自动重试。如果问题持续,请稍后再试或减少生成题目数量。';
  565. }
  566. if (str_contains($error, 'Authentication Fails') || str_contains($error, 'invalid api key')) {
  567. return 'API密钥认证失败,请检查DeepSeek API密钥配置。';
  568. }
  569. if (str_contains($error, 'timeout') || str_contains($error, '超时')) {
  570. return '请求超时,建议减少题目数量或稍后再试。';
  571. }
  572. if (str_contains($error, 'rate limit') || str_contains($error, 'too many requests')) {
  573. return 'API调用频率限制,请稍后再试。';
  574. }
  575. if (str_contains($error, 'insufficient quota') || str_contains($error, 'balance')) {
  576. return 'API账户余额不足,请充值后重试。';
  577. }
  578. return '请检查网络连接或稍后再试,如问题持续请联系技术支持。';
  579. }
  580. /**
  581. * 重试生成
  582. */
  583. #[On('retryGeneration')]
  584. public function retryGeneration(string $kpCode, array $skills, int $count): void
  585. {
  586. $this->generateKpCode = $kpCode;
  587. $this->selectedSkills = $skills;
  588. $this->questionCount = min($count, 50); // 重试时限制题目数量
  589. Notification::make()
  590. ->title('准备重试')
  591. ->body("正在为知识点 {$kpCode} 重新生成 {$this->questionCount} 道题目...")
  592. ->info()
  593. ->send();
  594. // 延迟2秒后开始重试,避免频率限制
  595. $this->js('setTimeout(() => { $wire.dispatch("execute-generate") }, 2000)');
  596. }
  597. /**
  598. * 头部操作按钮已在视图中直接添加
  599. */
  600. }