import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';

import {
  Anchor,
  Button,
  Popover,
  Radio,
  Result,
  Spin,
} from 'antd';
import classNames from 'classnames';
import Cookies from 'js-cookie';
import { dom } from 'kit_utils';
import { connect } from 'react-redux';
import { useMountedState } from 'react-use';

import RightContent from '@/components/GlobalHeader/RightContent';
import { Panel } from '@/components/SliderPanel';
import { actionCreators } from '@/containers/App/store';
import Authorized from '@/utils/Authorized';
import {
  findPathByLeafId,
  getBaseName,
} from '@/utils/utils';
import {
  LeftOutlined,
  LoadingOutlined,
  MenuFoldOutlined,
} from '@ant-design/icons';
import ProLayout, { getPageTitle } from '@ant-design/pro-layout';
import { getMatchMenu } from '@umijs/route-utils';
// import { renderRoutes } from 'react-router-config';
import { useHistory } from '@wisdom-utils/runtime';

import pkg from '../../package.json';
import SecurityLayout from './SecurityLayout';
import Site from './Site';
import styles from './UserLayout.less';

const { layout: defaultSetting } = require('../../config/config');

// import Login from '../pages/user/login/login';
const antIcon = <LoadingOutlined style={{ fontSize: 12 }} spin />;
// const { TabPane } = Tabs;

// const baseURI = isProd
//   ? window.location.origin
//   : `http://${window.location.hostname}:3020`;
const optionsWith = [
  { label: '按站点', value: 'site' },
  { label: '按城市', value: 'city' },
];
const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={<Button type="primary">Go Login</Button>}
  />
);

const renderIcon = (icon, size, alias) => (
  <img
    src={icon}
    style={{ width: `${size}px`, height: `${size}px`, opacity: '0.8' }}
    alt=""
  />
);

const menuExtraRender = currentRoutes => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [toggleSystem, setToggleSystem] = useState(false);
  return {
    render: ({ collapsed }) => {
      if (currentRoutes) {
        const iconURL =
          currentRoutes && currentRoutes.extData && currentRoutes.extData.icon;
        return (
          <>
            <Spin
              spinning={currentRoutes.extData && !currentRoutes.extData.icon}
            >
              {iconURL && (
                <a
                  style={{ display: 'flex', alignItems: 'center' }}
                  onClick={() => setToggleSystem(!toggleSystem)}
                >
                  <img
                    src={iconURL}
                    style={{ width: '20px', height: '20px' }}
                    alt=""
                  />

                  <span
                    style={{
                      margin: '0 2px 0 7px',
                      textOverflow: 'ellipsis',
                      overflow: 'hidden',
                      whiteSpace: 'nowrap',
                      color: 'rgba(255, 255, 255, 0.65)',
                      fontSize: '14px',
                    }}
                  >
                    {currentRoutes && currentRoutes.name}
                  </span>
                  <MenuFoldOutlined
                    style={{ color: '#888', marginLeft: '10px' }}
                  />
                </a>
              )}
            </Spin>
          </>
        );
      }
      return null;
    },
    toggleSystem,
    onClose: () => setToggleSystem(!toggleSystem),
  };
};
const HOT = ['HOT', '县', '市', 'New'];
const StationsItem = (item, action) => {
  const changeGroup = (event, data) => {
    action.changeGroup && action.changeGroup(event, data);
  };
  return (
    <li
      key={item.groupID}
      style={{ marginRight: `${item.style.marginRight}px` }}
    >
      <a
        className={classNames(styles.city_select, styles.showTip)}
        title={item.city}
        index={item.promoteIndex}
        style={{ fontSize: '13px' }}
        onClick={event => changeGroup(event, item)}
      >
        {item.groupName}
        {item.promoteTip && HOT.includes(item.promoteTip) && (
          <div title={`${item.promoteTip}`}>{item.promoteTip}</div>
        )}
      </a>
    </li>
  );
};

