import { query } from '@/modules/query';
import { message } from 'antd';
import { create } from 'zustand';

type Me = {
  id?: string;
  username?: string;
  needChangePassword?: boolean;
  role?: string;
  description?: string;
  type?: 'user' | 'org';
  orgs?: string[];
  avatar?: string;
};
export type LayoutStore = {
  open: boolean;
  setOpen: (open: boolean) => void;
  me: Me;
  setMe: (me: Me) => void;
  getMe: () => Promise<void>;
  openUser: boolean;
  setOpenUser: (openUser: boolean) => void;
  switchOrg: (username?: string, type?: 'user' | 'org') => Promise<void>;
};
export const useLayoutStore = create<LayoutStore>((set) => ({
  open: false,
  setOpen: (open) => set({ open }),
  me: {},
  setMe: (me) => set({ me }),
  getMe: async () => {
    const res = await query.post({
      path: 'user',
      key: 'me',
    });
    if (res.code === 200) {
      set({ me: res.data });
    }
  },
  openUser: false,
  setOpenUser: (openUser) => set({ openUser }),
  switchOrg: async (username?: string, type?: string) => {
    const res = await query.post({
      path: 'user',
      key: 'switchOrg',
      data: {
        username,
        type,
      },
    });
    if (res.code === 200) {
      const { token } = res.data;
      query.saveToken(token);
      message.success('Switch success');
      window.location.reload();
    } else {
      message.error(res.message || 'Request failed');
    }
  },
}));
