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 { Provider } from 'react-redux';

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

const namespace = `__PANDA_STORE__${location.hostname}`
window.createStoreage = new Storeage(namespace);
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}>
        <Container>
          <App />
        </Container>
      </ConnectedRouter>
    </Provider>,
    MOUNT_NODE,
  );
};
const loader = (appContent, loading) => render({ appContent, loading });

const initLocale = () => {
  localStorage.setItem('umi_locale', 'zh-CN');
};

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

  if (!createStoreage.get('globalConfig')) {
    window.createStoreage = new Storeage(namespace);
  }

  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(loader);
  }
};

window.share &&
  window.share.event && (
    window.share.event.on('triggerMicro', () => {
      initMicroApps(loader);
    })
  )

  // window.share.event.on('listenerRemoveSigleTab', (url) => {
  //   console.log(url);
  //   window.location.href = url
  //   window.share.event.removeAllListeners('listenerRemoveSigleTab')
  // });

  //listenerRemoveTab


initGlobalConfig();
initLocale();