import React, { useState, useEffect } from 'react';
import { initialization, queryOrganizationsList, queryPlacesList, queryUserDevice, authFormat } from './utils';
import { BaseStore } from '@zenview/micro-basic-library';
import { logger } from '@zenview/micro-utils';
import './index.less';

function InitialRequest({ children, Spin, customInitialization, mode = 'ext' }) {
  const [isInit, setIsInit] = useState(false);
  useEffect(() => {
    const initAction = mode === 'replace' && customInitialization ? customInitialization : initialization;
    initAction()
      .then((res) => {
        if (mode !== 'replace') {
          const { userPrivileges, allPrivileges, centerPrivileges, centerInfo, systemInfo, userInfo } = res;
          const userRoles = (userPrivileges.data || []).map((item) => item.functionCodes).flat();
          BaseStore.app.updateUserInfo(userInfo);
          BaseStore.app.updateAppInfo(centerInfo.data);
          BaseStore.app.updateSystemConfig(systemInfo.data);
          const userAuth = [].concat(authFormat(userRoles, centerPrivileges.data, userInfo.userType));
          const globalAuth = [].concat(authFormat([], allPrivileges.data, userInfo.userType));
          BaseStore.auth.initAuthData([...userAuth, ...globalAuth]);
          queryOrganizationsList().then((res) => BaseStore.org.initSetOrgData(res.data || []));
          queryPlacesList().then((res) => BaseStore.place.initSetPlaceData(...res));
          queryUserDevice().then((devices) => BaseStore.device.initSetDevices(devices));
        }
      })
      .then(() => {
        if (mode === 'ext' && customInitialization) {
          return customInitialization();
        }
      })
      .then(() => {
        setIsInit(true);
      })
      .catch((e) => {
        logger.error('接口初始化失败！', e);
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return isInit ? children : Spin ? <Spin spinning={true} /> : null;
}

export default InitialRequest;
