import '!file-loader?name=[name].[ext]!./images/favicon.ico';
import './global.less';
import '@babel/polyfill';
import 'animate.css/animate.css';
import 'antd/dist/antd.less';
import 'file-loader?name=.htaccess!./.htaccess'; // eslint-disable-line import/extensions
import 'kit_utils/lib/format';
import 'sanitize.css/sanitize.css';

import React from 'react';
import ReactDOM from 'react-dom';

import { ConnectedRouter } from 'connected-react-router/immutable';
import Immutable from 'immutable';
import {
  params,
  Storeage,
} from 'kit_utils';
import {
  addGlobalUncaughtErrorHandler,
  registerMicroApps,
  runAfterFirstMounted,
  setDefaultMountApp,
  start,
} from 'qiankun';
import { Provider } from 'react-redux';

import Http from './api';
import configureStore from './configureStore';
import App from './containers/App';
import { actionCreators } from './containers/App/store';
import history from './utils/history';

window.createStoreage = new Storeage("PANDA_STORE")
window.Http = Http
const initialState = Immutable.Map();
const store = configureStore(initialState, history);

const MOUNT_NODE = document.getElementById('app');
const render = () => {
  ReactDOM.render(
    <Provider store={store}>
      <ConnectedRouter history={history}>
        <App />
      </ConnectedRouter>
    </Provider>,
    MOUNT_NODE,
  );
};
const loader = (appContent, loading) => render({ appContent, loading });

const initLocale = () => {
  localStorage.setItem("umi_locale", 'zh-CN')
}
const initMicroApps = () => {
  registerMicroApps(
    [
      {
        name: 'purehtml',
        entry: `//${window.location.hostname}:3020`,
        container: '#subapp-container',
        activeRule: '/web4/',
        loader,
        props: {
          emitter:  window.share.event,
          globalConfig: createStoreage.get("globalConfig") || {},
          XMLHttpRequest: window.XMLHttpRequest
        }
      },
    ],
    {
      beforeLoad: [
        app => {
          // hookRequest()
          console.log('[LifeCycle] before load %c%s', 'color: green;',  JSON.stringify(app));
        },
      ],
      beforeMount: [
        app => {
          // hookRequest()
          console.log('[LifeCycle] before mount %c%s', 'color: green;', JSON.stringify(app));
        },
      ],

      afterUnmount: [
        app => {
          console.log('[LifeCycle] after unmount %c%s', 'color: green;', JSON.stringify(app));
        },
      ],
    },
  );
  const config = createStoreage.get("globalConfig")
  if(config && config.token) {
    setDefaultMountApp(`/web4/?client=${window.globalConfig.client}`)
  }
  start({
    sandbox: {
      experimentalStyleIsolation: true
    },
    singular: true,
    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('pv.sohu.com') !== -1 || url.indexOf('mt0.google.cn') !==-1
    }
  });
  runAfterFirstMounted(() => {
    console.log('[MainApp] first app mounted');
  });
  
  addGlobalUncaughtErrorHandler(event => console.log(event));
  
  // if (process.env.NODE_ENV === 'production') {
  //   require('offline-plugin/runtime').install(); // eslint-disable-line global-require
  // }
}

const initGlobalConfig = () => {
  const config = createStoreage.get("globalConfig") || {};
  if(config.title == null) {
    createStoreage.remove("PANDA_STORE")
  }
  if(!params.getParams('client') && config) {
    createStoreage.remove("PANDA_STORE")
  }

  if(!createStoreage.get("globalConfig")) {
    window.createStoreage = new Storeage("PANDA_STORE")
  }

  if(config.title !== null && Object.keys(config).length > 0) {
    store.dispatch(actionCreators.getConfig(config))
    render({ appContent: '', loading: true });
  } else {
    Http.getConfig().then(res => {
      store.dispatch(actionCreators.getConfig(res))
    }).then(res => {
      render({ appContent: '', loading: true });
    }).catch(error => {
      store.dispatch(actionCreators.getConfigError(error))
    })
  }

  if(config.token) {
    initMicroApps()
  }



}
window.share && window.share.event && window.share.event.on('loginSuccess', () => {
  initMicroApps()
})

initGlobalConfig()
initLocale()




// console.log("globalConfig", globalConfig)

