import { query } from '@/modules';
import { message } from 'antd';
import { create } from 'zustand';
import { history } from '@/utils/history';
type LoginStore = {
  loading: boolean;
  setLoading: (loading: boolean) => void;
  formData: any;
  setFormData: (formData: any) => void;
  login: () => Promise<void>;
  register: () => Promise<void>;
  isLogin: boolean;
  setIsLogin: (isLogin: boolean) => void;
};
export const useLoginStore = create<LoginStore>((set, get) => {
  return {
    loading: false,
    setLoading: (loading) => set({ loading }),
    formData: {},
    setFormData: (formData) => set({ formData }),
    login: async () => {
      const { formData } = get();
      const { username, password } = formData;
      if (!username || !password) {
        message.error('Please input username and password');
        return;
      }
      set({ loading: true });
      const loaded = message.loading('loading...', 0);
      const res = await query.post({ path: 'user', key: 'login', username, password });
      loaded();
      if (res.code === 200) {
        const { token } = res.data;
        message.success('Success');
        set({ isLogin: true });
        localStorage.setItem('token', token);
        // 跳到某一个页面，更新localStorage
        history.push('/map');
      } else {
        message.error(res.message || 'Request failed');
      }
    },
    register: async () => {
      set({ loading: true });
      const loaded = message.loading('loading...', 0);
      const res = await query.post({ path: 'user', key: 'register' });
      loaded();
      if (res.code === 200) {
        message.success('Success');
        // 跳到某一个页面
        // history.push('/map', {}, true);
      } else {
        message.error(res.message || 'Request failed');
      }
    },
    isLogin: false,
    setIsLogin: (isLogin) => set({ isLogin }),
  };
});