const Stations = props => {
  const data = props.data.stations;
  const [targetOffset, setTargetOffset] = useState(undefined);
  const cityPane = useRef(null);
  const cityContent = useRef(null);
  const [defaultTab, setDefaultTab] = useState('site');
  useEffect(() => {
    setTargetOffset(cityPane.current.clientHeight / 2);
  }, []);

  const handleClick = (event, link) => {
    event.preventDefault();
  };

  const handleTabChange = event => {
    setDefaultTab(event.target.value);
  };
  return (
    <>
      <div className={styles.focusStations}>
        <ul>
          {Array.isArray(data)
            ? data.map(item => StationsItem(item, props.action))
            : null}
        </ul>
      </div>
      <Radio.Group
        options={optionsWith}
        optionType="button"
        buttonStyle="solid"
        size="small"
        value={defaultTab}
        onChange={handleTabChange}
        style={{ marginTop: '6px' }}
      />
      <div style={{ maxWidth: '520px', position: 'relative' }}>
        {defaultTab === 'site' ? (
          <div
            className={classNames(styles.city_pane, styles.station_container)}
            ref={cityPane}
          >
            <Anchor
              affix={false}
              onClick={handleClick}
              targetOffset={targetOffset}
              getContainer={() => cityContent.current}
            >
              <ul className={styles.py}>
                {props.data &&
                  props.data.siteCityList &&
                  props.data.siteCityList.letters}
              </ul>
              <div
                className={styles.cityContent}
                style={{ height: '335px' }}
                ref={cityContent}
              >
                {props.data &&
                  props.data.siteCityList &&
                  props.data.siteCityList.content}
              </div>
            </Anchor>
          </div>
        ) : (
          <div className="city_pane city_container">
            {props.data.citySelector}
          </div>
        )}
        <Spin spinning={props.loading} tip="加载中" />
      </div>
    </>
  );
};

