import React, { Key, useContext, useEffect, useRef, useState, useMemo } from 'react';
import {
  withRouter,
} from 'react-router-dom';
import { Menu, Popover, Tooltip } from 'antd';
import { RightOutlined } from '@ant-design/icons';
import { menuList } from '../../routes//config/menuList';
import { XMContext, VersionContext } from '../../store/context';
import BaseService from '@/domains/basic-domain/baseService';
import StoreService from '@/domains/store-domain/storeService';
import classNames from 'classnames';
import User from "@/common/js/user"
import _ from 'underscore';
import tBus from '@/core/tbus'
import "./Menu.less";
import { display } from 'html2canvas/dist/types/css/property-descriptors/display';
import ContactWidget from '@/components/ContactWidget';

const { SubMenu } = Menu;

function VersionPanel(props: any) {
  const [versionName, setVersionName] = useState('标准版');
  const [showVersionPopover, setShowVersionPopover] = useState(false);
  const [showRenewPopover, setShowRenewPopover] = useState(false);
  const versionInfo = useContext(VersionContext);

  function onVersionEnter() {
    setShowVersionPopover(true);
  }
  function onVersionLeave() {
    setShowVersionPopover(false);
    setShowRenewPopover(false);
  }
  function onRenewClick() {
    setShowRenewPopover(true);
    setShowVersionPopover(false);
  }

  const versionPopoverClass = classNames({
    popover: true,
    'popover-show': showVersionPopover,
  });

  return (
    <div className='version-info' onMouseEnter={onVersionEnter} onMouseLeave={onVersionLeave}>
      <div className='row-1'>
        <div className='version-name'>{versionName}</div>
        <ContactWidget trigger='click' placement='rightBottom' visible={showRenewPopover}>
          <div className='renew' onClick={onRenewClick}>
            去续费
            <span className='icon iconfont' style={{ fontSize: '10px' }}>
              &#59291;
            </span>
          </div>
        </ContactWidget>
      </div>
      <div className='expiration-time'>
        有效期至{versionInfo?.validEndTime}
        {versionInfo?.stateEnum === 'NO' ? '(已过期)' : ''}
      </div>
      <div className={versionPopoverClass}>
        <div className='title'>版本信息</div>
        {versionInfo?.stateEnum === 'NO' ? <div className='expiration-tag'>已过期</div> : ''}

        <div className='content'>
          <div className='widget' style={{ marginRight: '26px', marginBottom: '16px', width: '70px' }}>
            <div className='lable'>剩余天数</div>
            <div className='lable-text'>{versionInfo?.surplusDayTime}</div>
          </div>
          <div className='widget' style={{ marginBottom: '16px', width: '212px' }}>
            <div className='lable'>有效起止日期</div>
            <div className='lable-text'>
              {versionInfo?.validStartTimeST === versionInfo?.validEndTimeST ? "-" : `${versionInfo?.validStartTime}~${versionInfo?.validEndTime}`}
            </div>
          </div>
          <div className='widget' style={{ marginRight: '26px', marginBottom: '8px', width: '70px' }}>
            <div className='lable'>剩余人数</div>
            <div className='lable-text'>{versionInfo?.surplusUserNum}</div>
          </div>
          <div className='widget' style={{ marginBottom: '8px' }}>
            <div className='lable' style={{ display: 'inline-block' }}>
              人数限制
            </div>
            <Tooltip
              overlayStyle={{ maxWidth: '587px', width: '587px' }}
              placement='topLeft'
              arrowPointAtCenter
              title={() => {
                return (
                  <div>
                    <div>1、若员工/学员存在多个学院，企业人数只统计为1人；</div>
                    <div>2、若一个学员既用「企业微信」登录学习又用「微信」登录学习，企业人数将统计为2人。</div>
                  </div>
                );
              }}>
              <div style={{ display: 'inline-block', position: 'relative', top: '2px', marginLeft: '4px' }}>
                <span>
                  <svg viewBox='0 0 1024 1024' version='1.1' xmlns='http://www.w3.org/2000/svg' p-id='1026' width='14' height='14'>
                    <path
                      d='M512 68.266667c245.111467 0 443.733333 198.656 443.733333 443.733333s-198.621867 443.733333-443.733333 443.733333C266.922667 955.733333 68.266667 757.077333 68.266667 512S266.922667 68.266667 512 68.266667z m29.320533 596.548266c0.477867-27.989333 2.4576-48.196267 5.802667-60.654933 3.413333-12.458667 8.567467-23.4496 15.633067-33.0752 6.997333-9.557333 21.9136-24.507733 44.714666-44.714667 33.928533-30.037333 56.797867-55.637333 68.437334-76.5952a139.1616 139.1616 0 0 0 17.5104-68.846933c0-43.008-16.5888-79.701333-49.800534-110.011733-33.1776-30.378667-77.6192-45.533867-133.358933-45.533867-52.6336 0-94.958933 14.1312-126.976 42.3936-31.9488 28.2624-51.268267 68.949333-57.685333 122.094933l71.8848 8.533334c6.212267-39.6288 19.3536-68.778667 39.3216-87.483734 19.933867-18.6368 44.817067-27.989333 74.6496-27.989333 30.788267 0 56.900267 10.308267 78.165333 30.9248 21.265067 20.5824 31.880533 44.544 31.880533 71.748267 0 15.018667-3.618133 28.910933-10.922666 41.608533-7.168 12.731733-22.971733 29.764267-47.240534 51.131733-24.200533 21.367467-41.028267 37.649067-50.346666 48.810667-12.6976 15.291733-21.9136 30.481067-27.613867 45.533867-7.748267 19.933867-11.639467 43.690667-11.639467 71.133866 0 4.676267 0.1024 11.707733 0.341334 21.026134h67.242666z m8.192 140.3904v-79.735466h-79.701333v79.735466h79.701333z'
                      fill='#bfbfbf'
                      p-id='1027'></path>
                  </svg>
                </span>
              </div>
            </Tooltip>
            <div className='lable-text'>{versionInfo?.userNum}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Aside(props: any) {
  const { menuType, handleMenuType } = props;
  const ctx: any = useContext(XMContext);
  const [selectKey, setSelectKey] = useState();
  const [selectKeyParent, setSelectKeyParent] = useState();
  const [openKeys, setOpenKeys] = useState(['']);
  const [topLogoUrl, setTopLogoUrl] = useState('');
  const [collapsed, setCollapsed] = useState(false);
  const rootSubmenuKeys = _.pluck(menuList, 'groupCode');

  useEffect(() => {
    const link = props.location.pathname;
    menuList.map((item: any, index: any) => {
      if (link.indexOf(item.link) !== -1) {
        setSelectKey(item.groupCode);
        setSelectKeyParent(item.groupCode);
        setOpenKeys([]);
      } else if (item.children) {
        item.children.map((_item: any, _index: any) => {
          if (link.indexOf(_item.link) !== -1) {
            setSelectKeyParent(item.groupCode);
            setSelectKey(_item.groupCode + index + _index);
          }
        });
      }
      return item;
    })
  }, [props.location.pathname])

  useEffect(()=> {
    getTopLeftLogo()
    tBus.bind("updateCollegeInfo",updateCollegeInfo)
    return ()=> {
      tBus.unbind("updateCollegeInfo",updateCollegeInfo)
    }
  },[])

  function updateCollegeInfo() {
    getTopLeftLogo()
  }

  function getTopLeftLogo() {
    if (User.getToken()) {
      StoreService.getStoreDetail({ storeId: User.getStoreId() }).then((res) => {
        if (_.isEmpty(res.result.logo)) {
          setTopLogoUrl('https://image.xiaomaiketang.com/xm/fe4NCjr7XF.png');
        } else {
          setTopLogoUrl(res.result.logo);
        }
      });
    }
  }

  function toggleMenu(item: any, selectKey: any) {
    console.log('item', item, selectKey);
    setSelectKeyParent(selectKey);
    window.RCHistory.push(item.link);
    if (!menuType) {
      setOpenKeys([]);
    }
  }

  function onOpenChange(key: Key[]) {
    if (typeof key === 'string') {
      if (openKeys.includes(key)) {
        setOpenKeys([]);
      } else {
        setOpenKeys([key]);
      }
    }
  }

  function onOpenChangeForHover(key: Key[]) {
    if (menuType) {
      return;
    }
    if (typeof key === 'string') {
      if (openKeys.includes(key)) {
        setOpenKeys([]);
      } else {
        setOpenKeys([key]);
      }
    }
  }

  function handleMenu() {
    handleMenuType();
    setCollapsed(!collapsed);
  }

  const openKeysConstrol = useMemo(() => {
    return {
      [menuType ? 'openKeys' : 'defaultOpenKeys']: openKeys,
    };
  }, [menuType, openKeys]);

  return (
    <div id='left-container' className={menuType ? 'left-container' : 'left-container left-container-vertical'}>
      <div className='top-ctrl'>
        <div className='topLogo'>{menuType && <img src={topLogoUrl} alt='' className='img1'></img>}</div>
        <div className='menu-type-icon' onClick={handleMenu}>
          {menuType ? <span className='icon iconfont'>&#xe83d;</span> : <span className='icon iconfont'>&#xe615;</span>}
        </div>
      </div>

      <div className='left'>
        <div className='nav'>
          <Menu
            {...openKeysConstrol}
            style={menuType ? { minHeight: '100%', background: '#0E1935' } : { minHeight: '100%', background: '#0E1935', width: '56px' }}
            selectedKeys={selectKey}
            onOpenChange={onOpenChange}
            inlineCollapsed={collapsed}
            mode={menuType ? 'inline' : 'vertical'}>
            {menuList.map((item: any, index: any) => {
              if (ctx.xmState.storeUserPermissionList.indexOf(item.groupCode) === -1) {
                return null;
              }
              if (item.children) {
                return (
                  <SubMenu
                    key={item.groupCode}
                    style={{ marginTop: 0 }}
                    icon={
                      !menuType && item.groupCode === selectKeyParent ? (
                        <div className='icon-img-box' style={{ backgroundColor: '#2966FF', width: '40px', height: '40px' }}>
                          <img src={item.selectImg} className='icon-img' />
                        </div>
                      ) : (
                        <div className='icon-img-box' style={{ backgroundColor: '#fff', width: '40px', height: '40px', display: 'inline-block' }}>
                          <img src={item.img} className='icon-img' />
                        </div>
                      )
                    }
                    title={menuType ? <span className='icon-img-title'>{item.groupName}</span> : ''}
                    onTitleClick={() => onOpenChange(item.groupCode)}>
                    {item.children.map((_item: any, _index: any) => {
                      if (ctx.xmState.storeUserPermissionList.indexOf(_item.groupCode) === -1) {
                        return null;
                      }
                      return (
                        <Menu.Item
                          onClick={() => {
                            toggleMenu(_item, item.groupCode);
                          }}
                          style={{ marginTop: 0 }}
                          key={_item.groupCode + index + _index}>
                          <span className='name'>{_item.groupName}</span>
                        </Menu.Item>
                      );
                    })}
                  </SubMenu>
                );
              } else {
                return (
                  <Menu.Item
                    onClick={() => {
                      toggleMenu(item, item.groupCode);
                    }}
                    key={item.groupCode}
                    icon={
                      !menuType && item.groupCode === selectKeyParent ? (
                        <div className='icon-img-box' style={{ backgroundColor: '#2966FF' }}>
                          <img src={item.selectImg} className='icon-img' />
                        </div>
                      ) : (
                        <div className='icon-img-box'>
                          <img src={selectKey === item.groupCode ? item.selectImg : item.img} className='icon-img' />
                        </div>
                      )
                    }>
                    {menuType ? <span className='icon-img-title'>{item.groupName}</span> : ''}
                  </Menu.Item>
                );
              }
            })}
          </Menu>
        </div>
        {
        menuType ? <VersionPanel /> : ""
        }
      </div>     
      
    </div>
  );
}

export default withRouter(Aside);
