import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import React, { PureComponent, Children, isValidElement, cloneElement, Fragment } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { connect } from './MenuContext';
import Tooltip from '../tooltip';
import MenuTitle from './MenuTitle';
import MenuItem from './MenuItem';
import ExpandMore from '../icons/internals/ExpandMore';
import ExpandLess from '../icons/internals/ExpandLess';
import ChevronRight from '../icons/internals/ChevronRight';
import Collapse from '../collapse';

function getMenuItems(children) {
  var items = [];
  Children.forEach(children, function (item) {
    if (isValidElement(item)) {
      items.push(item);
    }
  });
  return items;
}
/**
 * SubMenu
 */


var SubMenu =
/*#__PURE__*/
function (_PureComponent) {
  _inherits(SubMenu, _PureComponent);

  _createClass(SubMenu, null, [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(props, state) {
      var defaultIsOpen = props.defaultIsOpen,
          disabled = props.disabled,
          compact = props.compact;

      if (compact !== state.prevCompact) {
        return {
          popupIsOpen: false
        };
      }

      if (defaultIsOpen !== state.prevDefaultIsOpen) {
        var shouldOpen = disabled ? false : defaultIsOpen;
        return {
          popupIsOpen: shouldOpen,
          isOpen: shouldOpen
        };
      }

      return null;
    }
  }]);

  function SubMenu(props) {
    var _this;

    _classCallCheck(this, SubMenu);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(SubMenu).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "toggle", function () {
      var _this$props = _this.props,
          compact = _this$props.compact,
          disabled = _this$props.disabled;

      _this.setState(function (state) {
        return compact ? {
          popupIsOpen: disabled ? false : !state.popupIsOpen
        } : {
          isOpen: disabled ? false : !state.isOpen
        };
      });
    });

    _defineProperty(_assertThisInitialized(_this), "open", function () {
      var _this$props2 = _this.props,
          compact = _this$props2.compact,
          disabled = _this$props2.disabled;

      _this.setState(compact ? {
        popupIsOpen: !disabled
      } : {
        isOpen: !disabled
      });
    });

    _defineProperty(_assertThisInitialized(_this), "close", function () {
      var compact = _this.props.compact;

      _this.setState(compact ? {
        popupIsOpen: false
      } : {
        isOpen: false
      });
    });

    var defaultIsOpen = props.defaultIsOpen,
        _compact = props.compact;
    _this.state = {
      prevCompact: _compact,
      prevDefaultIsOpen: defaultIsOpen,
      isOpen: defaultIsOpen,
      popupIsOpen: defaultIsOpen,
      selected: defaultIsOpen
    };
    return _this;
  }

  _createClass(SubMenu, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props3 = this.props,
          currentValue = _this$props3.currentValue,
          disabled = _this$props3.disabled,
          children = _this$props3.children,
          autoFold = _this$props3.autoFold,
          mode = _this$props3.mode;
      var target = Array.isArray(currentValue) ? currentValue : [currentValue];
      var childrenSelected = currentValue == null || disabled ? false : (autoFold || mode === 'popup') && this.findValueRecrusively(children, target);
      this.setState({
        popupIsOpen: childrenSelected,
        isOpen: childrenSelected,
        selected: mode === 'popup' && childrenSelected
      });
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var _this$props4 = this.props,
          compact = _this$props4.compact,
          currentValue = _this$props4.currentValue,
          disabled = _this$props4.disabled,
          children = _this$props4.children,
          mode = _this$props4.mode,
          autoFold = _this$props4.autoFold;
      var target = Array.isArray(currentValue) ? currentValue : [currentValue];

      if ((currentValue !== prevProps.currentValue || compact !== prevProps.compact) && (autoFold || mode === 'popup')) {
        var childrenSelected = currentValue == null || disabled ? false : this.findValueRecrusively(children, target);

        if (autoFold && mode !== 'popup') {
          this.setState({
            isOpen: childrenSelected
          });
        }

        if (mode === 'popup') {
          this.setState({
            selected: childrenSelected
          });
        }
      }
    }
  }, {
    key: "findValueRecrusively",
    value: function findValueRecrusively(children, target) {
      var _this2 = this;

      var finded = false;

      if (!children) {
        return false;
      }

      Children.forEach(children, function (item) {
        if (isValidElement(item) && !finded) {
          if (target.includes(item.props.value)) {
            finded = true;
          } else if (item.type.isSubMenu || item.type.isMenuItemGroup) {
            finded = _this2.findValueRecrusively(item.props.children, target);
          }
        }
      });
      return finded;
    }
  }, {
    key: "render",
    value: function render() {
      var _classNames,
          _this3 = this;

      var _this$state = this.state,
          isOpen = _this$state.isOpen,
          selected = _this$state.selected,
          popupIsOpen = _this$state.popupIsOpen;

      var _this$props5 = this.props,
          children = _this$props5.children,
          prefixCls = _this$props5.prefixCls,
          className = _this$props5.className,
          title = _this$props5.title,
          currentValue = _this$props5.currentValue,
          itemValue = _this$props5.itemValue,
          disabled = _this$props5.disabled,
          defaultIsOpen = _this$props5.defaultIsOpen,
          autoFold = _this$props5.autoFold,
          mode = _this$props5.mode,
          popIcon = _this$props5.popIcon,
          expandLessIcon = _this$props5.expandLessIcon,
          expandMoreIcon = _this$props5.expandMoreIcon,
          level = _this$props5.level,
          close = _this$props5.close,
          compact = _this$props5.compact,
          prefix = _this$props5.prefix,
          iconRender = _this$props5.iconRender,
          autoIndent = _this$props5.autoIndent,
          indentBase = _this$props5.indentBase,
          size = _this$props5.size,
          selectable = _this$props5.selectable,
          other = _objectWithoutProperties(_this$props5, ["children", "prefixCls", "className", "title", "currentValue", "itemValue", "disabled", "defaultIsOpen", "autoFold", "mode", "popIcon", "expandLessIcon", "expandMoreIcon", "level", "close", "compact", "prefix", "iconRender", "autoIndent", "indentBase", "size", "selectable"]);

      var classes = classNames(prefixCls, (_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-inline"), mode === 'inline'), _defineProperty(_classNames, "".concat(prefixCls, "-popup"), mode === 'popup'), _defineProperty(_classNames, "".concat(prefixCls, "-parallel"), mode === 'parallel'), _classNames), className);
      var menu = getMenuItems(children).map(function (item, key) {
        return cloneElement(item, {
          level: mode === 'inline' ? level + 1 : undefined,
          key: item.props.value != null ? item.props.value : "subMenu-".concat(key),
          close: mode === 'popup' ? _this3.close : close
        });
      });
      var submenuListCls = classNames("".concat(prefixCls, "-list"), _defineProperty({}, "".concat(prefixCls, "-list-size-").concat(size), size));
      return mode === 'parallel' ? React.createElement(MenuItem, _extends({
        prefix: prefix,
        disableTooltip: true,
        compact: compact,
        value: itemValue,
        className: classes,
        selectable: true,
        suffix: iconRender ? iconRender(isOpen, mode) : popIcon
      }, other), title) : React.createElement("li", {
        className: classes
      }, mode === 'inline' ? React.createElement(Fragment, null, React.createElement(MenuTitle, {
        disabled: disabled,
        selected: !disabled && selected && selectable,
        prefix: prefix,
        compact: compact,
        level: level,
        "aria-haspopup": true,
        "aria-expanded": isOpen,
        role: "button",
        suffix: iconRender ? iconRender(isOpen, mode) : isOpen ? expandLessIcon : expandMoreIcon,
        onClick: this.toggle
      }, title), React.createElement(Collapse, {
        in: isOpen,
        timeout: "auto"
      }, React.createElement("ul", _extends({
        role: "menu"
      }, other, {
        className: submenuListCls
      }), menu))) : React.createElement(Tooltip, _extends({}, other, {
        isOpen: compact ? popupIsOpen : isOpen,
        autoAdjustPosition: true,
        content: React.createElement(MenuTitle, {
          disabled: disabled,
          selected: !disabled && selected && selectable,
          prefix: prefix,
          disableTooltip: true,
          compact: compact,
          "aria-haspopup": true,
          onClick: this.toggle,
          "aria-expanded": compact ? popupIsOpen : isOpen,
          suffix: iconRender ? iconRender(isOpen, mode) : popIcon,
          autoIndent: false,
          role: "button"
        }, title),
        prefixCls: "".concat(prefixCls, "-popup-container"),
        position: "rightTop",
        onOpen: this.open,
        onClose: this.close
      }), React.createElement("ul", {
        role: "menu",
        className: submenuListCls
      }, menu)));
    }
  }]);

  return SubMenu;
}(PureComponent);

