import React, { Component } from 'react';
import PropTypes from 'prop-types';

/**
 * 菜单增强，主要是用于刷新时，自动 active 当前菜单
 * @export
 * @param {Component} WrappedComponent
 * @returns
 */
export default function connectMenu(WrappedComponent){
  return class MenuComponent extends Component {

    static propTypes = {
      url: PropTypes.string,
      index: PropTypes.bool,
      isBlank: PropTypes.bool,
      // 设置菜单 active key
      setMenuActive: PropTypes.func,
      // 当前菜单的 key值
      menuKey: PropTypes.string
    };

    componentDidMount() {
      this.refreshActive(this.props);
    }

    getHref(props) {
      let href = props.url;
      if (props.isBlank) {
        return href;
      }
      if (!props.index && !href) {
        return '';
      }
      const baseURL = '/';
      href = `${baseURL}/${href || ''}`;
      return href.replace(/\/+/g, '/').replace(/(.+)\/$/, '$1');
    }

    isActive(props, href) {
      if (props.index) {
        return href === (location.pathname || '/');
      } else {
        return href && new RegExp(`${href}(?=/|$|\\?|#)`).test(location.href);
      }
    }

    refreshActive = (props) => {
      const href = this.getHref(props);
      const active = this.isActive(props, href);
      if (active){
        props.setMenuActive && props.setMenuActive(props.menuKey);
      }
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
}
