/*
 * @Author: 赵伟
 * @Date: 2024-06-26 16:37:39
 * @Description: 全局网络请求 Loading
 */

import KFSpin from '@/components/KFSpin';
import { ConfigProvider, SpinProps } from 'antd';
import { globalConfig } from 'antd/es/config-provider';
import zhCN from 'antd/locale/zh_CN';
import { createRoot } from 'react-dom/client';

export class Loading {
  static total = 0;
  static show(props?: SpinProps) {
    Loading.total += 1;
    if (Loading.total > 1) {
      return;
    }
    const container = document.createElement('div');
    container.id = 'loading';
    const rootContainer = document.getElementsByTagName('main')[0];
    rootContainer?.appendChild(container);
    const root = createRoot(container);
    const global = globalConfig();
    let timeoutId: ReturnType<typeof setTimeout>;

    function render(spinProps: SpinProps) {
      clearTimeout(timeoutId);

      timeoutId = setTimeout(() => {
        const rootPrefixCls = global.getPrefixCls();
        const iconPrefixCls = global.getIconPrefixCls();
        const theme = global.getTheme();
        const dom = <KFSpin {...spinProps} />;

        root.render(
          <ConfigProvider
            prefixCls={rootPrefixCls}
            iconPrefixCls={iconPrefixCls}
            theme={theme}
            locale={zhCN}
          >
            {global.holderRender ? global.holderRender(dom) : dom}
          </ConfigProvider>,
        );
      });
    }

    render({ size: 'large', ...props, spinning: true });
  }

  static hide(force: boolean = false) {
    Loading.total -= 1;
    if (Loading.total <= 0 || force) {
      Loading.total = 0;
      const rootContainer = document.getElementsByTagName('main')[0];
      const container = document.getElementById('loading');
      if (container) {
        rootContainer?.removeChild(container);
      }
    }
  }
}

export default Loading;
