import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
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 _inherits from "@babel/runtime/helpers/esm/inherits";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";

/**
 * Select.jsx
 *
 * @Author: jruif
 * @Date: 2018/1/21 上午10:12
 */
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import TagsInput from './TagInput';
import keyboardKey from '../util/keyboardKey';
import DropdownMenu from '../dropdownMenu'; // import AutoComplete from '../autoComplete';

import Menu, { MenuItem } from '../menu';
/**
 * TagSelect
 * */

var TagSelect =
/*#__PURE__*/
function (_React$Component) {
  _inherits(TagSelect, _React$Component);

  function TagSelect(props, context) {
    var _this;

    _classCallCheck(this, TagSelect);

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

    _defineProperty(_assertThisInitialized(_this), "valueToLabel", {});

    _defineProperty(_assertThisInitialized(_this), "getSelectWidth", function (isOpen) {
      var newWidth;
      var _this$props = _this.props,
          onChange = _this$props.onChange,
          disabled = _this$props.disabled;
      var _this$state = _this.state,
          search = _this$state.search,
          value = _this$state.value;

      if (!isOpen || disabled) {
        _this.setState(function () {
          return {
            isOpen: false
          };
        });

        if (search && onChange) {
          if (!value.includes(search)) {
            var newValue = [].concat(_toConsumableArray(value), [search]);

            _this.setState({
              value: newValue
            });

            onChange && onChange(newValue, search);
          }

          _this.setState({
            search: ''
          });
        }

        return;
      }

      _this.setState(function () {
        return {
          isOpen: true
        };
      });
    });

    _defineProperty(_assertThisInitialized(_this), "handleChange", function (e, value, itemValue) {
      var onChange = _this.props.onChange;

      _this.setState({
        search: '',
        value: value
      });

      onChange && onChange(value, itemValue);
    });

    _defineProperty(_assertThisInitialized(_this), "handleSearch", function (e, search) {
      _this.setState({
        search: search
      });

      var onSearch = _this.props.onSearch;
      onSearch && onSearch(e, search);
    });

    _defineProperty(_assertThisInitialized(_this), "getTagData", function (options, value) {
      var target = _this.valueToLabel[value];
      return target ? {
        label: target,
        value: value
      } : {
        label: value,
        value: value
      };
    });

    _defineProperty(_assertThisInitialized(_this), "tagFilter", function (tag) {
      var onChange = _this.props.onChange;
      var value = _this.state.value;

      _this.setState(function (state) {
        return {
          value: state.value.filter(function (v) {
            return v !== tag;
          })
        };
      });

      onChange && onChange(value.filter(function (v) {
        return v !== tag;
      }), tag);
    });

    _defineProperty(_assertThisInitialized(_this), "selectRootNodeRef", function (el) {
      var selectRef = _this.props.selectRef;
      _this.selectRootNode = el;
      selectRef && selectRef(el);
    });

    _defineProperty(_assertThisInitialized(_this), "handleKeyDown", function (e) {
      var _this$props2 = _this.props,
          triggerKey = _this$props2.triggerKey,
          disabled = _this$props2.disabled,
          onChange = _this$props2.onChange;

      if (!disabled && keyboardKey.getCode(e) === triggerKey) {
        e.preventDefault();
        var _this$state2 = _this.state,
            search = _this$state2.search,
            value = _this$state2.value;

        if (search && onChange) {
          if (!value.includes(search)) {
            var newValue = [].concat(_toConsumableArray(value), [search]);

            _this.setState({
              value: newValue
            });

            onChange && onChange(newValue, search);
          }

          _this.setState({
            search: ''
          });
        }
      }
    });

    var options = props.options,
        defaultValue = props.defaultValue,
        children = props.children;
    options ? options.forEach(function (_ref) {
      var label = _ref.label,
          value = _ref.value;
      _this.valueToLabel[value] = label;
    }) : React.Children.forEach(children, function (child) {
      if (!React.isValidElement(child)) {
        return null;
      }

      _this.valueToLabel[child.props.value] = child.props.searchText || child.props.children;
    });
    var _value = '';

    if (!Array.isArray(defaultValue)) {
      _value = [defaultValue];
    } else {
      _value = defaultValue;
    }

    _this.state = {
      value: _value,
      width: 100,
      isOpen: false,
      search: ''
    };
    _this.selectRootNode = null;
    return _this;
  }

  _createClass(TagSelect, [{
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      var _this2 = this;

      var _this$props3 = this.props,
          defaultValue = _this$props3.defaultValue,
          children = _this$props3.children,
          options = _this$props3.options;

      if (children !== nextProps.children || options !== nextProps.options) {
        this.valueToLabel = {};
        nextProps.options ? nextProps.options.forEach(function (_ref2, index) {
          var label = _ref2.label,
              className = _ref2.className,
              value = _ref2.value,
              item = _objectWithoutProperties(_ref2, ["label", "className", "value"]);

          _this2.valueToLabel[value] = label;
        }) : React.Children.forEach(nextProps.children, function (child, index) {
          if (!React.isValidElement(child)) {
            return null;
          }

          _this2.valueToLabel[child.props.value] = child.props.searchText || child.props.children;
        });
      }

      if (nextProps.defaultValue !== defaultValue) {
        var value = '';

        if (!Array.isArray(nextProps.defaultValue)) {
          value = [nextProps.defaultValue];
        } else {
          value = nextProps.defaultValue;
        }

        this.setState(function () {
          return {
            value: value,
            search: ''
          };
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this,
          _classNames;

      var _this$props4 = this.props,
          triggerKey = _this$props4.triggerKey,
          prefixCls = _this$props4.prefixCls,
          className = _this$props4.className,
          children = _this$props4.children,
          readOnly = _this$props4.readOnly,
          defaultValue = _this$props4.defaultValue,
          placeholder = _this$props4.placeholder,
          style = _this$props4.style,
          disabled = _this$props4.disabled,
          propOptions = _this$props4.options,
          inputProps = _this$props4.inputProps,
          size = _this$props4.size,
          onChange = _this$props4.onChange,
          filter = _this$props4.filter,
          onSearch = _this$props4.onSearch,
          tagRender = _this$props4.tagRender,
          fullWidth = _this$props4.fullWidth,
          status = _this$props4.status,
          errorIcon = _this$props4.errorIcon,
          loadingIcon = _this$props4.loadingIcon,
          successIcon = _this$props4.successIcon,
          showStatusIcon = _this$props4.showStatusIcon,
          prefix = _this$props4.prefix,
          suffix = _this$props4.suffix,
          id = _this$props4.id,
          other = _objectWithoutProperties(_this$props4, ["triggerKey", "prefixCls", "className", "children", "readOnly", "defaultValue", "placeholder", "style", "disabled", "options", "inputProps", "size", "onChange", "filter", "onSearch", "tagRender", "fullWidth", "status", "errorIcon", "loadingIcon", "successIcon", "showStatusIcon", "prefix", "suffix", "id"]);

      var _this$state3 = this.state,
          isOpen = _this$state3.isOpen,
          value = _this$state3.value,
          search = _this$state3.search;
      var options = propOptions ? propOptions.map(function (_ref3, index) {
        var label = _ref3.label,
            item = _objectWithoutProperties(_ref3, ["label"]);

        return React.createElement(MenuItem, _extends({
          value: value,
          className: classNames("".concat(prefixCls, "-menu-item"), className),
          key: value || index
        }, item, {
          role: "option"
        }), label);
      }) : React.Children.map(children, function (child, index) {
        if (!React.isValidElement(child)) {
          return null;
        }

        return React.cloneElement(child, {
          key: child.props.value || index,
          role: 'option'
        });
      });
      var filtered = options.filter(function (option) {
        return filter(search, option.props.searchText || option.props.children, option.props.value);
      });
      return React.createElement("div", {
        className: classNames(prefixCls, className),
        ref: this.selectRootNodeRef
      }, React.createElement(DropdownMenu, {
        autoWidth: true,
        anchorEl: React.createElement(TagsInput, {
          id: id,
          suffix: suffix,
          status: status,
          errorIcon: errorIcon,
          loadingIcon: loadingIcon,
          successIcon: successIcon,
          showStatusIcon: showStatusIcon,
          "aria-haspopup": "true",
          role: "button",
          onTagDelete: this.tagFilter,
          onChange: this.handleSearch,
          searchText: search,
          readOnly: readOnly,
          onKeyDown: this.handleKeyDown,
          tags: value.filter(function (tag) {
            return _this3.getTagData(options, tag);
          }).map(function (tag) {
            return _this3.getTagData(options, tag);
          }),
          placeholder: placeholder,
          inputProps: inputProps,
          className: classNames("".concat(prefixCls, "-input"), (_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-open"), isOpen && !disabled), _defineProperty(_classNames, "".concat(prefixCls, "-disabled"), disabled), _defineProperty(_classNames, "".concat(prefixCls, "-multiple"), true), _classNames)),
          tagRender: tagRender,
          style: style,
          disabled: disabled,
          searchable: true,
          size: size
        }),
        trigger: "focus",
        disabled: disabled,
        onOpenChange: this.getSelectWidth,
        defaultIsOpen: isOpen,
        noClose: true
      }, React.createElement(Menu, _extends({}, other, {
        indentBase: 0,
        selectable: true,
        multiple: true,
        onChange: this.handleChange,
        className: classNames("".concat(prefixCls, "-menu")),
        value: value,
        role: "listbox",
        size: size
      }), filtered)));
    }
  }]);

  return TagSelect;
}(React.Component);

_defineProperty(TagSelect, "displayName", 'NeatUI.TagSelect');

_defineProperty(TagSelect, "propTypes", {
  /**
   * 占位描述字段
   * */
  placeholder: PropTypes.string,

  /**
   * 预设值
   * */
  defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.bool, PropTypes.array]),

  /**
   * Select的选项
   * */
  options: PropTypes.array,

  /**
   * 是否禁止
   * */
  disabled: PropTypes.bool,

  /**
   * TagSelect的ref函数，获取TagSelect的dom元素
   * */
  selectRef: PropTypes.func,

  /**
   * 自定义样式
   * */
  style: PropTypes.object,

  /**
   * Select选项
   * */
  inputProps: PropTypes.object,

  /**
   * 是否根据输入项进行筛选
   * */
  filter: PropTypes.func,

  /**
   * 文本框值变化时回调
   * */
  onChange: PropTypes.func,

  /**
   * 选择框大小，默认medium，base同medium
   * */
  size: PropTypes.oneOf(['large', 'medium', 'small', 'base']),
  // base === medium

  /**
   * 多选标签渲染方法
   */
  tagRender: PropTypes.bool,

  /**
   * 是否占满整行
   */
  fullWidth: PropTypes.bool
});

_defineProperty(TagSelect, "defaultProps", {
  prefixCls: 'ne-tag-select',
  disabled: false,
  size: 'medium',
  fullWidth: false,
  indent: 12,
  filter: function filter(search, value) {
    if (search === '') {
      return true;
    }

    return "".concat(value).includes(search);
  }
});

export default TagSelect;