import { CaretDownOutlined, CaretUpOutlined } from '@easyv/react-icons';
import { Cascader } from '@easyv/antd';
import classNames from 'classnames';
import { RootState } from 'models';
import { updateCurExpandedNavKeys, updateCurSelectedKeys } from 'models/spaceship';
import { SpaceShipState } from 'models/spaceship.types';
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getCurSelectedKeyById, jumpByNavConfig, pathNameIsSpaceShipEdit } from 'utils/spaceship';
import { deepFindOne } from 'utils/utils';
import NavExpanIcon from './NavExpanIcon';
import styles from './topNavSidebar.less';

interface Props {
  maxWidth: React.CSSProperties['maxWidth'];
}

const deleteByChildrenIsEmpty = (data: any) => {
  return data.reduce((pre, cur) => {
    if (cur.children && cur.children.length) {
      return [...pre, { ...cur, children: deleteByChildrenIsEmpty(cur.children) }];
    }
    // INFO 这里故意解构出children,防止children为空时存在级联组件中
    const { children, ...otherCur } = cur;
    return [...pre, { ...otherCur }];
  }, []);
};

const TopNavSidebar = (props: Props) => {
  const { maxWidth } = props;
  const spaceShip = useSelector<RootState>((state) => state.spaceShip) as SpaceShipState;
  const { curSelectedKeys, curPortalBaseInfo, curPortalNavigation = [] } = spaceShip;
  const [display, setDisplay] = useState(false);
  const [openStatus, setOpenStatus] = useState(false);
  const [displayUpIcon, setDisplayUpIcon] = useState(false);
  const [levelOneSelectedKey, setLevelOneSelectedKey] = useState<number | undefined>(); //一级选中的key
  const dispatch = useDispatch();

  const isThemeWhite = curPortalBaseInfo?.thumbColor?.name === 'white';

  useEffect(() => {
    const curNavData = curPortalNavigation.find(
      (item) =>
        Object.keys(deepFindOne(item?.children || [], (obj) => obj.id === curSelectedKeys, 'children') || {}).length > 0 ||
        item.id === curSelectedKeys
    );
    if (curNavData) {
      setLevelOneSelectedKey(curNavData.id);
    }
  }, [curSelectedKeys]);

  return (
    <>
      <div
        style={{ maxWidth }}
        className={classNames(isThemeWhite ? styles.navContainerWhite : styles.navContainerBlack, {
          [styles.changeNavSidebarHeight]: display
        })}>
        <div
          className={classNames(isThemeWhite ? styles.titleWhite : styles.titleBlack, {
            [styles.changeNavSidebarHeight]: display
          })}
          title="易知微门户易知微门户易知微门户">
          {curPortalBaseInfo?.name}
        </div>
        <div className={styles.navContainer} id="TopNavSidebar">
          {curPortalNavigation?.map((item) => (
            <div
              key={item.id}
              onMouseLeave={() => {
                setDisplayUpIcon(false);
                setOpenStatus(false);
              }}>
              <Cascader
                key={item.id}
                open={openStatus && item.id === levelOneSelectedKey && item.children && item.children.length > 0}
                onDropdownVisibleChange={(v) => {
                  setDisplayUpIcon(v);
                  setOpenStatus(v);
                }}
                onChange={(e: number[], option) => {
                  const navData = option?.slice(-1)?.[0] || {};
                  if (Array.isArray(e)) {
                    // 如果是编辑页则任何引用类型的菜单都可以被选中
                    if (pathNameIsSpaceShipEdit()) {
                      document.getElementById(`navSet${navData.key}`)?.scrollIntoView(true);
                      curSelectedKeys && dispatch(updateCurExpandedNavKeys([curSelectedKeys, ...e.concat([]).reverse()]));
                      dispatch(updateCurSelectedKeys(e.slice(-1)?.[0]));
                      return;
                    }

                    // 非编辑页，且当前选中为空节点，则查找当前空节点子节点存在引用类型为外链或者应用的
                    if (navData.quoteType === 0) {
                      const curSelectedChildrenData = getCurSelectedKeyById(navData.children || []);
                      if (Object.keys(curSelectedChildrenData).length) {
                        document.getElementById(`navSet${curSelectedChildrenData.id}`)?.scrollIntoView(true);
                        dispatch(updateCurSelectedKeys(curSelectedChildrenData.id));
                      }
                      return;
                    }
                    //  非编辑页，且当新建页面打开
                    if (navData.openWay === 2) {
                      jumpByNavConfig(navData);
                      return;
                    }
                    // 非编辑页，且当前选中菜单引用类型不为空节点
                    document.getElementById(`navSet${navData.key}`)?.scrollIntoView(true);
                    dispatch(updateCurSelectedKeys(e.slice(-1)?.[0]));
                  }
                }}
                getPopupContainer={() => document.getElementById('TopNavSidebar') || document.body}
                expandTrigger="hover"
                changeOnSelect={true}
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                options={deleteByChildrenIsEmpty(item.children)}>
                <div
                  onMouseEnter={() => {
                    setDisplayUpIcon(true);
                    setOpenStatus(true);
                    setLevelOneSelectedKey(item.id);
                  }}
                  onClick={(e) => {
                    e.stopPropagation();
                    // 如果不是编辑页
                    // 非编辑页
                    if (!pathNameIsSpaceShipEdit()) {
                      if (item.quoteType === 0) {
                        const curSelectedChildrenData = getCurSelectedKeyById(item.children || []);
                        if (Object.keys(curSelectedChildrenData).length) {
                          if (curSelectedChildrenData.openWay === 2) {
                            jumpByNavConfig(curSelectedChildrenData);
                            return;
                          }
                          document.getElementById(`navSet${item.id}`)?.scrollIntoView(true);
                          dispatch(updateCurSelectedKeys(Number(curSelectedChildrenData.id)));
                        }
                        return;
                      }
                      //  非编辑页，且当新建页面打开
                      if (item.openWay === 2) {
                        jumpByNavConfig(item);
                        return;
                      }
                      // 非编辑页，且当前选中菜单引用类型不为空节点
                      document.getElementById(`navSet${item.id}`)?.scrollIntoView(true);
                      dispatch(updateCurSelectedKeys(Number(item.id)));
                      return;
                    }
                    // 编辑页
                    document.getElementById(`navSet${item.id}`)?.scrollIntoView(true);
                    dispatch(updateCurSelectedKeys(item.id));
                    if (item.id !== levelOneSelectedKey) {
                      setLevelOneSelectedKey(item.id);
                    }
                  }}
                  className={classNames(styles.navItem, isThemeWhite ? styles.navItemWhite : styles.navItemBlack, {
                    [styles.navItemSelectedWhite]: levelOneSelectedKey === item.id && isThemeWhite,
                    [styles.navItemSelectedBlack]: levelOneSelectedKey === item.id && !isThemeWhite
                  })}
                  id={`navDisplay${item.id}`}>
                  <span className={styles.navTitle}>{item.name}</span>
                  {item?.children?.length ? (
                    displayUpIcon && item.id === levelOneSelectedKey ? (
                      <CaretUpOutlined className={styles.icon} />
                    ) : (
                      <CaretDownOutlined className={styles.icon} />
                    )
                  ) : null}
                </div>
              </Cascader>
            </div>
          ))}
        </div>
      </div>
      <NavExpanIcon
        them={curPortalBaseInfo?.thumbColor?.name || 'black'}
        onClick={(e) => setDisplay(e)}
        navBarLayout={curPortalBaseInfo?.navBarLayout}
      />
    </>
  );
};

export default TopNavSidebar;
