import { create } from 'zustand'; import { query } from '@/modules/query'; import { toast } from 'sonner'; import { QueryConfig, Config } from '@kevisual/api/config'; export const queryConfig = new QueryConfig({ query: query as any }); interface ConfigStore { list: any[]; getConfigList: () => Promise; updateData: (data: any, opts?: { refresh?: boolean }) => Promise; showEdit: boolean; setShowEdit: (showEdit: boolean) => void; formData: any; setFormData: (formData: any) => void; deleteConfig: (id: string) => Promise; detectConfig: () => Promise; onOpenKey: (key: string) => Promise; getEnv: () => Promise; updateEnv: (data: Config) => Promise; envData: Config; setEnvData: (envData: Config) => void; } export const useConfigStore = create((set, get) => ({ list: [], getConfigList: async () => { const res = await queryConfig.listConfig(); if (res.code === 200) { set({ list: res.data?.list || [] }); } }, updateData: async (data: any, opts?: { refresh?: boolean }) => { const res = await queryConfig.updateConfig(data); if (res.code === 200) { get().setFormData(res.data); if (opts?.refresh ?? true) { get().getConfigList(); } toast.success('保存成功'); } else { toast.error('保存失败'); } return res; }, showEdit: false, setShowEdit: (showEdit: boolean) => set({ showEdit }), formData: {}, setFormData: (formData: any) => set({ formData }), deleteConfig: async (id: string) => { const res = await queryConfig.deleteConfig({ id }); if (res.code === 200) { get().getConfigList(); toast.success('删除成功'); } else { toast.error('删除失败'); } }, detectConfig: async () => { const res = await queryConfig.detectConfig(); if (res.code === 200) { const data = res?.data?.updateList || []; console.log(data); toast.success('检测成功'); } else { toast.error('检测失败'); } }, onOpenKey: async (key: string) => { const { setFormData, setShowEdit, getConfigList } = get(); const res = await queryConfig.getConfigByKey(key as any); if (res.code === 200) { const data = res.data; setFormData(data); setShowEdit(true); getConfigList(); } else { console.log(res); toast.error('获取配置失败'); } }, getEnv: async () => { const res = await queryConfig.getByKey('env.json'); if (res.code === 200) { const data = res.data; console.log(data); set({ envData: data }); } else { console.log(res); toast.error('获取失败'); } }, updateEnv: async (data: any) => { const res = await queryConfig.updateConfig({ key: 'env.json', ...data }); if (res.code === 200) { toast.success('更新成功'); } else { console.log(res); toast.error('更新失败'); } }, envData: {}, setEnvData: (envData: any) => set({ envData }), }));