import React, { useRef, useEffect } from 'react';
import { loadMicroApp } from 'qiankun';
import { logger } from '@zenview/micro-utils';
import { getMicroConfig } from './utils';
import './index.less';

const excludeCssSandBox = ['login', 'portalGateway', 'userTools'];

function LoaderApp({ appConfig, appProps, style }) {
  const domRef = useRef(null);
  const microAppRef = useRef(null);

  useEffect(() => {
    const config = getMicroConfig(appConfig, appProps, domRef.current);
    if (!config) {
      logger.debug('微应用不存在', 'config ->', appConfig, 'appProps ->', appProps);
      return;
    }
    microAppRef.current = loadMicroApp(config, { sandbox: { strictStyleIsolation: !excludeCssSandBox.includes(config.name), experimentalStyleIsolation: true } });
    return () => {
      if (microAppRef.current && microAppRef.current.getStatus() === 'MOUNTED') {
        try {
          microAppRef.current.unmount();
        } catch (error) {
          logger.debug(error);
        }
      }
      microAppRef.current = null;
      logger.debug('微应用卸载', 'config ->', appConfig, 'appProps ->', appProps);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return <main ref={domRef} className="loaded-app-layout" style={style}></main>;
}

export default React.memo(LoaderApp);
