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

import { Popover } from 'antd';
import { connect } from 'react-redux';
import { matchRoutes, renderRoutes } from 'react-router-config';
import { useHistory } from 'react-router-dom';

import { MenuFoldOutlined } from '@ant-design/icons';
import ProLayout, { SettingDrawer } from '@ant-design/pro-layout';

import RightContent from '../components/GlobalHeader/RightContent';
import { Panel } from '../components/SliderPanel';
import { actionCreators } from '../containers/App/store';
import { getBaseName } from '../utils/utils';
import SecurityLayout from './SecurityLayout';
import Site from './Site';
import styles from './UserLayout.less';

const renderIcon = (icon, size) => {
  return (
    <img
      src={`https://panda-water.cn/web4/${icon}`}
      style={{ width: `${size}px`, height: `${size}px`, opacity: '0.8' }}
    />
  );
};
const menuExtraRender = currentRoutes => {
  const [toggleSystem, setToggleSystem] = useState(false);
  return {
    render: ({ collapsed }) => {
      if (currentRoutes) {
        return (
          <a style={{ display: 'flex', alignItems: 'center' }}>
            <img
              src={`http://panda-water.cn/web4/${currentRoutes &&
                currentRoutes.extData.icon}`}
              style={{ width: '20px', height: '20px' }}
            />
            <span
              style={{
                margin: '0 10px',
                textOverflow: 'ellipsis',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
              }}
            >
              {currentRoutes && currentRoutes.name}
            </span>
            <MenuFoldOutlined onClick={() => setToggleSystem(!toggleSystem)} />
          </a>
        );
      }
      return null;
    },
    toggleSystem,
    onClose: () => setToggleSystem(!toggleSystem),
  };
};

const renderTitle = (title, action) => {
  console.log(styles);
  const getCityStationsForUser = action && action.getCityStationsForUser();
  console.log(getCityStationsForUser);
  return (
    <>
      <span className={styles['header-title']}>{title}</span>
      <div className={styles.cityContent}>
        <Popover placement="bottom">
          <span className={styles.siteName}>
            <img
              src="https://panda-water.cn/web4/assets/images/depart.svg"
              alt="city"
            />
            <span>GCK演示</span>
          </span>
        </Popover>
        <span className={styles.weather}>
          <img
            src="https://panda-water.cn/web4/assets/images/weather2/0.svg"
            alt="weather"
          />
          <span>晴 -1℃/17℃</span>
        </span>
      </div>
    </>
  );
};
const BasicLayout = props => {
  /* eslint-disable no-unused-vars */
  const {
    children,
    settings,
    location = {
      pathname: '/',
    },
  } = props;
  const basename = getBaseName();
  const history = useHistory();
  const [pathname, setPathname] = useState(props.location.pathname);
  const [currentRoutes, setCurrentRoutes] = useState(props.route.routes[0]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [collapse, setCollapse] = useState(false);
  const [loading, setLoading] = useState(true);
  const menuDataRef = useRef([]);
  const microApp = useRef(null);
  const handleMenuCollapse = collapse => {
    setCollapse(collapse);
  };

  const [siteAction, setSiteAction] = useState(() => {
    return new Site(props);
  });

  matchRoutes(props.route.routes, props.location.pathname);
  const extraRender = menuExtraRender(currentRoutes);
  let clearTime = null;
  useEffect(() => {
    setLoading(true);
    clearTime = setTimeout(() => {
      setCurrentRoutes(props.route.routes[currentIndex]);
      setLoading(false);
    }, 100);
    return () => clearTimeout && clearTimeout(clearTime);
  }, [currentIndex]);
  const updateSettings = config => {
    console.log(config);
    props.updageSetting && props.updageSetting(config);
  };

  const handleSelectedKey = key => {
    setSelectedKeys(`${key}`);
    extraRender.onClose();
    history.push(key);
  };

  const handleLogo = event => {
    setTimeout(() => {
      history.replace(`/industry`);
    }, 300);
    //
  };

  return (
    <SecurityLayout>
      <ProLayout
        logo="http://panda-water.cn/web4/assets/images/logo/单独图案-白色.svg"
        siderWidth="145px"
        title=""
        fixSiderbar={true}
        onMenuHeaderClick={event => handleLogo(event)}
        onCollapse={collapse => handleMenuCollapse(collapse)}
        menuExtraRender={extraRender.render}
        rightContentRender={() => <RightContent />}
        headerContentRender={() => renderTitle(props.global.title, siteAction)}
        menu={{
          loading,
        }}
        locale={true}
        menuDataRender={() => currentRoutes && currentRoutes.routes}
        menuItemRender={(menuItemProps, defaultDom) => {
          if (menuItemProps.isUrl || !menuItemProps.path) {
            return defaultDom;
          }
          return (
            <a
              to={menuItemProps.path}
              onClick={() =>
                window.history.replaceState(
                  null,
                  `/${basename}${menuItemProps.path}`,
                  `/${basename}${menuItemProps.path}`,
                )
              }
            >
              {renderIcon(
                menuItemProps.extData && menuItemProps.extData.icon,
                17,
              )}
              {defaultDom}
            </a>
          );
        }}
        subMenuItemRender={(menuItemProps, defaultDom) => {
          return (
            <>
              {renderIcon(
                menuItemProps.extData && menuItemProps.extData.icon,
                17,
              )}
              {collapse ? (
                <div className={`ant-pro-menu-item ${styles.shortName}`}>
                  {menuItemProps.extData.shortName}
                </div>
              ) : (
                defaultDom
              )}
            </>
          );
        }}
        menuProps={{
          onClick: ({ item, key, keyPath, domEvent }) => {
            setSelectedKeys(`${key}`);
            window.share.event.emit('changeRoute', key);
          },
          selectedKeys: [selectedKeys],
        }}
        postMenuData={menuData => {
          menuDataRef.current = menuData || [];
          return menuData || [];
        }}
        menuProps={{
          onClick: ({ item, key, keyPath, domEvent }) => {
            setSelectedKeys(`${key}`);
            setPathname(`/${basename}${key}`);
            window.share && window.share.event.emit('changeRoute', key);
          },
          selectedKeys: [selectedKeys],
        }}
        {...props}
        {...settings}
      >
        {renderRoutes(props.route.routes)}
        <Panel
          visible={extraRender.toggleSystem}
          keyboard={true}
          onClose={extraRender.onClose}
          data={props.route.routes || []}
          onChange={index => setCurrentIndex(index)}
          onSelect={selectKeys => handleSelectedKey(selectKeys)}
        />
        <div id="micro-container" className="subapp-container" ref={microApp} />

        <SettingDrawer
          settings={props.settings}
          onSettingChange={config => updateSettings(config)}
          publicPath={`/${basename}/theme`}
        />
      </ProLayout>
    </SecurityLayout>
  );
};
const mapStateToProps = state => {
  return {
    global: state.getIn(['global', 'globalConfig']),
    settings: state.getIn(['global', 'defaultSetting']),
  };
};
const mapDispatchToProps = dispatch => {
  return {
    updageSetting(setting) {
      dispatch(actionCreators.updageSetting(setting));
    },
  };
};
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(BasicLayout);
