import { fromJS } from 'immutable';
import Cookies from 'js-cookie';
import { AppConfig, store, event, Storage, helpers } from '@wisdom-utils/utils';
import { Storeage as Store } from '@wisdom-utils/utils/lib/helpers';
import pkg from '../../../../package.json';
import defaultSetting from '@wisdom-utils/components/lib/AppLayout/layouts/defaultSettings';
// import { transformWidgets } from '../../../utils/routes';
// eslint-disable-next-line import/no-duplicates
import {
  CLEAR_RCENT_KEYWORD,
  COMPLEX_CONFIG,
  COMPLEX_PATHNAME,
  CREATE_CONEXT,
  EXTEND_OPEN_KEY,
  GENERATE_MENU,
  GET_CONFIG,
  GET_CURRENT_INDEX,
  GET_CURRENT_ROUTES,
  GET_ERROR_CONFIG,
  GET_MICRO_MOUNTED_STATUS,
  GET_PATHNAME,
  GET_RCENT_KEYWORD,
  GET_RECENT_PRODUCT,
  GET_RECENT_VISITED,
  GET_THEME_CONFIG,
  LOGIN_MODE,
  LOGINOUT,
  SELECT_MENU_KEY,
  SLIDER_MENU_MODE,
  VALIDATE_AUTH,
  MAP_VIEW,
  AMAP_VIEW,
  PD_VIEW,
} from './constants';

const { generMainRoutes, generFlatRoutes, transformWidgets } = helpers;

const proxy = require('../../../../config/proxy');

const keywordStorage = new Storage(`__global_search_keywords__micro_${window.location.hostname}`);
const recentVisitedStorage = new Storage(`__global_recent_visited__micro_${window.location.hostname}`);
const recentProductStorage = new Storage(`__global__recent_product__micro_${window.location.hostname}`);
const currentProduct = new Store(`__global__recent_productIndex__micro_${window.location.hostname}`);
Cookies.set('loginMode', Cookies.get('loginMode') || 'pdw');
export const initialState = fromJS({
  globalConfig: {},
  globalConfigError: '',
  currentRoutes: {},
  instance: null,
  menu: [],
  flatMenu: [],
  defaultSetting,
  recentKeywords: keywordStorage.list || [],
  recentVisited: recentVisitedStorage.list || [],
  recentProducts: recentProductStorage.list || [],
  currentMenuIndex: currentProduct.get('currentMenuIndex') || 0,
  currentMenu: null,
  collapsed: true,
  loginMode: Cookies.get('loginMode') || 'pdw',
  authValidate: false,
  pathname: '',
  selectedKeys: null,
  openKeys: [],
  complexConfig: {},
  complexPathName: null,
  microMounted: true,
  mapView: null,
  amapView: {},
});

