import { useLatest } from 'ahooks';
import { useState } from 'react';
import { useWillMount } from '../useWillMount';
import { StoreManager } from '@/ObserverManagers';

// 模拟在组件渲染之前创建store实例
export const useCreateStore = <T = any,>(
  createStore: () => any,
  unitFlag: boolean,
  key: string,
) => {
  const [orderStore, setStore] = useState<T>();
  const latestOrder = useLatest(orderStore);

  useWillMount(() => {
    latestOrder.current =
      !unitFlag || !StoreManager.check(key)
        ? createStore()
        : ((StoreManager.check(key) as unknown) as T);

    if (!!unitFlag) {
      StoreManager.setStore(key, latestOrder.current);
    }

    setStore(latestOrder.current);
  });

  return { store: latestOrder.current, setStore };
};
