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 './locales/zh-CN';
// import './loader';
// import './vm';
import React from 'react';
import ReactDOM from 'react-dom';

import { Button, message, notification } from 'antd';
import { ConnectedRouter } from 'connected-react-router/immutable';
import Immutable from 'immutable';
import Cookies from 'js-cookie';
import { params, Storeage } from 'kit_utils';
import { Provider } from 'react-redux';

import { useIntl } from '@/locales/localeExports';
import { ErrorBoundary } from '@ant-design/pro-utils';
import { history } from '@wisdom-utils/runtime';

import defaultSettings from '../config/defaultSetting';
// import themePluginConfig from '../config/themePluginConfig';
import { appService } from './api';
import { updateTheme } from './common/helpers/settingColor';
import Container from './components/Container';
import configureStore from './configureStore';
import App from './containers/App';
import { actionCreators } from './containers/App/store';
import { LocaleContainer } from './locales/locale';
import { initMicroApps } from './micro';
import Login from './pages/user/login/login';
import { getToken, isString } from './utils/utils';

const isHttps = document.location.protocol === 'https:';
const { pwa } = defaultSettings;
// eslint-disable-next-line no-restricted-globals
const namespace = `__PANDA_STORE__${location.hostname}`;
window.createStoreage = new Storeage(namespace);
// eslint-disable-next-line no-underscore-dangle
const initialState = Immutable.Map();
const store = configureStore(initialState, history);
const MOUNT_NODE = document.getElementById('root');

// window.umi_plugin_ant_themeVar = themePluginConfig.theme;
const render = () => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  ReactDOM.render(
    <Provider store={store}>
      <ConnectedRouter history={history}>
        <LocaleContainer>
          <ErrorBoundary>
            <Container>
              <App />
            </Container>
          </ErrorBoundary>
        </LocaleContainer>
      </ConnectedRouter>
    </Provider>,
    MOUNT_NODE,
  );
};

const loader = (appContent, loading) => render({ appContent, loading });

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

const initGlobalConfig = () => {
  // eslint-disable-next-line no-debugger
  // eslint-disable-next-line no-undef
  let config = createStoreage.get('globalConfig') || {};
  store.dispatch(actionCreators.updateComplexConfig({}));
  if (!getToken() || config.token == null) {
    // eslint-disable-next-line no-undef
    createStoreage.remove(namespace);
    config = {};
  }
  if (!params.getParams('client', window.location.search) && config) {
    // eslint-disable-next-line no-undef
    createStoreage.remove(namespace);
  }

  // eslint-disable-next-line no-undef
  if (!createStoreage.get('globalConfig')) {
    window.createStoreage = new Storeage(namespace);
  }
  if (!getToken()) {
    localStorage.removeItem('loginSite');
  }

  if (config.token !== null && Object.keys(config).length > 0) {
    store.dispatch(actionCreators.getConfig(config));
    // render({ appContent: '', loading: true });
    initMicroApps(loader, store);
    if (config.isNewYear) {
      updateTheme('#ff9600');
    }
  } else {
    appService.getWateWayConfig().then(res => {
      const hasGateWay =
        res && res.data && isString(res.data) ? JSON.parse(res.data) : res.data;
      if (res.code === 0) {
        store.dispatch(
          actionCreators.getConfig(
            Object.assign({}, window.globalConfig, {
              hasGateWay,
              apiGatewayDomain: `${window.location.origin}/Publish/GateWay`,
            }),
          ),
        );
      }
    });
    // eslint-disable-next-line react-hooks/rules-of-hooks
    appService
      .queryConfig({ client: params.getParams('client') || 'city' })
      .then(res => {
        if (res) {
          const data = res;
          if (!data.client) {
            data.client = 'city';
          }
          store.dispatch(
            actionCreators.getConfig(
              Object.assign({}, window.globalConfig, data),
            ),
          );

          if (data.loginTemplate === '新春 - 智联.html') {
            updateTheme('#ff9600');
          }
          // eslint-disable-next-line no-new
          if (getToken()) {
            // eslint-disable-next-line no-new
            new Login(
              {
                global: Object.assign({}, data, {
                  token: getToken(),
                }),
                // eslint-disable-next-line no-shadow
                updateConfig: data =>
                  store.dispatch(actionCreators.getConfig(data)),
              },
              () => {
                (async () => {
                  (await (getToken() &&
                    window.globalConfig &&
                    window.globalConfig.token)) && initMicroApps(loader, store);
                })();
              },
              true,
            );
          }

          // eslint-disable-next-line no-shadow
        }
        return res;
      })
      // eslint-disable-next-line no-shadow
      .then(res => {
        render({ appContent: '', loading: true });
      })
      .catch(error => {
        store.dispatch(actionCreators.getConfigError(error));
      });
  }
};

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


if (pwa) {
  // const appPWA = window.i18n.getI18n('app');
  window.addEventListener('sw.offline', () => {
    message.warning(useIntl().formatMessage({ id: 'app.pwa.offline' }));
  });

  window.addEventListener('sw.updated', event => {
    const e = event;
    const reloadSW = async () => {
      const worker = e.detail && e.detail.waiting;
      if (!worker) {
        return true;
      }
      await new Promise((resolve, reject) => {
        const channel = new MessageChannel();
        channel.port1.onmessage = msgEvent => {
          if (msgEvent.data.error) {
            reject(msgEvent.data.error);
          } else {
            resolve(msgEvent.data);
          }
        };
        worker.postMessage({ type: 'skip-waiting' }, [channel.port2]);
      });
      window.location.reload(true);
      return true;
    };
    const key = `open${Date.now()}`;
    const btn = (
      <Button
        type="primary"
        onClick={() => {
          notification.close(key);
          reloadSW();
        }}
      >
        {useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated.ok' })}
      </Button>
    );
    notification.open({
      message: useIntl().formatMessage({ id: 'pwa.serviceworker.updated' }),
      description: useIntl().formatMessage({
        id: 'pwa.serviceworker.updated.hint',
      }),
      btn,
      key,
      onClose: async () => null,
    });
  });
} else if ('serviceWorker' in navigator && isHttps) {
  const { serviceWorker } = navigator;
  if (serviceWorker.getRegistrations) {
    serviceWorker.getRegistrations().then(sws => {
      sws.forEach(sw => {
        sw.unregister();
      });
    });
  }
  serviceWorker.getRegistration().then(sw => {
    if (sw) sw.unregister();
  });

  if (window.caches && window.caches.keys) {
    caches.keys().then(keys => {
      keys.forEach(key => {
        caches.delete(key);
      });
    });
  }
}
