"use client"; import { closestCenter, DndContext, KeyboardSensor, MouseSensor, TouchSensor, useSensor, useSensors, type DragEndEvent, } from "@dnd-kit/core"; import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy, } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; import { GripVerticalIcon, MoreHorizontalIcon, PlusIcon, RefreshCwIcon, SearchIcon, Trash2Icon } from "lucide-react"; import { useCallback, useEffect, useState, type CSSProperties } from "react"; import { toast } from "sonner"; import { ListPagination } from "@/components/list-pagination"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { ButtonGroup } from "@/components/ui/button-group"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Input } from "@/components/ui/input"; import { Switch } from "@/components/ui/switch"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { createAIConfig, deleteAIConfig, fetchAIConfigs, updateAIConfig, updateAIConfigSort, updateAIConfigStatus, type AIConfig, type CreateAIConfigPayload, type PageResult, } from "@/lib/api/admin"; import { AIModelType, AIModelTypeLabels, AIProvider, AIProviderLabels, Status, StatusLabels } from "@/lib/generated/enums"; import { getEnumLabel, getEnumOptions } from "@/lib/enums"; import { cn } from "@/lib/utils"; import { EditDialog } from "./_components/edit"; import { OptionCombobox } from "./_components/option-combobox"; const listStatusOptions = [ { value: "all", label: "全部状态" }, ...getEnumOptions(StatusLabels).map((option) => ({ value: String(option.value), label: option.label, })), ]; const providerFilterOptions = [ { value: "all", label: "全部供应商" }, ...getEnumOptions(AIProviderLabels).map((option) => ({ value: String(option.value), label: option.label, })), ]; const modelTypeFilterOptions = [ { value: "all", label: "全部类型" }, ...getEnumOptions(AIModelTypeLabels).map((option) => ({ value: String(option.value), label: option.label, })), ]; function maskAPIKey(value: string) { const text = value.trim(); if (!text) { return "-"; } if (text.length <= 8) { return "****"; } return `${text.slice(0, 4)}****${text.slice(-4)}`; } type SortableAIConfigRowProps = { item: AIConfig; disabled: boolean; actionLoadingId: number | null; openEditDialog: (item: AIConfig) => void; handleToggleStatus: (item: AIConfig) => void; handleDelete: (item: AIConfig) => void; }; function SortableAIConfigRow({ item, disabled, actionLoadingId, openEditDialog, handleToggleStatus, handleDelete, }: SortableAIConfigRowProps) { const { attributes, listeners, setNodeRef, transform, transition, isDragging, } = useSortable({ id: item.id, disabled, }); const style: CSSProperties = { transform: CSS.Transform.toString(transform), transition, }; return ( {item.name} {getEnumLabel( AIProviderLabels, item.provider as AIProvider, )} {getEnumLabel( AIModelTypeLabels, item.modelType as AIModelType, )} {item.modelName} {item.dimension > 0 && ( {item.dimension} 维 )} {item.baseUrl} Key: {maskAPIKey(item.apiKey)} 上下文 {item.maxContextTokens || 0} 输出 {item.maxOutputTokens || 0} 超时 {item.timeoutMs}ms / 重试 {item.maxRetryCount} RPM {item.rpmLimit || 0} / TPM {item.tpmLimit || 0} void handleToggleStatus(item)} aria-label={`${item.name} 状态切换`} /> {getEnumLabel( StatusLabels, item.status as keyof typeof StatusLabels, )} openEditDialog(item)} > 编辑 } aria-label={`更多操作 ${item.name}`} > void handleDelete(item)} className="text-destructive focus:text-destructive" > {item.status === Status.Ok ? "启用中不可删" : actionLoadingId === item.id ? "删除中..." : "删除"} ); } export default function DashboardAIConfigsPage() { const [keywordInput, setKeywordInput] = useState(""); const [statusFilterInput, setStatusFilterInput] = useState("all"); const [providerFilterInput, setProviderFilterInput] = useState("all"); const [modelTypeFilterInput, setModelTypeFilterInput] = useState("all"); const [keyword, setKeyword] = useState(""); const [statusFilter, setStatusFilter] = useState("all"); const [providerFilter, setProviderFilter] = useState("all"); const [modelTypeFilter, setModelTypeFilter] = useState("all"); const [page, setPage] = useState(1); const [limit, setLimit] = useState(20); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [actionLoadingId, setActionLoadingId] = useState(null); const [sorting, setSorting] = useState(false); const [dialogOpen, setDialogOpen] = useState(false); const [editingItem, setEditingItem] = useState(null); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); const [deletingItem, setDeletingItem] = useState(null); const [result, setResult] = useState>({ results: [], page: { page: 1, limit: 20, total: 0 }, }); const sensors = useSensors( useSensor(MouseSensor, { activationConstraint: { distance: 8 }, }), useSensor(TouchSensor, { activationConstraint: { delay: 150, tolerance: 8 }, }), useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates, }), ); const loadData = useCallback(async () => { setLoading(true); try { const data = await fetchAIConfigs({ name: keyword.trim() || undefined, status: statusFilter === "all" ? undefined : statusFilter, provider: providerFilter === "all" ? undefined : providerFilter, modelType: modelTypeFilter === "all" ? undefined : modelTypeFilter, page, limit, }); setResult(data); } catch (error) { toast.error(error instanceof Error ? error.message : "加载 AI 配置失败"); } finally { setLoading(false); } }, [keyword, statusFilter, providerFilter, modelTypeFilter, page, limit]); useEffect(() => { void loadData(); }, [loadData]); function applyFilters() { setKeyword(keywordInput); setStatusFilter(statusFilterInput); setProviderFilter(providerFilterInput); setModelTypeFilter(modelTypeFilterInput); setPage(1); } function handleFilterKeyDown(event: React.KeyboardEvent) { if (event.key !== "Enter") { return; } event.preventDefault(); applyFilters(); } function handlePageChange(nextPage: number) { if (nextPage < 1 || nextPage === page) { return; } setPage(nextPage); } function handleLimitChange(nextLimit: number) { if (nextLimit <= 0 || nextLimit === limit) { return; } setLimit(nextLimit); setPage(1); } function openCreateDialog() { setEditingItem(null); setDialogOpen(true); } function openEditDialog(item: AIConfig) { setEditingItem(item); setDialogOpen(true); } function handleDialogOpenChange(open: boolean) { if (saving) { return; } if (!open) { setEditingItem(null); } setDialogOpen(open); } async function handleSubmit(payload: CreateAIConfigPayload) { if (saving) { return; } setSaving(true); try { if (editingItem) { await updateAIConfig({ id: editingItem.id, ...payload }); toast.success(`已更新 AI 配置:${editingItem.name}`); } else { await createAIConfig(payload); toast.success(`已创建 AI 配置:${payload.name}`); } setDialogOpen(false); setEditingItem(null); await loadData(); } catch (error) { toast.error(error instanceof Error ? error.message : "保存 AI 配置失败"); } finally { setSaving(false); } } async function handleToggleStatus(item: AIConfig) { setActionLoadingId(item.id); try { const nextStatus = item.status === Status.Ok ? Status.Disabled : Status.Ok; await updateAIConfigStatus(item.id, nextStatus); toast.success( `已${nextStatus === Status.Ok ? "启用" : "禁用"}:${item.name}`, ); await loadData(); } catch (error) { toast.error(error instanceof Error ? error.message : "更新状态失败"); } finally { setActionLoadingId(null); } } async function handleDelete(item: AIConfig) { if (item.status === Status.Ok) { toast.error("启用中的 AI 配置不允许删除"); return; } setDeletingItem(item); setDeleteDialogOpen(true); } async function handleConfirmDelete() { if (!deletingItem) { return; } const item = deletingItem; setActionLoadingId(item.id); try { await deleteAIConfig(item.id); toast.success(`已删除 AI 配置:${item.name}`); setDeleteDialogOpen(false); setDeletingItem(null); await loadData(); } catch (error) { toast.error(error instanceof Error ? error.message : "删除 AI 配置失败"); } finally { setActionLoadingId(null); } } async function handleDragEnd(event: DragEndEvent) { const { active, over } = event; if (!over || active.id === over.id || sorting) { return; } const previousResults = result.results; const oldIndex = previousResults.findIndex((item) => item.id === active.id); const newIndex = previousResults.findIndex((item) => item.id === over.id); if (oldIndex < 0 || newIndex < 0) { return; } const nextResults = arrayMove(previousResults, oldIndex, newIndex); setResult((current) => ({ ...current, results: nextResults, })); setSorting(true); try { await updateAIConfigSort(nextResults.map((item) => item.id)); toast.success("AI 配置排序已更新"); await loadData(); } catch (error) { setResult((current) => ({ ...current, results: previousResults, })); toast.error(error instanceof Error ? error.message : "更新排序失败"); } finally { setSorting(false); } } return ( <> setKeywordInput(event.target.value)} onKeyDown={handleFilterKeyDown} placeholder="按配置名称筛选" className="pl-9" /> 查询 void loadData()} disabled={loading} > 刷新列表 新建 配置 供应商 模型 接入信息 限制 状态 操作 {loading ? ( 正在加载 AI 配置... ) : result.results.length === 0 ? ( 暂无 AI 配置数据 ) : ( item.id)} strategy={verticalListSortingStrategy} > {result.results.map((item) => ( ))} )} { if (actionLoadingId) { return; } setDeleteDialogOpen(open); if (!open) { setDeletingItem(null); } }} > 确认删除 AI 配置 {deletingItem ? `确认删除“${deletingItem.name}”吗?此操作不可撤销。` : "此操作不可撤销。"} { setDeleteDialogOpen(false); setDeletingItem(null); }} > 取消 void handleConfirmDelete()} > {actionLoadingId ? "删除中..." : "确认删除"} > ); }