import React, { useState, useEffect, useCallback } from 'react' import { View, Text, ScrollView, Input, Textarea } from '@tarojs/components' import Taro from '@tarojs/taro' import NavBar from '@/components/NavBar' import Loading from '@/components/common/Loading' import { useUser } from '@/hooks/useUser' import { pageAppApiKey, createAppApiKey, updateAppApiKeyStatus, removeAppApiKey } from '@/api/app/apikey' import { getPageList, maskKey } from '@/utils/devcenter' definePageConfig({ navigationBarTitleText: 'API Key 管理' }) const ApiKeysPage: React.FC = () => { const { isLoggedIn } = useUser() const [loading, setLoading] = useState(true) const [list, setList] = useState([]) const [showModal, setShowModal] = useState(false) const [form, setForm] = useState({ name: '', remark: '' }) const [submitting, setSubmitting] = useState(false) const load = useCallback(async () => { setLoading(true) try { const data = await pageAppApiKey({ page: 1, limit: 50 }) setList(getPageList(data)) } catch (e) { // ignore } finally { setLoading(false) } }, []) useEffect(() => { if (isLoggedIn) load() }, [isLoggedIn, load]) const toggle = async (item: any) => { try { await updateAppApiKeyStatus(item.id, item.status === 0 ? 1 : 0) Taro.showToast({ title: '已更新', icon: 'none' }) load() } catch (e: any) { Taro.showToast({ title: e?.message || '操作失败', icon: 'none' }) } } const remove = (item: any) => { Taro.showModal({ title: '删除密钥', content: '删除后无法恢复,确定删除?', success: async (r) => { if (r.confirm) { try { await removeAppApiKey(item.id) Taro.showToast({ title: '已删除', icon: 'success' }) load() } catch (e: any) { Taro.showToast({ title: e?.message || '删除失败', icon: 'none' }) } } }, }) } const copy = (item: any) => { Taro.setClipboardData({ data: item.apiKey || '' }) } const submit = async () => { if (!form.name.trim()) { Taro.showToast({ title: '请填写名称', icon: 'none' }) return } setSubmitting(true) try { await createAppApiKey({ name: form.name, scopes: 'read,write', remark: form.remark }) Taro.showToast({ title: '创建成功', icon: 'success' }) setShowModal(false) load() } catch (e: any) { Taro.showToast({ title: e?.message || '创建失败', icon: 'none' }) } finally { setSubmitting(false) } } return ( { setForm({ name: '', remark: '' }) setShowModal(true) }} /> {loading ? ( ) : list.length === 0 ? ( 暂无 API Key ) : ( {list.map((item) => ( {item.name} {item.status === 0 ? '正常' : '禁用'} {maskKey(item.apiKey)} copy(item)}> 复制 toggle(item)}> {item.status === 0 ? '禁用' : '启用'} remove(item)}> 删除 ))} )} {showModal && ( 创建 API Key 名称 setForm({ ...form, name: e.detail.value })} /> 备注