import {
  addGlobalUncaughtErrorHandler,
  initGlobalState,
  registerMicroApps,
  runAfterFirstMounted,
  setDefaultMountApp,
  start,
} from 'qiankun';
import 'kit_logger';
import micorConfig, { genActiveRule } from '../config/micor';
import pkg from '../package.json';
import { FILTER_FOLER_REG } from './utils/constants';
import { actionCreators } from './containers/App/store';
// eslint-disable-next-line no-undef
const Logger = logger('micro');
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, store) => {
  /* eslint-disable */
  const config = createStoreage.get('globalConfig');
  const application = config.products || [];
  const entrys =
    process.env.NODE_ENV !== 'production'
      ? micorConfig.dev
      : (application && Array.isArray(application) && application.length > 0 ) ? application.map(item => {
          item.name = item.PackageName;
          item.entry = item.RouteUrl.replace(
            // eslint-disable-next-line no-template-curly-in-string
            'localhost:${port}',
            window.location.host,
          );
          item.container = '#micro-container';
          item.activeRule = genActiveRule(`/civbase/${item.PackageName}`);
          item.props = JSON.parse(item.DefaultSetting);
          return item;
        }): micorConfig.prod;

  registerMicroApps(
    entrys.map(item => {
      item.loader = loader;
      item.props = {
        emitter: window.share.event,
        baseRoot: item.name,
        // eslint-disable-next-line no-undef
        globalConfig: createStoreage.get('globalConfig'),
        XMLHttpRequest: window.XMLHttpRequest,
      };
      return item;
    }),
    {
      beforeLoad: [
        app => {
          store.dispatch(actionCreators.updateMicroMounted(true));
          Logger.info('[LifeCycle] before load %c%s');
        },
      ],
      beforeMount: [
        app => {
<<<<<<< HEAD
          store.dispatch(actionCreators.updateMicroMounted(false));
=======
>>>>>>> 0e8f6915ac6e5dc6a04d3511197675755ca3bc00
          Logger.info(`[LifeCycle] before mount %c%s ${app.name}`);
        },
      ],
      afterMount: [
        app => {
          store.dispatch(actionCreators.updateMicroMounted(false));
          Logger.info(`[LifeCycle] after mount %c%s ${app.name}`);
        },
      ],
      beforeUnmount: [
        app => {
          window.share.event.removeAllListeners('changeRoute');
          Logger.info(`[LifeCycle] after unmount %c%s ${app.name}`);
        },
      ],
      afterUnmount: [app => {}],
    },
  );
  const { setGlobalState } = initGlobalState({
    // eslint-disable-next-line no-undef
    globalConfig: createStoreage.get('globalConfig'),
  });
  setGlobalState({
    // eslint-disable-next-line no-undef
    globalConfig: createStoreage.get('globalConfig'),
  });
  start({
    sandbox: {
      experimentalStyleIsolation: true,
      loose: true,
    },
    singular: true,
    scopedCSS: true,
    // prefetch: 'all',
    // eslint-disable-next-line no-underscore-dangle
    getPublicPath: window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__,
    excludeAssetFilter: url =>
      url.indexOf('framework/amap/AMap.UI') !== -1 ||
      url.indexOf('framework/amap/init.js') !== -1 ||
      url.indexOf('configuration/js') !== -1 ||
      url.indexOf('framework/three.js') !== -1 ||
      url.indexOf('threedimensional/frameworkthree') !== -1 ||
      url.indexOf('iframe/Civ3DLLab/js') !== -1 ||
      url.indexOf('framework/jquery/gridify-min.js') !== -1 ||
      url.indexOf('framework/jquery/gridify.qrcode.js') !== -1 ||
      url.indexOf('echarts') !== -1 ||
      url.indexOf('lbs.amap.com') !== -1 ||
      url.indexOf('restapi.amap.com') !== -1 ||
      url.indexOf('webapi.amap.com') !== -1 ||
      url.indexOf('webapi.amap.com/count') !== -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 ||
      url.indexOf('hm.baidu.com') !== -1 ||
      url.indexOf('https://maponline0.bdimg.com') !== -1 ||
      url.indexOf('https://maponline1.bdimg.com') !== -1 ||
      url.indexOf('https://maponline2.bdimg.com') !== -1 ||
      url.indexOf('https://maponline3.bdimg.com') !== -1 ||
      url.indexOf('https://api.map.baidu.com/getscript') !== -1,
  });
  runAfterFirstMounted(() => {
    Logger.info('[MainApp] first app mounted');
  });
  // eslint-disable-next-line no-use-before-define
  defaultApp();
  addGlobalUncaughtErrorHandler(event => {
    const { error } = event;
    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 = () => {
  // eslint-disable-next-line no-undef
  const config = createStoreage.get('globalConfig');
  if (config && config.token) {
    // const startWith = config.homepage ? config.homepage.split('/') : [];
    // console.log(findPathByLeafId(config.homepage,  '', 'url'))
    const basePath =
      config.homepage !== '' && FILTER_FOLER_REG.test(config.homepage)
        ? 'civweb4'
        : 'civweb4';
    const defaultURL =
      config.homepage === ''
        ? `/${pkg.name.toLocaleLowerCase()}/${basePath}?client=${config.client}`
        : `${basePath}/${config.homepage}`;
    setDefaultMountApp(defaultURL);
  }
};