/* eslint-disable default-case, no-param-reassign */
const appReducer = (state = initialState, action) => {
  switch (action.type) {
    case GET_CONFIG:
      /* eslint-disable */
      window.__INITIAL_STATE__ = Object.assign(
        {},
        action.data,
        {
          assetsRoot: proxy.assetsRoot,
          allWidgets: action.data.widgets || [],
          env: process.env.NODE_ENV === 'development' ? 'daily' : 'prod',
        },
      );
      window.arcgisAssetsPath = `${window.location.origin}/${pkg.name.toLocaleLowerCase()}/assets`;
      window.__INITIAL_STATE__.mdi = 'SDI';
      window.__INITIAL_STATE__.menu = 'banner-left';
      window.globalConfig = AppConfig(window.__INITIAL_STATE__);
      // eslint-disable-next-line no-undef
      createStoreage.set('globalConfig', window.globalConfig);
      // eslint-disable-next-line no-undef,no-case-declarations
      const config = window.globalConfig;
      // config.access_token = "";
      // eslint-disable-next-line no-case-declarations
      const { homepage } = window.globalConfig;
      const modulePkg = {};
      window.globalConfig && window.globalConfig.products && Array.isArray(window.globalConfig.products) && window.globalConfig.products.map(item => {
          modulePkg[item.PackageName] = item;
      });
      config.widgets = transformWidgets(config.widgets);
      const generMenu = generMainRoutes(config.widgets || [], null, 0, modulePkg);
      let flatMenu = [];
      if (generMenu) {
        flatMenu = generFlatRoutes(generMenu || [], null, null, modulePkg);
      }

      const home = flatMenu.find(item => {
        const path = decodeURI(item.path).split('|');
        let currentPath = path[0];
        if (/^\//.test(currentPath)) {
          currentPath = currentPath.replace(/^\//, '');
        }
        return currentPath === decodeURI(homepage);
      });

      let currentMenuIndex = 0;
      if (home) {
        const parent = home.level >= 2 ? home.parent.parent : home.level >= 3 ? home.parent.parent.parent : home.parent;
        if (parent) {
          currentMenuIndex = generMenu.findIndex(item => item.name === parent.label);
          currentProduct.set('currentMenuIndex', currentMenuIndex);
          store.set('updateMenuIndex', currentMenuIndex);
        }
      }
      window.globalConfig.home = home;
      Cookies.set('city', Cookies.get('city') || window.globalConfig.client);
      window.globalConfig = config;
      return state.merge({
        globalConfig: config,
        menu: generMenu || [],
        flatMenu,
        currentMenu: generMenu && generMenu[state.currentMenuIndex],
      });
    case GET_ERROR_CONFIG:
      return state.merge({
        globalConfigError: action.data,
      });
    case GET_CURRENT_ROUTES:
      return state.merge({
        currentRoutes: action.data,
      });
    case CREATE_CONEXT:
      return state.merge({
        instance: action.data,
      });
    case GENERATE_MENU:
      return state.merge({
        menu: action.data,
        currentMenu: action.data[state.currentMenuIndex],
      });
    case GET_THEME_CONFIG:
      return state.merge({
        defaultSetting: action.data,
      });
    case GET_RCENT_KEYWORD:
      keywordStorage.set('keywords', action.data);
      return state.merge({
        recentKeywords: keywordStorage.list,
      });
    case GET_RECENT_VISITED:
      recentVisitedStorage.set('history', action.data);
      return state.merge({
        recentVisited: recentVisitedStorage.list,
      });
    case GET_RECENT_PRODUCT:
      recentProductStorage.set('history', action.data);
      return state.merge({
        recentProducts: recentProductStorage.list,
      });
    case CLEAR_RCENT_KEYWORD:
      keywordStorage.clear();
      return state.merge({
        recentKeywords: [],
        recentVisited: [],
      });
    case GET_CURRENT_INDEX:
      currentProduct.set('currentMenuIndex', action.data);
      return state.merge({
        currentMenuIndex: currentProduct.get('currentMenuIndex'),
      });
    case SLIDER_MENU_MODE:
      return state.merge({
        collapsed: action.data,
      });
    case LOGIN_MODE:
      return state.merge({
        loginMode: action.data,
      });
    case VALIDATE_AUTH:
      return state.merge({
        authValidate: action.data,
      });
    case GET_PATHNAME:
      return state.merge({
        pathname: action.data,
      });
    case SELECT_MENU_KEY:
      return state.merge({
        selectedKeys: action.data,
      });
    case EXTEND_OPEN_KEY:
      return state.merge({
        openKeys: action.data,
      });
    case COMPLEX_CONFIG:
      return state.merge({
        complexConfig: action.data,
      });
    case COMPLEX_PATHNAME:
      return state.merge({
        complexPathName: action.data,
      });
    case GET_MICRO_MOUNTED_STATUS:
      return state.merge({
        microMounted: action.data,
      });
    case LOGINOUT:
      event.emit('event: application-logout', action.data);
      return state.merge({
        complexConfig: action.data.complexConfig,
        currentMenuIndex: action.data.currentMenuIndex,
        globalConfig: action.data.globalConfig,
      });
    case MAP_VIEW:
      store.set('view', action.data);
      return state.merge({
        mapView: action.data,
      });
    case AMAP_VIEW:
      store.set('amapView', action.data);
      return state.merge({
        amapView: action.data,
      });
    case PD_VIEW:
      store.set('pdView', action.data);
      return state.merge({
        pdView: action.data,
      });

    default:
      return state;
  }
};
export default appReducer;
