import { fromJS } from 'immutable';
import Cookies from 'js-cookie';
import { AppConfig, store, event, Storage, helpers } from '@wisdom-utils/utils';
import { params, Storeage as Store } from '@wisdom-utils/utils/lib/helpers';
import defaultSetting from '@wisdom-utils/components/lib/AppLayout/layouts/defaultSettings';
import _ from 'lodash';
import memoized from 'nano-memoize';
import pkg from '../../../../package.json';
// 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,
  CONFIG_INTEGRATED,
} 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 = `__global__recent_productIndex__micro_${window.location.hostname}_${sessionStorage.getItem(
  'client',
) ||
  params.getParams('client') ||
  'city'}`;
sessionStorage.setItem(currentProduct, 0);
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: Number(sessionStorage.getItem(currentProduct)) || 0,
  currentMenu: null,
  collapsed: true,
  loginMode: Cookies.get('loginMode') || 'pdw',
  authValidate: false,
  pathname: '',
  selectedKeys: null,
  openKeys: [],
  complexConfig: {},
  complexPathName: null,
  microMounted: true,
  mapView: null,
  amapView: {},
  integratedConfig: JSON.parse(localStorage.getItem('integrationConfig') || '{}'),
});

/* 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';
      const temp = AppConfig(window.__INITIAL_STATE__);
      temp.displayMode = window.__INITIAL_STATE__?.displayMode || '';
      // 验证码开启 系统配置表里配置
      temp.isVerification = action.data.isVerification || '';
      // 验证码配置 站点设置里配置 只针对该站点
      temp.isVerificationCode =
        action.data?.isVerificationCode ||
        action.data?.IsVerificationCode ||
        action.data.VerificationConfig?.IsVerificationCode ||
        false;
      temp.verificationCodeTimeOut =
        action.data.verificationCodeTimeOut || action.data.VerificationConfig?.VerificationCodeTimeOut || 1;
      temp.verificationCodeType =
        action.data.verificationCodeType || temp.isVerificationCode
          ? action.data.verificationCodeType || action.data.VerificationConfig?.VerificationCodeType || ''
          : '';
      // temp.isVerificationCode 为false 时,不能用短信验证码
      // 密码校验
      temp.PasswordAuth = action.data.PasswordAuth || '否';
      temp.PasswordRule = action.data.PasswordRule || '';
      temp.PasswordTip = action.data.PasswordTip || '';
      window.globalConfig = temp;

      // 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, isOpenTransitionPage } = 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 pickMenus = memoized(() => )
      const generMenu = generMainRoutes(config.widgets || [], null, 0, modulePkg);
      let flatMenu = [];
      if (generMenu) {
        const flat = state.toJS();
        const data = _.uniqBy(generFlatRoutes(generMenu || [], null, null, modulePkg), 'path');
        if (
          _.isEqualWith(flat.flatMenu, data, (value, other) => {
            if (value.path === other.path) {
              return true;
            }
          })
        ) {
          flatMenu = data;
        } else {
          flatMenu = flat.flatMenu;
        }
        const index = flatMenu.findIndex(item => item.name === '首页');
        if (!isOpenTransitionPage && index === -1) {
          flatMenu.push({
            path: `/${homepage}`,
            href: `/${homepage}`,
            key: 'PANDA_HOME',
            name: '首页',
          });
        }
      }

      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) || 0;
          sessionStorage.setItem(currentProduct, currentMenuIndex);
          store.set('updateMenuIndex', currentMenuIndex);
        }
      }
      window.globalConfig.home = home;
      Cookies.set('client', Cookies.get('client') || 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:
      const currentProductNew = `__global__recent_productIndex__micro_${
        window.location.hostname
      }_${sessionStorage.getItem('client') || window.globalConfig?.client || 'city'}`;
      sessionStorage.setItem(currentProductNew, action.data);
      return state.merge({
        currentMenuIndex: Number(sessionStorage.getItem(currentProductNew)) || 0,
      });
    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 || 0,
        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,
      });
    case CONFIG_INTEGRATED:
      localStorage.setItem('integrationConfig', action.data ? JSON.stringify(action.data) : '');
      return state.merge({
        integratedConfig: fromJS(action.data || {}),
      });
    default:
      return state;
  }
};
export default appReducer;