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

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

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 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' }}>
            <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 HOT = ["HOT", "县", "市", "New"]
const StationsItem = (item, action) => {
  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={action.changeGroup.bind(action)}>
           {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();
    console.log(link);
  }

  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'}}>
      {
        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>
        )
      }
      </div>
      
    </>
  )
}

const renderTitle = (title, action, data) => {
  console.log("renderTitle", data)
  return {
    render: (
      <>
        <span className={styles['header-title']}>
          {title}
        </span>
        <div className={styles.cityContent}>
          <Popover placement="bottomLeft" 
                   trigger="click" 
                   content={<Stations data={data} action={action}/>} 
                   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 => {
  console.log("props", 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 [cityData, setCityData] = useState({});
  const menuDataRef = useRef([]);
  const [pageLoading, setPageLoading] = useState(true)
  const handleMenuCollapse = collapse => {
    setCollapse(collapse);
  };

  const isMounted = useMountedState();

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

  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(() => {
    if(props.global && !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 => {
    setTimeout(() => {
      history.replace(`/industry`);
    }, 300);
  };

  const headerContentRender = renderTitle(props.global.title, siteAction, cityData);
  const others = {
    history: props.history,
    location: props.location,
    match: props.match,
    route: props.menu
  }
  return (
    <SecurityLayout loading={true}>
      <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 {...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}`,
                )
              }
            >
              {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],
        }}
        {
          ...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)}
          />
          <Authorized authority={props.location.pathname} {...props}  noMatch={noMatch}>
              {
                  children
              }
              {/* <div id="micro-container" className="subapp-container" ref={microApp} /> */}
          </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']),
    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));
    }
  };
};
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(BasicLayout);
