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

import {
  Anchor,
  Button,
  Popover,
  Radio,
  Result,
  Spin,
} from 'antd';
import classNames from 'classnames';
import _ from 'lodash';
import { connect } from 'react-redux';
import { renderRoutes } from 'react-router-config';
import { useHistory } from 'react-router-dom';
import { useMountedState } from 'react-use';

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

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

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) => {
  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' }} onClick={() => setToggleSystem(!toggleSystem)}>
            <img
              src={`http://panda-water.cn/web4/${currentRoutes &&
              currentRoutes.extData && currentRoutes.extData.icon}`}
              style={{ width: '20px', height: '20px' }}
            />
            <span
              style={{
                margin: '0 7px',
                textOverflow: 'ellipsis',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                color: 'rgba(255, 255, 255, 0.65)'
              }}
            >
              {currentRoutes && currentRoutes.name}
            </span>
            <MenuFoldOutlined style={{color: '#888', marginLeft: '10px'}}/>
          </a>
        );
      }
      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} 
           data-GroupID={item.groupID} 
           data-Site={item.site}
           style={{fontSize: '13px'}} onClick={(event) => changeGroup(event, item)}>
           {item.groupName}
           {
              item.promoteTip && HOT.includes(item.promoteTip) && (
                <div imgType={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 => {
                return 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.siteCityList.letters
                    }
                  </ul>
                  <div className={styles.cityContent} style={{height: '335px'}} ref={cityContent}>
                    {
                      props.data.siteCityList.content
                    }
                  </div>
                </Anchor>
            </div>
          ): (
            <div className="city_pane city_container">
              {
                props.data.citySelector
              }
            </div>
          )
        }
        <Spin spinning={props.loading}></Spin>
      </div>
      
    </>
  )
}

const renderTitle = (title, action, data, loading, setLoading, collapsed, fixedHeader) => {
  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 { 
      const deltWidth = document.body.clientWidth - header.offsetWidth;
      marginLeft = collapsed ? '0px': deltWidth === DEFAULT_MIXIN_WIDTH ? `100px`: `${deltWidth}px`
    }
  };
  return {
    render: (
      <>
        <span className={styles['header-title']} style={{marginLeft: marginLeft}}>
          {title}
        </span>
        <div className={styles.cityContent}>
          <Popover placement="bottomLeft" 
                   trigger="click" 
                   content={<Stations data={data} action={action} loading={loading} setLoading={setLoading}/>} 
                   arrowPointAtCenter
                   overlayClassName={styles.stationsWrapper}>
            {
              (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>
                </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>
      </>
    )
  };
};
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 [selectedKeys, setSelectedKeys] = 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 isMounted = useMountedState();

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

  // matchRoutes(props.route.routes, props.location.pathname);
  const extraRender = menuExtraRender(currentRoutes);
  let clearTime = null;

  useEffect(() => {
    setTimeout(() => {
      if(isMounted) setPageLoading(!pageLoading)
    }, 300)
  }, [])
  useEffect(() => {
    setLoading(true);
    clearTime = setTimeout(() => {
      setCurrentRoutes(props.route.routes[props.currentMenuIndex]);
      setLoading(false);
    }, 100);
    return () => clearTimeout && clearTimeout(clearTime);
  }, [props.currentMenuIndex]);

  useEffect(() => {
    //props.global.token === null || 
    if(_.isEmpty(props.global.token)) {
      history.replace(`/user/login?client=${props.global.client}`);
      return
    }
    siteAction.getCityStationsForUser().then(res => {
      setCityData(res);
    })
    
  }, []);

  // const updateSettings = config => {
  //   props.updageSetting && props.updageSetting(config);
  // };

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

  const handleLogo = event => {
    props.global.userInfo.site ?  history.replace(`/industry`): null;
  };

  
  const others = {
    history: props.history,
    location: props.location,
    match: props.match,
    route: props.menu,
    fixedHeader: true,
    fixSiderbar: true,
    // collapsed: collapse
  }
  const headerContentRender = renderTitle(props.global.title, siteAction, cityData, siteLoading, setSiteLoading, collapse, others.fixedHeader);

  return (
    <SecurityLayout loading={true}>
      <ProLayout
        logo="http://panda-water.cn/web4/assets/images/logo/单独图案-白色.svg"
        siderWidth="145px"
        title={props.global && props.global.title}
        onCollapse={collapse => setCollapse(collapse)}
        onMenuHeaderClick={event => handleLogo(event)}
        menuExtraRender={props.menu.length > 0 ? extraRender.render: null}
        rightContentRender={() => <RightContent {...props}/>}
        headerContentRender={() => headerContentRender.render}
        menu={{
          loading,
        }}
        loading={pageLoading}
        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}`,
                )
              }
            >
              {
                collapse && (
                  <>
                   {
                      renderIcon(
                        menuItemProps.extData && menuItemProps.extData.icon,
                        17,
                      )
                    }
                   <div className={`ant-pro-menu-item ${styles.shortName} ${styles.minixName}`}>
                      {menuItemProps.extData.shortName ? menuItemProps.extData.shortName: menuItemProps.name}
                   </div>
                   <div className={`ant-pro-menu-item ${styles.shortName} ${styles.popverName}`}>
                      {menuItemProps.name}
                   </div>
                  </>
                )
              }

              {
                !collapse && (
                  <>
                    {
                      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}`);
            setPathname(`/${basename}${key}`);
            window.share && window.share.event.emit('changeRoute', key);
          },
          selectedKeys: [selectedKeys],
          popupClassName: styles.menuPopover
        }}
        {
          ...others
        }
        {...settings}
      >
        {renderRoutes(props.route.routes)}

        <Panel
            visible={extraRender.toggleSystem}
            keyboard={true}
            onClose={extraRender.onClose}
            data={props.route.routes || []}
            onChange={index => props.updateCurrentIndex(index)}
            onSelect={selectKeys => handleSelectedKey(selectKeys)}
          />
           {/* <div id="micro-container" className="subapp-container"/> */}
          <Authorized authority={props.location.pathname +  (props.location.search ? props.location.search: '')} {...props}  noMatch={noMatch}>
              {
                  children
              }
               <div id="micro-container" className="subapp-container"/>
 
          </Authorized>
          {/* <div id="micro-container" className="subapp-container"/> */}
          
{/* 
          <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']),
    collapsed: state.getIn(['global', 'collapsed']),
    menu: state.getIn(['global', 'menu']),
    currentMenuIndex: state.getIn(['global', 'currentMenuIndex']),
    flatMenu: state.getIn(['global', 'flatMenu']),
  };
};
const mapDispatchToProps = dispatch => {
  return {
    updageSetting(setting) {
      dispatch(actionCreators.updageSetting(setting));
    },
    updateConfig(config) {
      dispatch(actionCreators.getConfig(config));
    },
    updateCurrentIndex(index) {
      dispatch(actionCreators.updateCurrentIndex(index));
    },
    updateCollapsed(collapsed) {
      dispatch(actionCreators.updateCollapsed(collapsed));
    }
  };
};
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(BasicLayout);