_defineProperty(SubMenu, "propTypes", {
  /**
   * 类前缀
   * */
  prefixCls: PropTypes.string,

  /** 子菜单标题 */
  title: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),

  /** 显示模式 */
  mode: PropTypes.oneOf(['inline', 'popup', 'parallel']),

  /** 是否自动折叠 */
  autoFold: PropTypes.bool,

  /** pop模式状态icon */
  popIcon: PropTypes.node,

  /** 展开时状态icon（pop模式下无效） */
  expandMoreIcon: PropTypes.node,

  /** 收缩时状态iocn（pop模式下无效） */
  expandLessIcon: PropTypes.node,

  /** 组件所处层数（用于确定缩进） */
  level: PropTypes.number,

  /** 菜单当前值 */
  currentValue: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.array]),

  /** 是否紧凑显示 */
  compact: PropTypes.bool,

  /** 前缀 */
  prefix: PropTypes.node,

  /** 状态icon渲染方法 function(isOpen, mode) => ReactNode */
  iconRender: PropTypes.func,

  /** 子菜单尺寸，继承自最上层 */
  size: PropTypes.string
});

_defineProperty(SubMenu, "defaultProps", {
  title: '',
  prefixCls: 'ne-submenu',
  defaultIsOpen: false,
  expandMoreIcon: React.createElement(ExpandMore, null),
  expandLessIcon: React.createElement(ExpandLess, null),
  popIcon: React.createElement(ChevronRight, null),
  level: 1,
  compact: false
});

_defineProperty(SubMenu, "contextTypes", {
  nuiMenuControl: PropTypes.object
});

var connectedSubMenu = connect(SubMenu);
connectedSubMenu.isSubMenu = true;
connectedSubMenu.displayName = 'NeatUI.SubMenu';
export default connectedSubMenu;