import React, { Component } from "react";
import dynamic from "dva/dynamic";
import { Menu, Icon } from "antd";
import { connect } from "dva";
import { Link } from "dva/router";

import styles from "./index.less";
// import list from "./data.json";
import BasicModules from "@/pages/BasicModules";

const { SubMenu } = Menu;

class Menus extends Component {
  constructor(props) {
    super(props);
    this.state = {
      openKeys: this.getDefaultCollapsedSubMenus(props)
    };
    this.menus = [];
  }

  componentWillMount() {
    this.props.dispatch({
      type: "menu/menuLoadData"
    });
  }

  componentWillReceiveProps(nextProps) {
    // this.setMenus(nextProps.menuList);
  }

  setMenus(menuList) {
    menuList = this.props.navDatas;
    const navDatas = this.getNavData(menuList);
    if (navDatas && navDatas.length > 0) {
      this.menus = navDatas.reduce(
        (arr, current) => arr.concat(current.children),
        []
      );
    }
  }

  getNavMenuItems(menusData, parentPath = "") {
    if (!menusData || menusData.length == 0) {
      return [];
    }
    return menusData.map(item => {
      if (!item.name || !item.path) {
        return null;
      }
      let itemPath;
      if (item.path.indexOf("http") === 0) {
        itemPath = item.path;
      } else {
        itemPath = `${parentPath}/${item.path || ""}`.replace(/\/+/g, "/");
      }
      if (item.children && item.children.some(child => child.name)) {
        return (
          <SubMenu
            title={
              item.icon ? (
                <div className="ant-menu-submenu-wrap">
                  <Icon type={item.icon} />
                  {item.name}
                </div>
              ) : (
                item.name
              )
            }
            key={item.treePathCode || item.path}
            className="ant-menu-submenu-title2"
          >
            {this.getNavMenuItems(item.children, itemPath)}
          </SubMenu>
        );
      }
      return (
        <Menu.Item
          key={item.treePathCode || item.path}
          component={item.component}
          name={item.name}
        >
          {/^https?:\/\//.test(itemPath) ? (
            <a href={itemPath} target={item.target}>
              <div className="ant-menu-submenu-wrap">
                <Icon type={item.icon} />
                {item.name}
              </div>
            </a>
          ) : (
            <Link
              to={`${item.path}`}
              target={item.target}
              replace={itemPath === window.location.pathname}
            >
              <div className="ant-menu-submenu-wrap">
                <Icon type={item.icon} />
                {item.name}
              </div>
            </Link>
          )}
        </Menu.Item>
      );
    });
  }

  getDefaultCollapsedSubMenus(props) {
    const currentMenuSelectedKeys = [...this.getCurrentMenuSelectedKeys(props)];
    currentMenuSelectedKeys.splice(-1, 1);
    if (currentMenuSelectedKeys.length === 0) {
      return [];
    }
    return currentMenuSelectedKeys;
  }

  getCurrentMenuSelectedKeys(props) {
    // const { location: { pathname } } = props || this.props;
    if (!this.menus || this.menus.length == 0) return [];
    const pathname = window.location.pathname;
    const keys = pathname.split("/").slice(1);
    if (keys.length === 1 && keys[0] === "") {
      return [this.menus[0].key];
    }
    return keys;
  }

  // getNavData(menuList) {
  //   const navs = this.getMenus(menuList);
  //   // dynamicWrapper(app, [], () => import("../layouts/buyer/HomeLayout")),
  //   return navs;
  // }
  getComponentPath(path) {
    return `../../${path}`;
  }
  getNavData(menuList) {
    const app = this.props.app;
    return menuList.map(menu => {
      if (menu.items && menu.items.length > 0) {
        menu.children = this.getNavData(menu.items);
      } else {
        menu.children = [];
      }
      menu.component = this.dynamicWrapper(app, [menu.modelsRef], () => {
        console.log(`../${menu.componentPath}`);
        return import("@/pages/basefiles/roles/roles");
      });
      return menu;
    });
  }
  getModelPath(m) {
    return `../../models/${m}.js`;
  }
  dynamicWrapper(app, models, component) {
    return dynamic({
      app,
      models: () => models.map(m => import(`../../models/${m}.js`)),
      component:
        models.length > 0 ? () => new BasicModules(component(), app) : component
    });
  }

  handleOpenChange = openKeys => {
    const lastOpenKey = openKeys[openKeys.length - 1];
    const isMainMenu = this.menus.some(
      item =>
        lastOpenKey &&
        (item.treePathCode === lastOpenKey || item.path === lastOpenKey)
    );
    this.setState({
      openKeys: isMainMenu ? [lastOpenKey] : [...openKeys]
    });
  };

  handleMenuClick = m => {
    try {
      this.props.onClick(m);
    } catch (e) {
      console.error(e);
    }
  };

  render() {
    const { collapsed } = this.props;

    // Don't show popup menu when it is been collapsed
    const menuProps = !collapsed
      ? {}
      : {
          openKeys: this.state.openKeys
        };
    return (
      <Menu
        theme="dark"
        mode="inline"
        {...menuProps}
        onOpenChange={this.handleOpenChange.bind(this)}
        selectedKeys={this.getCurrentMenuSelectedKeys()}
        style={{ width: "100%" }}
        className={styles.menu}
        onClick={this.handleMenuClick}
      >
        {this.getNavMenuItems(this.props.navDatas)}
      </Menu>
    );
  }
}
export default connect(state => ({
  ...state,
  // menuList: list.data
  menuList: state.menu.list
}))(Menus);
