import {UserLoginData} from '@models';
import {QUERY_CLIENT, USER_TOKEN_STORAGE} from '@utils';
import {startTransition} from 'react';
import {createStore} from 'zustand/vanilla';
import {menuStore} from './menu';

type UserStoreState = UserLoginData;

type UserStoreAction = {
  init(data: UserLoginData): void;
  logout(): void;
  setMenu(menus: string[]): void;
};

function defaultValue(): UserStoreState {
  return {
    id: 0,
    realName: '',
    token: '',
    userName: '',
    menu: null,
    department: '',
    role: '',
  };
}

export const userStore = createStore<UserStoreState & UserStoreAction>(
  function (set) {
    // 刷新时不会丢掉用户状态
    const sessionData = sessionStorage.getItem(USER_TOKEN_STORAGE);
    const initValue = sessionData
      ? (JSON.parse(sessionData) as UserLoginData)
      : defaultValue();

    return {
      ...initValue,
      init(data) {
        set(data);
      },
      logout() {
        // 清除用户缓存
        sessionStorage.removeItem(USER_TOKEN_STORAGE);
        set(defaultValue());

        startTransition(function () {
          // 清除请求缓存
          QUERY_CLIENT.clear();

          // 清除菜单缓存
          const {clear} = menuStore.getState();
          clear();
        });
      },
      setMenu(menus) {
        set({menu: menus.join(',') + ','});
      },
    };
  },
);
