/*
 * @Author: ZengJing
 * @Date: 2022-04-15 09:34:03
 * @LastEditTime: 2022-04-19 14:57:13
 * @LastEditors: ZengJing
 * @Description:
 * @FilePath: \CivWeb\src\layouts\AppLayout\components\SlideMenu\index.js
 */
import React, { useContext, useEffect, useState, useCallback } from 'react';
import { ConfigProvider, Divider, Skeleton, Tooltip } from 'antd';
import classNames from 'classnames';
import { connect } from 'react-redux';
import { ReactSVG } from 'react-svg';
import ProLayout, { getPageTitle } from '@ant-design/pro-layout';
import useMergedState from 'rc-util/lib/hooks/useMergedState';
import { useHistory } from '@wisdom-utils/runtime';
const LoadingSkeleton = props => {
  const { route } = props;

  return (
    <div style={{ padding: route && !route.routes ? '20px 6px 6px 6px' : '0px' }}>
      <Skeleton loading={route && !route.routes} active title={false} paragraph={{ rows: 10 }}>
        {props.children}
      </Skeleton>
    </div>
  );
};

const Menu = props => {
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('layout-slider');
  const { menuItemRender, menuHeaderRender, siderWidth, onMenuClick } = props;
  const { collapsed, onCollapse, route, style } = props;
  const history = useHistory();
  const [activeMenu, setActiveMenu] = useState('首页');

  const toLink = path => {
    if (!window.__POWERED_BY_QIANKUN__) {
      history.push(path);
    } else {
      window.history.pushState(null, '', path);
    }
  };

  const onSelectItem = (item, dom) => {
    let current = void 0;
    let childrenRoutes = [];
    setActiveMenu(item.name);

    if (item && item.child) {
      current = item.child[0];
      childrenRoutes = item.child;
    } else {
      current = item;
      childrenRoutes = [item];
    }

    if (/iframe/.test(current.path)) {
      history.push({
        path: 'iframe',
        state: current.params,
      });
    } else {
      window.__POWERED_BY_QIANKUN__ ? toLink(`/civbase${current.path}`) : toLink(current.path);
    }

    onMenuClick && onMenuClick(current, childrenRoutes);
  };
  useEffect(() => {
    route.routes = treeRoutes(route.routes);
  }, [route, treeRoutes]);
  const treeRoutes = useCallback(iroute =>
    iroute
      .filter(item => item.level !== 3)
      .map(item => {
        if (item.routes && Array.isArray(item.routes) && item.routes.length >= 1) {
          if (item.level === 2) {
            item.child = item.routes;
          }
          item.routes = treeRoutes(item.routes);
        }
        return item;
      }),
  );
  return (
    <LoadingSkeleton {...props}>
      {route && route.routes && route.routes.length > 0 && (
        <ProLayout
          route={route}
          title={props.title}
          logo={null}
          siderWidth={140}
          config={props.global}
          // onHeaderLogo={handlerIndustry}
          // onPageChange={handlerPageChange}
          // onMenuPanelItemClick={handleUpdateCurrentIndex}
          menuItemRender={(item, dom) =>
            item.level < 3 ? (
              <div
                onClick={() => {
                  onSelectItem(item, dom);
                }}
                className={classNames(`test-icon`, {
                  [`hight-active`]: item.name === activeMenu,
                })}
              >
                {/.svg/.test(item.extData.icon) ? (
                  <div className="my-svg">
                    <ReactSVG src={item.extData.icon} style={{ width: '100%', height: '100%' }} />
                  </div>
                ) : (
                  <div className="my-img">
                    <img src={item.extData.icon} style={{ width: '100%', height: '100%' }} />
                  </div>
                )}
                <span className="my-desc" title={item.name}>
                  {' '}
                  {item.name}{' '}
                </span>
              </div>
            ) : null
          }
          subMenuItemRender={(item, dom) => (
            <div
              className={classNames(`test-icon`, {
                [`hight-active`]: item.name === activeMenu,
              })}
            >
              {/.svg/.test(item.extData.icon) ? (
                <div className="my-svg">
                  <ReactSVG src={item.extData.icon} style={{ width: '100%', height: '100%' }} />
                </div>
              ) : (
                <div className="my-img">
                  <img src={item.extData.icon} style={{ width: '100%', height: '100%' }} />
                </div>
              )}
              <span className="my-desc" title={item.name}>
                {' '}
                {item.name}{' '}
              </span>
            </div>
          )}
          // headerSiteRender={() =>
          //   renderSite({
          //     data: cityData,
          //     config: props.global,
          //     loading: siteLoading,
          //     setLoading: setSiteLoading,
          //     action: siteAction,
          //   })
          // }
        >
          <>
            {/* <Suspense fallback={<></>}>
            {window.location.pathname.startsWith('/civbase/civ_3d') ? (
              <KeepAlive>
                <CesiumMap />
              </KeepAlive>
            ) : window.location.pathname.startsWith('/civbase/civ_webgis') ? (
              mapMode === 'AMap' ? (
                <AMap />
              ) : (
                <ArcgisMap options={{ type: 'ArcgisMap' }} />
              )
            ) : null}
          </Suspense>
          <div id="micro-container" className="subapp-container">
            {props.children}
          </div> */}
          </>
        </ProLayout>
      )}
    </LoadingSkeleton>
  );
};
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,
)(Menu);
