import { create } from 'zustand';
import { query } from '@/modules/query';
import { toast } from 'react-toastify';
import { QueryConfig } from '@kevisual/query-config';

export const queryConfig = new QueryConfig({ query: query as any });

interface ConfigStore {
  list: any[];
  getConfigList: () => Promise<void>;
  updateData: (data: any, opts?: { refresh?: boolean }) => Promise<any>;
  showEdit: boolean;
  setShowEdit: (showEdit: boolean) => void;
  formData: any;
  setFormData: (formData: any) => void;
  deleteConfig: (id: string) => Promise<void>;
  detectConfig: () => Promise<void>;
  onOpenKey: (key: string) => Promise<void>;
}

export const useConfigStore = create<ConfigStore>((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);
    if (res.code === 200) {
      const data = res.data;
      setFormData(data);
      setShowEdit(true);
      getConfigList();
    } else {
      console.log(res);
      toast.error('获取配置失败');
    }
  },
}));
