import {
  addGlobalUncaughtErrorHandler,
  registerMicroApps,
  runAfterFirstMounted,
  setDefaultMountApp,
  start,
} from 'qiankun';

import micorConfig from '../config/micor';
import pkg from '../package.json';
import { FILTER_FOLER_REG } from './utils/constants';

const MICRO_STATUS = {
  NOT_LOADED: "NOT_LOADED",
  LOADING_SOURCE_CODE: "LOADING_SOURCE_CODE",
  NOT_BOOTSTRAPPED: "NOT_BOOTSTRAPPED",
  BOOTSTRAPPING: 'BOOTSTRAPPING',
  NOT_MOUNTED: 'NOT_MOUNTED',
  MOUNTING: 'MOUNTING',
  MOUNTED: 'MOUNTED',
  UPDATING: 'UPDATING',
  UNMOUNTING: 'UNMOUNTING',
  UNLOADING: 'UNLOADING',
  SKIP_BECAUSE_BROKEN: 'SKIP_BECAUSE_BROKEN',
  LOAD_ERROR: 'LOAD_ERROR'
}
export const initMicroApps = loader => {
  const entrys =
    process.env.NODE_ENV !== 'production' ? micorConfig.dev : micorConfig.prod;

  registerMicroApps(
    entrys.map(item => {
      item.loader = loader;
      item.props = {
        emitter: window.share.event,
        baseRoot: item.name,
        globalConfig: JSON.stringify(createStoreage.get('globalConfig') || {}),
        XMLHttpRequest: window.XMLHttpRequest,
      };
      return item;
    }),
    {
      beforeLoad: [
        app => {
          console.log(
            '[LifeCycle] before load %c%s',
            'color: green;',
            app.name,
          );
        },
      ],
      beforeMount: [
        app => {
          // hookRequest()
          // ReactDOM.unmountComponentAtNode(
          //   document.getElementById('subapp-container'),
          // );
          // console.log(
          //   '[LifeCycle] before mount %c%s',
          //   'color: green;',
          //   JSON.stringify(app),
          // );
          // window.share.event.removeAllListeners();
          console.log(
            '[LifeCycle] before mount %c%s',
            'color: green;',
            app.name,
          );
        },
      ],
      afterMount: [
        app => {
          console.log(
            '[LifeCycle] after mount %c%s',
            'color: green;',
            app.name,
          );
          
        },
      ],
      beforeUnmount: [
        app => {
          window.share.event.removeAllListeners('changeRoute');
          console.log(
            '[LifeCycle] after unmount %c%s',
            'color: green;',
            app.name,
          );
        },
      ],
      afterUnmount: [
        app => {
        },
      ],
    },
  );

  defaultApp();
  start({
    sandbox: {
      experimentalStyleIsolation: true,
      loose: true,
    },
    singular: false,
    scopedCSS: true,
    getPublicPath: window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__,
    excludeAssetFilter: url => {
      return (
        url.indexOf('webapi.amap.com') !== -1 ||
        url.indexOf('api.map.baidu.com') !== -1 ||
        url.indexOf('map.baidu.com') !== -1 ||
        url.indexOf('pv.sohu.com') !== -1 ||
        url.indexOf('mt0.google.cn') !== -1 ||
        url.indexOf('mt1.google.cn') !== -1 ||
        url.indexOf('mt2.google.cn') !== -1 ||
        url.indexOf('mt3.google.cn') !== -1
      );
    },
  });
  runAfterFirstMounted(() => {
    console.log('[MainApp] first app mounted');
  });

  addGlobalUncaughtErrorHandler(event => {
    
    const error = event.error;
    const reson = 'Failed to fetch';
    if(error && error.message.indexOf(MICRO_STATUS.LOADING_SOURCE_CODE) && error.message.indexOf(reson)) {
      window.history.pushState({message: '应用服务请求异常，请检查应用配置'}, null, '/civbase/500')
    }
  });
};

export const defaultApp = () => {
  const config = createStoreage.get('globalConfig');
  if (config && config.token) {
    // const startWith = config.homepage ? config.homepage.split('/') : [];
    const basePath = FILTER_FOLER_REG.test(config.homepage)
      ? 'civweb4'
      : 'civweb';
    setDefaultMountApp(
      `/${pkg.name.toLocaleLowerCase()}/${basePath}/?client=${config.client}`,
      //   config.homepage
      //     ? `/${pkg.name.toLocaleLowerCase()}/${basePath}/${config.homepage}`
      //     : `/${pkg.name.toLocaleLowerCase()}/${basePath}/?client=${
      //         window.globalConfig.client
      //       }`,
    );
  }
};
