import { create } from 'zustand';
import { query } from '@/modules';
import { message } from '@/modules/message';
type UserAppStore = {
  showEdit: boolean;
  setShowEdit: (showEdit: boolean) => void;
  formData: any;
  setFormData: (formData: any) => void;
  loading: boolean;
  setLoading: (loading: boolean) => void;
  list: any[];
  getList: () => Promise<void>;
  updateData: (data: any) => Promise<void>;
  deleteData: (id: string) => Promise<void>;
  showShareEdit: boolean;
  setShowShareEdit: (showShareEdit: boolean) => void;
  userApp: any;
  setUserApp: (userApp: any) => void;
  getUserApp: (id: string) => Promise<void>;
};
export const useUserAppStore = create<UserAppStore>((set, get) => {
  return {
    showEdit: false,
    setShowEdit: (showEdit) => set({ showEdit }),
    formData: {},
    setFormData: (formData) => set({ formData }),
    loading: false,
    setLoading: (loading) => set({ loading }),
    list: [],
    getList: async () => {
      set({ loading: true });

      const res = await query.post({
        path: 'user-app',
        key: 'list',
      });
      set({ loading: false });
      if (res.code === 200) {
        set({ list: res.data });
      } else {
        message.error(res.message || 'Request failed');
      }
    },
    updateData: async (data) => {
      const { getList } = get();
      const res = await query.post({
        path: 'user-app',
        key: 'update',
        data,
      });
      if (res.code === 200) {
        message.success('Success');
        set({ showEdit: false, showShareEdit: false, formData: res.data });
        getList();
      } else {
        message.error(res.message || 'Request failed');
      }
    },
    deleteData: async (id) => {
      const { getList } = get();
      const res = await query.post({
        path: 'user-app',
        key: 'delete',
        id,
      });
      if (res.code === 200) {
        getList();
        message.success('Success');
      } else {
        message.error(res.message || 'Request failed');
      }
    },
    showShareEdit: false,
    setShowShareEdit: (showShareEdit) => set({ showShareEdit }),
    userApp: {},
    setUserApp: (userApp) => set({ userApp }),
    getUserApp: async (id) => {
      set({ userApp: null });
      const res = await query.post({
        path: 'user-app',
        key: 'get',
        id,
      });
      if (res.code === 200) {
        set({ userApp: res.data });
      } else {
        message.error(res.message || 'Request failed');
      }
    },
  };
});
