import { appService } from './api';
import { initMicroApps } from './micro';
import { params, Storeage } from 'kit_utils';
import Cookies from 'js-cookie';
import { actionCreators } from './containers/App/store';
import { getToken, isString } from './utils/utils';
import loader, { render } from './render';
import store from './stores';
import Login from './pages/user/login/login';
const namespace = `__PANDA_STORE__${location.hostname}`;
window.createStoreage = new Storeage(namespace);
export const initGlobalConfig = () => {
  
    // eslint-disable-next-line no-debugger
    // eslint-disable-next-line no-undef
    createStoreage.remove(`__PANDA_STORE__${location.hostname}`);
    window.globalConfig = {};
    window.__INITIAL_STATE__ = {};
    let config = window.globalConfig || {};
    //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 (window.globalConfig.token !== null && Object.keys(window.globalConfig).length > 0) {
      store.dispatch(actionCreators.getConfig(window.globalConfig));
     // 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 && res.data === 'true') {
          store.dispatch(
            actionCreators.getConfig(
              Object.assign({}, window.globalConfig, {
                hasGateWay,
                apiGatewayDomain: `${window.location.origin}/PandaCore`,
              }),
            ),
          );
        }
      });
      // eslint-disable-next-line react-hooks/rules-of-hooks
    let client = params.getParams('client') || Cookies.get('city')
    client = client && client !== 'undefined' ? client : 'city';
    appService
        .queryConfig({
          client: client || 'city',
          ignoreSite: true,
        })
        .then(res => {
          if (res) {
           
            store.dispatch(actionCreators.getConfig(Object.assign({})));
            const data = res;
            if (!data.client) {
              data.client = client;
            }
            // Cookies.set('city', data.client);
            store.dispatch(
              actionCreators.getConfig(
                Object.assign({}, data, {
                  token: '', 
                  access_token: '',
                  userInfo: null
                }),
              ),
            );
            
            //Cookies.set('city', params.getParams('client'))
  
            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)),
                  isInit: false,
                  logout: () => store.dispatch(actionCreators.logout()),
                },
                () => {
                  (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 => {
          // eslint-disable-next-line no-use-before-define
          // initSensorType();
          // eslint-disable-next-line no-use-before-define
          // initIsMock();
          render({ appContent: '', loading: true });
        })
        .catch(error => {
          console.log(error);
          store.dispatch(actionCreators.getConfigError(error));
        });
    }
  };