const renderTitle = ({
  title,
  action,
  data,
  loading,
  setLoading,
  collapsed,
  fixedHeader,
  config,
}) => {
  // eslint-disable-next-line react-hooks/rules-of-hooks,no-debugger
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [visible, setVisible] = useState(false);
  const header = document.querySelector('.ant-pro-fixed-header');
  let marginLeft = '148px';
  const DEFAULT_MIXIN_WIDTH = 48;
  if (header && fixedHeader) {
    const documentWidth = document.body.clientWidth;
    if (documentWidth === header.offsetWidth && !collapsed) {
      marginLeft = '148px';
    } else {
      /* eslint-disable */
      const deltWidth = document.body.clientWidth - header.offsetWidth;
      marginLeft = collapsed
        ? '0px'
        : deltWidth === DEFAULT_MIXIN_WIDTH
        ? `100px`
        : `${deltWidth}px`;
    }
  }
  let loaded = !!(
    (data && !data.stations) ||
    (Array.isArray(data.weathers) && data.weathers.length === 0)
  );
  if (config && config.userInfo && config.userInfo.site === '') {
    loaded = false;
  }
  return (
    <>
      <span className={styles['header-title']} style={{ marginLeft }}>
        {title}
      </span>
      <Spin
        indicator={antIcon}
        spinning={loaded}
        size="small"
        style={{ marginLeft: '10px' }}
        tip="加载中"
        wrapperClassName={styles.spinLoadding}
      >
        <div className={styles.cityContent}>
          <Popover
            placement="bottomLeft"
            trigger="click"
            content={
              <Stations
                data={data}
                action={action}
                loading={loading}
                setLoading={setLoading}
              />
            }
            arrowPointAtCenter
            overlayClassName={styles.stationsWrapper}
            onVisibleChange={visible => setVisible(visible)}
          >
            {Array.isArray(data.stations) && data.stations.length > 0 ? (
              <span className={styles.siteName}>
                <img src="https://panda-water.cn/web4/assets/images/depart.svg" />
                <span>{data.currentStationName}</span>
                <img
                  src="https://panda-water.cn/web4/assets/images/下.svg"
                  style={{
                    transform: !visible ? `rotate(0deg)` : `rotate(180deg)`,
                  }}
                />
              </span>
            ) : null}
          </Popover>
          {data.weathers && Object.keys(data.weathers).length > 0 ? (
            <span
              className={styles.weatcher}
              style={{
                borderLeft:
                  data.stations.length === 0 ? '0px' : '1px solid #aaaaaa',
              }}
            >
              <img src={data.weathers && data.weathers.icon} />
              <span>{data.weathers && data.weathers.text}</span>
            </span>
          ) : null}
        </div>
      </Spin>
    </>
  );
};
const BasicLayout = props => {
  /* eslint-disable no-unused-vars */
  const {
    children,
    settings,
    location = {
      pathname: '/',
    },
  } = props;

  const basename = getBaseName();
  const history = useHistory();
  const [currentRoutes, setCurrentRoutes] = useState([]);
  const [collapse, setCollapse] = useState(false);
  const [loading, setLoading] = useState(true);
  const [cityData, setCityData] = useState({});
  const [pageLoading, setPageLoading] = useState(true);
  const [siteLoading, setSiteLoading] = useState(false);
  const [complexCollapsed, setComplexCollapsed] = useState(false);
  const [tabRoutesList, setTabRoutesList] = useState(
    JSON.parse(sessionStorage.getItem('tabNav')),
  ); // 多标签导航
  const [tabActiveKey, setTabActiveKey] = useState(
    sessionStorage.getItem('tabActiveKey'),
  ); // 多标签导航选中项
  const isMounted = useMountedState();
  const [siteAction, setSiteAction] = useState(
    () => new Site(props, setSiteLoading),
  );

  // useEffect(() => {
  //   setCurrentRoutes(props.route.routes[props.currentMenuIndex]);
  // }, [props.route, props.currentMenuIndex]);

  useEffect(() => {
    props.updatePathname(props.location.pathname);
    // let path = props.global.homepage ? `/civweb4/${props.global.homepage}` : `/civweb4/?client=${props.global.get('client')}`;
    // if(!JSON.parse(sessionStorage.getItem('tabNav'))){
    //   sessionStorage.setItem('tabNav', JSON.stringify([{title: '首页', key: path, path: path}]))
    //   setTabRoutesList([{title: '首页', key: path, path: path}]);
    // }
    // if(!sessionStorage.getItem('tabActiveKey')){
    //   sessionStorage.setItem('tabActiveKey', path);
    //   setTabActiveKey(path);
    // }
  }, []);

  const extraRender = menuExtraRender(currentRoutes);
  let clearTime = null;
  //
  // useEffect(() => {
  //   setTimeout(() => {
  //     if (isMounted) setPageLoading(!pageLoading);
  //   }, 2000);
  // }, []);

  useEffect(() => {
    const config = findPathByLeafId(
      `${props.location.pathname}`,
      [currentRoutes],
      '',
      'path',
      true,
    );
    config && config.parent && props.updateOpenKeys([config.parent.path]);
    if (config && config.level <= 3) {
      props.updatePathname(config.key);
      props.updateSelectedKeys(config.key);
    } else if (config) {
      const { name, path, parent } = config;
      // setPathname(parent.key);
      props.updatePathname(parent.key);
      props.updateSelectedKeys(parent.path);
      props.updateComplexPathName(path);
      const findDeepLevelConfig = findPathByLeafId(
        parent.path,
        currentRoutes.routes,
        '',
        'path',
      );
      props.updateComplexConfig(findDeepLevelConfig);
      setCollapse(true);
      history.push(config.path);
    }
    // handleTabList(props.location.pathname);
  }, [props.location.pathname, currentRoutes]);

  // 监听路由变化，处理标签数据
  const handleTabList = pathname => {
    const { flatMenu } = props;
    let curConfigArr =
      flatMenu.length > 0 &&
      flatMenu.filter(item => item.name && item.path == pathname);
    if (curConfigArr.length > 0) {
      let config = curConfigArr[0];
      let key = null;
      let curTabRoutesList = JSON.parse(sessionStorage.getItem('tabNav'));
      if (config.level <= 3) {
        key = pathname;
        const curSelectTab = curTabRoutesList.filter(child => child.key == key);
        if (curSelectTab.length > 0) {
          setTabActiveKey(key);
        } else {
          curTabRoutesList.push({
            title: config.name,
            key: key,
            path: pathname,
          });
        }
      } else {
        const routes = config.parent.routes || [];
        if (routes.length > 0) {
          key = routes[0].path;
          const curSelectTab = curTabRoutesList.filter(
            child => child.key == key,
          );
          if (curSelectTab.length > 0) {
            setTabActiveKey(key);
          } else {
            curTabRoutesList.push({
              title: config.parent.name,
              key: key,
              path: routes[0].path,
            });
          }
        }
      }
      setTabActiveKey(key);
      setTabRoutesList(curTabRoutesList);
      sessionStorage.setItem('tabNav', JSON.stringify(curTabRoutesList));
      sessionStorage.setItem('tabActiveKey', key);
    }
  };

  //
  useEffect(() => {
    setLoading(true);
    clearTime = setTimeout(() => {
      if (props.currentMenuIndex !== -1) {
        setCurrentRoutes(props.route.routes[props.currentMenuIndex]);
        setLoading(false);
      }
    }, 400);
    return () => clearTimeout && clearTimeout(clearTime);
  }, [props.currentMenuIndex]);



  useEffect(() => {
    siteAction.setGlobalConfig(props.global);
    if (!Cookies.get('token')) {
      history.replace(`/user/login?client=${props.global.get('client')}`);
      props.logout();
      return;
    }
    if (
      props.global &&
      props.global.userInfo &&
      props.global.userInfo.token !== null &&
      props.global.userInfo.loginName &&
      Object.keys(cityData).length === 0
    ) {
      siteAction.getCityStationsForUser().then(res => {
        setCityData(res);
      });
    }
  }, [props.global]);

  useEffect(() => {
    window.share.event.on('updateSite', res => setCityData(res));
    return () => {
      window.share.event.removeAllListeners('updateSite');
      // sessionStorage.removeItem('tabNav')
      // sessionStorage.removeItem('tabActiveKey')
    };
  }, []);

  useMemo(() => {
    window.share.event.on('listenerRemoveTab', () => {
      props.updateSelectedKeys(
        `/civweb4/?client=${props.global.get('client')}`,
      );
      props.updatePathname(`/civweb4/?client=${props.global.get('client')}`);
      history.push(`/civweb4/?client=${props.global.get('client')}`);
    });
    window.share.event.removeAllListeners('listenerRemoveSigleTab');
  }, [props.pathname]);

  useMemo(() => {
    window.share.event.on('listenerRemoveSigleTab', url => {
      const config = findPathByLeafId(
        `${props.location.pathname}`,
        [currentRoutes],
        '',
        'path',
      );
      if (config) {
        props.updatePathname(config.key);
        props.updateSelectedKeys(config.key);
      }
    });
    window.share.event.removeAllListeners('listenerRemoveSigleTab');
  }, []);

  const updateSettings = config => {
    props.updageSetting && props.updageSetting(config);
  };
  const menuDataRef = useRef([]);
  const authorized = useMemo(() => {
    const isHash = window.location.hash !== '';
    const path = isHash
      ? `${props.location.pathname}${window.location.hash}`
      : `${props.location.pathname}`;
    return (
      getMatchMenu(path || '/', menuDataRef.current).pop() || {
        path,
      }
    );
  }, [location.pathname]);
  const handleSelectedKey = item => {
    const config = findPathByLeafId(
      item.path,
      currentRoutes.routes,
      '',
      'path',
    );
    props.updateComplexConfig({});
    props.updateComplexPathName(null);
    if (config && config.routes && config.routes.length > 0) {
      props.updateComplexConfig(config);
      props.updateComplexPathName(config.routes[0].path);
      history.push(config.routes[0].path);
    } else {
      history.push(config.path);
    }
    props.updatePathname(item.key);
    props.updateSelectedKeys(`${item.key}`);
    extraRender.onClose();
    // history.push(item.key);
  };

  const handleLogo = event => {
    props.global.get('userInfo.site') ? history.push(`/industry`) : void 0;
      //history.push('/openapi');
  };

  const transformPopupMenu = useCallback(key => {
    if (key.length > 0) {
      const element = document.getElementById(`${key[0]}$Menu`);
      const len = element ? element.children.length : 0;
      if (len >= 6) {
        dom.addClass(element, styles['popup-menu-flex']);
      }
    }
  });

  const others = {
    history: props.history,
    location: props.location,
    match: props.match,
    route: props.menu,
    fixedHeader: true,
    fixSiderbar: true,
    collapsed: collapse,
  };

  const headerContentRender = renderTitle({
    title: props.global.get('title'),
    action: siteAction,
    data: cityData,
    loading: siteLoading,
    setLoading: setSiteLoading,
    collapsed: collapse,
    fixedHeader: others.fixedHeader,
    config: props.global,
  });

  const menuComplexDataRender = menuList =>
    menuList.map(item => {
      const localItem = {
        ...item,
        hideInMenu: false,
        routes: item.routes ? item.routes : undefined,
      };
      return localItem;
    });

  const transformComplexSideWidth = () => {
    const complexConfig = props.complexConfig.toJS
      ? props.complexConfig.toJS()
      : props.complexConfig;
    let defaultWidth = '150px';
    if (complexCollapsed) {
      return defaultWidth;
    }
    if (
      complexConfig &&
      Object.keys(complexConfig).length > 0 &&
      complexConfig.level === 3
    ) {
      defaultWidth = 150;
    } else {
      defaultWidth = 0;
    }
    return defaultWidth;
  };

  const forceRender = () => {
    if (
      props.location.pathname ===
      decodeURIComponent(
        window.location.pathname.split(pkg.name.toLocaleLowerCase())[1],
      )
    ) {
      window.share.event.emit('trigger:route');
    }
  };

  const title = getPageTitle({
    title: (props.global && props.global.get('title')) || defaultSetting.title,
  });

  const logo = props.global.get('bannerLogo')
    ? window.globalConfig.transformDevAssetsBaseURL(
        props.global.get('bannerLogo'),
      )
    : defaultSetting.logo;
  const renderComplexLayout = children => {
    const complexConfig = props.complexConfig.toJS
      ? props.complexConfig.toJS()
      : props.complexConfig;
    return (
      <ProLayout
        logo={false}
        title={title}
        headerRender={false}
        rightContentRender={() => null}
        collapsedButtonRender={false}
        menuHeaderRender={false}
        footerRender={false}
        className={styles.complexLayout}
        location={{
          pathname: props.complexPathName,
        }}
        route={{
          routes:
            (complexConfig &&
              complexConfig.routes &&
              menuComplexDataRender(complexConfig.routes)) ||
            [],
        }}
        menuItemRender={(menuItemProps, defaultDom) => {
          if (menuItemProps.isUrl || !menuItemProps.path) {
            return defaultDom;
          }
          return <a to={menuItemProps.path}>{defaultDom}</a>;
        }}
        menuProps={{
          onClick: ({ item, key, keyPath, domEvent }) => {
            const config = findPathByLeafId(key, [complexConfig], '', 'key');
            props.updateComplexPathName(key);
            history.push(config.path);
          },
        }}
        collapsed={complexCollapsed}
        navTheme="light"
        siderWidth={transformComplexSideWidth()}
        style={{
          height: '400px',
        }}
      >
        {complexConfig && Object.keys(complexConfig).length > 0 ? (
          <span
            className={styles.complexCollapse}
            onClick={() => setComplexCollapsed(!complexCollapsed)}
          >
            <span className={styles.collapsed}>
              <LeftOutlined />
            </span>
          </span>
        ) : null}
        {children}
      </ProLayout>
    );
  };

  const handlerCollapsed = collapse => {
    setCollapse(collapse);
    if (!collapse) {
      const config = findPathByLeafId(
        `${props.location.pathname}`,
        [currentRoutes],
        '',
        'path',
      );
      // fix: 目前菜单限制只支持两级
      if (config && config.parent) {
        const parentConfig = findPathByLeafId(
          config.parent.path,
          [currentRoutes],
          '',
          'path',
        );
        parentConfig &&
          parentConfig.parent &&
          props.updateOpenKeys([parentConfig.parent.path, config.parent.path]);
      }
    }
  };

  const renderSiderMenu = (menuItemProps, defaultDom) => {
    if (collapse) {
      return (
        <>
          {renderIcon(
            menuItemProps.extData && menuItemProps.extData.icon,
            17,
            menuItemProps.alias,
          )}
          <div
            className={`ant-pro-menu-item ${styles.shortName} ${
              styles.minixName
            }`}
          >
            {menuItemProps &&
            menuItemProps.extData &&
            menuItemProps.extData.shortName
              ? menuItemProps.extData.shortName
              : menuItemProps.name}
          </div>
          <div
            className={`ant-pro-menu-item ${styles.shortName} ${
              styles.popverName
            }`}
          >
            {menuItemProps.name}
          </div>
        </>
      );
    }
    return (
      <>
        {renderIcon(
          menuItemProps.extData && menuItemProps.extData.icon,
          17,
          menuItemProps.alias,
        )}
        {defaultDom}
      </>
    );
  };

  // 多标签模式下，切换标签
  const handleTabRouteChange = activeKey => {
    let tabRoutesList = JSON.parse(sessionStorage.getItem('tabNav'));
    const currentItem = tabRoutesList.filter(item => item.key === activeKey)[0];
    if (currentItem.title == '首页') {
      let path = tabRoutesList[0].path;
      props.updateSelectedKeys(path);
      props.updatePathname(path);
      history.replace(path);
    } else {
      const config = findPathByLeafId(
        currentItem.path,
        [currentRoutes],
        '',
        'path',
      );
      props.updateComplexConfig({});
      props.updateComplexPathName(null);
      if (config && config.routes && config.routes.length > 0) {
        props.updateComplexConfig(config);
        props.updateComplexPathName(config.routes[0].path);
        history.push(config.routes[0].path);
      }
      history.push(currentItem.path);
      props.updatePathname(activeKey);
      props.updateSelectedKeys(`${activeKey}`);
    }
    setTabActiveKey(activeKey);
    sessionStorage.setItem('tabActiveKey', activeKey);
    forceRender();
  };

  // 多标签模式下，删除标签
  const handleTabRouteEdit = (targetKey, action) => {
    if (action === 'remove') {
      let newActiveKey = tabActiveKey;
      let lastIndex;
      let tabRoutesList = JSON.parse(sessionStorage.getItem('tabNav'));
      tabRoutesList.forEach((item, i) => {
        if (item.key === targetKey) {
          lastIndex = i - 1;
        }
      });
      const newTabList = tabRoutesList.filter(item => item.key !== targetKey);
      if (newTabList.length && newActiveKey === targetKey) {
        newActiveKey =
          lastIndex >= 0 ? newTabList[lastIndex].key : newTabList[0].key;
      }
      const config = findPathByLeafId(
        newActiveKey,
        [currentRoutes],
        '',
        'path',
      );
      props.updateComplexConfig({});
      props.updateComplexPathName(null);
      if (config && config.routes && config.routes.length > 0) {
        props.updateComplexConfig(config);
        props.updateComplexPathName(config.routes[0].path);
        history.push(config.routes[0].path);
      }
      if (lastIndex >= 0) {
        history.push(newTabList[lastIndex].path);
      } else {
        history.replace(`/civweb4/${props.global.homepage}`);
      }
      props.updateSelectedKeys(newActiveKey);
      props.updatePathname(newActiveKey);
      setTabActiveKey(newActiveKey);
      setTabRoutesList(newTabList);
      sessionStorage.setItem('tabNav', JSON.stringify(newTabList));
      sessionStorage.setItem('tabActiveKey', newActiveKey);
    }
  };

  const { openKeys } = props;
  // const filterMenu = props.menu.filter(item => !item.hideInMenu)
  return (
    <SecurityLayout loading updateCurrentIndex={props.updateCurrentIndex}>
      {collapse && props.global.loginTemplate === '新春 - 智联.html' ? null : (
        props.global.loginTemplate === '新春 - 智联.html' && (
        <img
          src="https://panda-water.com/web4/assets/images/%E6%96%B0%E5%B9%B4%E4%B8%BB%E9%A2%98/%E6%96%B0%E5%B9%B4%E5%BF%AB%E4%B9%90.gif"
          style={{
            width: '120px',
            position: 'absolute',
            bottom: '40px',
            zIndex: 500,
            left: '12px',
          }}
        />)
      )}

      <ProLayout
        logo={logo}
        siderWidth={defaultSetting.siderWidth}
        onPageChange={() => {}}
        className={
          props.global.loginTemplate === '新春 - 智联.html'
            ? styles.fixSliderHeight
            : ''
        }
        title={title}
        onCollapse={collapse => handlerCollapsed(collapse)}
        onMenuHeaderClick={event => handleLogo(event)}
        menuExtraRender={props.menu.length > 0 ? extraRender.render : null}
        rightContentRender={() => <RightContent {...props} />}
        headerContentRender={() => headerContentRender}
        menu={{
          loading,
        }}
        location={props.pathname}
        locale
        menuDataRender={() => currentRoutes && currentRoutes.routes}
        menuItemRender={(menuItemProps, defaultDom) => {
          if (menuItemProps.isUrl || !menuItemProps.path) {
            return (
              <a
                className={styles.menuItemLink}
                href={menuItemProps.href}
                target={menuItemProps.target}
                title={menuItemProps.name}
              >
                {!collapse && (
                  <>
                    {renderIcon(
                      menuItemProps.extData && menuItemProps.extData.icon,
                      17,
                      menuItemProps.alias,
                    )}
                    <span className="ant-pro-menu-item">
                      <span className="ant-pro-menu-item-title">
                        {menuItemProps.name}
                      </span>
                    </span>
                  </>
                )}
                {collapse && renderSiderMenu(menuItemProps, defaultDom)}
              </a>
            );
          }
          return (
            <a
              to={menuItemProps.path}
              className={styles.menuItemLink}
              onClick={() => history.push(menuItemProps.path)}
              title={menuItemProps.name}
            >
              {renderSiderMenu(menuItemProps, defaultDom)}
            </a>
          );
        }}
        subMenuItemRender={(menuItemProps, defaultDom) => (
          <>
            {renderIcon(
              menuItemProps.extData && menuItemProps.extData.icon,
              17,
              menuItemProps.alias,
            )}
            {collapse ? (
              <div className={`ant-pro-menu-item ${styles.shortName}`}>
                {menuItemProps.extData && menuItemProps.extData.shortName
                  ? menuItemProps.extData.shortName
                  : menuItemProps.name}
              </div>
            ) : (
              defaultDom
            )}
          </>
        )}
        openKeys={[...openKeys]}
        menuProps={{
          forceSubMenuRender: false,
          onClick: ({ item, key, keyPath, domEvent }) => {
            debugger
            domEvent.persist();
            const keyField = key.indexOf('/') > -1 ? 'path' : 'key';
            const config = findPathByLeafId(
              key,
              currentRoutes.routes,
              '',
              keyField,
            );
            props.updateComplexConfig({});
            props.updateComplexPathName(null);
            if (config && config.routes && config.routes.length > 0) {
              props.updateComplexConfig(config);
              props.updateComplexPathName(config.routes[0].path);
              history.push(config.routes[0].path);
            }
            props.updateSelectedKeys(key);
            props.updatePathname(key);
            forceRender();
          },
          onOpenChange: openKeys => {
            props.updateOpenKeys(openKeys.length > 0 ? openKeys : []);
            if (collapse) {
              transformPopupMenu(openKeys);
            }
          },
          selectedKeys: [props.selectedKeys],
          popupClassName: styles.menuPopover,
        }}
        postMenuData={menuData => {
          menuDataRef.current = menuData || [];
          return menuData || [];
        }}
        settings={defaultSetting}
        {...others}
      >
        <Spin
          spinning={props.microMounted}
          size="large"
          wrapperClassName={styles.loadding}
        >
          <Panel
            visible={extraRender.toggleSystem}
            keyboard
            onClose={extraRender.onClose}
            data={props.route.routes || []}
            currentMenuIndex={props.currentMenuIndex}
            onChange={index => props.updateCurrentIndex(index)}
            onSelect={item => handleSelectedKey(item)}
          />
          {/*{*/}
          {/*  props.global.mdi == 'MDI' && */}
          {/*  <Tabs*/}
          {/*    className={styles.menuTabs}*/}
          {/*    type="editable-card"*/}
          {/*    hideAdd={true}*/}
          {/*    onChange={activeKey => handleTabRouteChange(activeKey)}*/}
          {/*    activeKey={tabActiveKey}*/}
          {/*    onEdit={(targetKey, action) => handleTabRouteEdit(targetKey, action)}*/}
          {/*  >*/}
          {/*    {tabRoutesList && tabRoutesList.length > 0 && tabRoutesList.map(item => (*/}
          {/*      <TabPane tab={item.title} key={item.key} closable={item.title != '首页'}/>*/}
          {/*    ))}*/}
          {/*  </Tabs>*/}
          {/*}*/}
          {/*noMatch={noMatch*/}
          {renderComplexLayout(
            <>
              <Authorized authority={authorized} {...props}>
                {children}
              </Authorized>
              <div id="micro-container" className="subapp-container" />
            </>,
          )}
        </Spin>

        {/*<SettingDrawer*/}
        {/*  settings={props.settings}*/}
        {/*  onSettingChange={config => updateSettings(config)}*/}
        {/*  publicPath={`/${basename}/theme`}*/}
        {/*/>*/}
      </ProLayout>
      {/*<div id="micro-container" className="subapp-container" />*/}
    </SecurityLayout>
  );
};
const mapStateToProps = state => ({
  global: state.getIn(['global', 'globalConfig']),
  settings: state.getIn(['global', 'defaultSetting']),
  collapsed: state.getIn(['global', 'collapsed']),
  menu: state.getIn(['global', 'menu']),
  currentMenuIndex: state.getIn(['global', 'currentMenuIndex']),
  flatMenu: state.getIn(['global', 'flatMenu']),
  authValidate: state.getIn(['global', 'authValidate']),
  pathname: state.getIn(['global', 'pathname']),
  selectedKeys: state.getIn(['global', 'selectedKeys']),
  openKeys: state.getIn(['global', 'openKeys']),
  complexConfig: state.getIn(['global', 'complexConfig']),
  complexPathName: state.getIn(['global', 'complexPathName']),
  microMounted: state.getIn(['global', 'microMounted']),
});
const mapDispatchToProps = dispatch => ({
  updageSetting(setting) {
    dispatch(actionCreators.updageSetting(setting));
  },
  updateConfig(config) {
    dispatch(actionCreators.getConfig(config));
  },
  updateCurrentIndex(index) {
    dispatch(actionCreators.updateCurrentIndex(index));
  },
  updateCollapsed(collapsed) {
    dispatch(actionCreators.updateCollapsed(collapsed));
  },
  updateAuthValidate(auth) {
    dispatch(actionCreators.updateAuthValidate(auth));
  },
  updatePathname(pathname) {
    dispatch(actionCreators.updatePathname(pathname));
  },
  updateSelectedKeys(keys) {
    dispatch(actionCreators.updateSelectedKeys(keys));
  },
  updateOpenKeys(keys) {
    dispatch(actionCreators.updateOpenKeys(keys));
  },
  updateComplexConfig(config) {
    dispatch(actionCreators.updateComplexConfig(config));
  },
  updateComplexPathName(pathname) {
    dispatch(actionCreators.updateComplexPathName(pathname));
  },
  logout() {
    dispatch(actionCreators.logout());
  }
});
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(BasicLayout);
