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

export type Settings = {
  key?: string;
  version?: string;
  username?: string;
  prefix?: string;
};
interface SettingsStore {
  settings: Settings;
  setSettings: (settings: Settings) => void;
  querySettings: () => Promise<void>;
  mounted: boolean;
  setMounted: (mounted: boolean) => void;
  init: () => Promise<void>;
  updateSettings: (settings: Settings) => void;
}

export const useSettingsStore = create<SettingsStore>((set, get) => ({
  settings: {},
  setSettings: (settings) => set({ settings }),
  mounted: false,
  setMounted: (mounted) => set({ mounted }),
  querySettings: async () => {
    const settings = get().settings;
    const res = await query.post({
      path: 'config',
      key: 'getUploadConfig',
    });
    console.log(res);
    if (res.code === 200) {
      const config = res.data;
      localStorage.setItem('upload-config', JSON.stringify(config));
      set({ settings: config });
      if (JSON.stringify(settings) !== JSON.stringify(config)) {
        set({ mounted: false });
        set({ mounted: true });
      }
    } else {
      toast.error(res.message || '获取配置失败');
    }
  },
  updateSettings: async (settings) => {
    console.log('setinng', settings);
    // const res = await query.post({
    //   path: 'config',
    //   key: 'updateUploadConfig',
    //   data: settings,
    // });
  },
  init: async () => {
    const cacheConfig = localStorage.getItem('upload-config');
    if (cacheConfig) {
      try {
        set({ settings: JSON.parse(cacheConfig), mounted: true });
      } catch (error) {
        toast.error('配置文件损坏');
        localStorage.removeItem('upload-config');
      }
    }
    get().querySettings();
  },
}));
