import React from 'react';
import PropTypes from 'prop-types';
import { Icon, Menu } from 'antd';
import { Link } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import { dataUtils } from '../../utils';

const Menus = ({ siderFold, darkTheme, location, handleClickNavMenu, navOpenKeys, changeOpenKeys, menu }) => {
  // 生成树状
  // const menuTree = arrayToTree(menu.filter(_ => _.upperId != '-1'), 'menuId', 'upperId')
  const menuTree = dataUtils.arrayToTree(menu.filter(_ => _.menuType === 'M'), 'menuId', 'upperId');
  const levelMap = {};

  // 递归生成菜单
  const getMenus = (menuTreeN, siderFoldN) => {
    // console.log(location);
    return menuTreeN.map(item => {
      if (item.children) {
        if (item.upperId) {
          levelMap[item.menuId] = item.upperId;
        }
        return (
          <Menu.SubMenu
            key={item.menuId}
            title={<span>
              {item.menuIcon && <Icon type={item.menuIcon}/>}
              {(!siderFoldN || menuTree.indexOf(item) < 0) && item.menuName}
            </span>}
          >
            {getMenus(item.children, siderFoldN)}
          </Menu.SubMenu>
        );
      }
      return (
        <Menu.Item key={item.menuId}>
          {item.menuUrl === location.pathname ?
            [item.menuIcon && <Icon key="icon" type={item.menuIcon}/>,
              (!siderFoldN || menuTree.indexOf(item) < 0) && item.menuName]
            : <Link key="link" to={{
              pathname: item.menuUrl,
              // search: location.search,
            }}>
              {item.menuIcon && <Icon type={item.menuIcon}/>}
              {(!siderFoldN || menuTree.indexOf(item) < 0) && item.menuName}
            </Link>}
        </Menu.Item>
      );
    });
  };
  const menuItems = getMenus(menuTree, siderFold);

  // 保持选中
  const getAncestorKeys = (key) => {
    let map = {};
    const getParent = (index) => {
      const result = [String(levelMap[index])];
      if (levelMap[result[0]]) {
        result.unshift(getParent(result[0])[0]);
      }
      return result;
    };
    for (let index in levelMap) {
      if ({}.hasOwnProperty.call(levelMap, index)) {
        map[index] = getParent(index);
      }
    }
    return map[key] || [];
  };

  const onOpenChange = (openKeys) => {
    const latestOpenKey = openKeys.find(key => !(navOpenKeys.indexOf(key) > -1));
    const latestCloseKey = navOpenKeys.find(key => !(openKeys.indexOf(key) > -1));
    let nextOpenKeys = [];
    if (latestOpenKey) {
      nextOpenKeys = getAncestorKeys(latestOpenKey).concat(latestOpenKey);
    }
    if (latestCloseKey) {
      nextOpenKeys = getAncestorKeys(latestCloseKey);
    }
    changeOpenKeys(nextOpenKeys);
  };


  // 寻找选中路由
  let currentMenu;
  let defaultSelectedKeys;
  for (let item of menu) {
    if (item.menuUrl && pathToRegexp(item.menuUrl).exec(location.pathname)) {
      currentMenu = item;
      break;
    }
  }
  const getPathArray = (array, current, pid, id) => {
    let result = [String(current[id])];
    const getPath = (item) => {
      if (item && item[pid]) {
        result.unshift(String(item[pid]));
        getPath(dataUtils.queryArray(array, item[pid], id));
      }
    };
    getPath(current);
    return result;
  };
  if (currentMenu) {
    defaultSelectedKeys = getPathArray(menu, currentMenu, 'upperId', 'menuId');
  }

  let menuProps = !siderFold ? {
    onOpenChange,
    openKeys: navOpenKeys,
  } : {};

  // console.log(menuProps, navOpenKeys, defaultSelectedKeys);

  return (
    <Menu
      {...menuProps}
      mode={'inline'}
      theme={'dark'}
      onClick={handleClickNavMenu}
      defaultSelectedKeys={defaultSelectedKeys}
      inlineCollapsed={siderFold}
    >
      {menuItems}
    </Menu>
  );
};

Menus.propTypes = {
  menu: PropTypes.array,
  siderFold: PropTypes.bool,
  darkTheme: PropTypes.bool,
  location: PropTypes.object,
  isNavbar: PropTypes.bool,
  handleClickNavMenu: PropTypes.func,
  navOpenKeys: PropTypes.array,
  changeOpenKeys: PropTypes.func,
};

export default Menus;
