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 _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 '../tagSelect/TagInput';
import Input from '../input';
import ExpandMore from '../icons/internals/ExpandMore';
import DropdownMenu from '../dropdownMenu'; // import AutoComplete from '../autoComplete';

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

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

  // static getDerivedStateFromProps(props, state) {
  //   const { defaultChecked } = props;
  //   if (!state.isControlled && defaultChecked !== state.prevDefaultChecked) {
  //     return {
  //       checked: defaultChecked,
  //       prevDefaultChecked: defaultChecked,
  //     };
  //   }
  //   return null;
  // }
  function Select(props, context) {
    var _this;

    _classCallCheck(this, Select);

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

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

    _defineProperty(_assertThisInitialized(_this), "getSelectWidth", function (isOpen) {
      var _this$props = _this.props,
          disabled = _this$props.disabled,
          searchable = _this$props.searchable,
          multiple = _this$props.multiple,
          options = _this$props.options;

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

        if (searchable && !multiple) {
          _this.setState(function (state) {
            var target = _this.getTagData(options, state.value);

            return {
              search: target == null ? '' : target.label
            };
          });
        } else if (searchable) {
          _this.setState({
            search: ''
          });
        }

        return;
      }

      if (searchable && !multiple) {
        _this.setState({
          search: ''
        });
      }

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

    _defineProperty(_assertThisInitialized(_this), "handleChange", function (e, value, itemValue) {
      var _this$props2 = _this.props,
          onChange = _this$props2.onChange,
          multiple = _this$props2.multiple,
          hasLabelInChange = _this$props2.hasLabelInChange,
          options = _this$props2.options;

      _this.setState(function () {
        return {
          search: !multiple ? _this.valueToLabel[value] : '',
          value: value
        };
      });

      onChange && onChange(hasLabelInChange && !multiple ? options.find(function (item) {
        return item.value === value;
      }) : value, itemValue);
    });

    _defineProperty(_assertThisInitialized(_this), "handleSearch", function (e, search) {
      _this.setState({
        search: search == null ? '' : 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
      } : '';
    });

    _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);
    });

    var _options = props.options,
        defaultValue = props.defaultValue,
        children = props.children,
        _multiple = props.multiple;
    _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 (_multiple && !Array.isArray(defaultValue)) {
      _value = defaultValue == null ? [] : [defaultValue];
    } else {
      _value = defaultValue;
    }

    _this.state = {
      value: _value,
      isOpen: false,
      search: props.multiple ? '' : _this.valueToLabel[props.defaultValue] == null ? '' : _this.valueToLabel[props.defaultValue]
    };
    return _this;
  }

  _createClass(Select, [{
    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) {
          var label = _ref2.label,
              value = _ref2.value;
          _this2.valueToLabel[value] = label;
        }) : React.Children.forEach(nextProps.children, function (child) {
          if (!React.isValidElement(child)) {
            return null;
          }

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

        if (!nextProps.multiple && !nextProps.needReceive) {
          this.setState(function (state) {
            return {
              search: _this2.valueToLabel[state.value] == null ? '' : _this2.valueToLabel[state.value]
            };
          });
        }
      }

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

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

          this.setState(function () {
            return {
              value: value,
              search: ''
            };
          });
        } else {
          value = nextProps.defaultValue;
          this.setState({
            value: value,
            search: this.valueToLabel[value] == null ? '' : this.valueToLabel[value]
          });
        }
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _classNames,
          _this3 = this;

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

      var _this$state = this.state,
          isOpen = _this$state.isOpen,
          value = _this$state.value,
          search = _this$state.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")),
          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 = searchable ? options.filter(function (option) {
        return filter(search, option.props.searchText || option.props.children, option.props.value);
      }) : options;
      var valueData = this.getTagData(options, value);
      var inputClasses = classNames(prefixCls, className, "".concat(prefixCls, "-input"), (_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-open"), isOpen && !disabled), _defineProperty(_classNames, "".concat(prefixCls, "-disabled"), disabled), _defineProperty(_classNames, "".concat(prefixCls, "-multiple"), multiple), _classNames));
      return React.createElement(DropdownMenu, {
        autoWidth: true,
        anchorEl: !multiple ? React.createElement(Input, _extends({
          autoComplete: "off",
          id: id,
          status: status,
          errorIcon: errorIcon,
          loadingIcon: loadingIcon,
          successIcon: successIcon,
          showStatusIcon: showStatusIcon,
          "aria-haspopup": "true",
          onChange: this.handleSearch,
          readOnly: !searchable || readOnly,
          size: size,
          suffix: React.createElement(ExpandMore, null),
          style: style,
          value: searchable ? search || '' : '',
          mask: !searchable ? search : null,
          placeholder: placeholder,
          disabled: disabled
        }, inputProps)) : React.createElement(TagsInput, _extends({
          id: id,
          status: status,
          errorIcon: errorIcon,
          loadingIcon: loadingIcon,
          successIcon: successIcon,
          showStatusIcon: showStatusIcon,
          "aria-haspopup": "true",
          role: "button",
          onTagDelete: this.tagFilter,
          onChange: this.handleSearch,
          searchText: search,
          readOnly: !searchable || readOnly // onClick={this.handleOpen}
          ,
          tags: multiple ? value.filter(function (tag) {
            return _this3.getTagData(options, tag);
          }).map(function (tag) {
            return _this3.getTagData(options, tag);
          }) : [],
          placeholder: placeholder,
          className: inputClasses,
          tagRender: tagRender,
          style: style,
          disabled: disabled,
          searchable: searchable,
          size: size
        }, inputProps)) // trigger="click"
        ,
        trigger: multiple && searchable ? 'focus' : 'click',
        disabled: disabled,
        onOpenChange: this.getSelectWidth,
        defaultIsOpen: isOpen,
        noClose: multiple,
        scrollContainer: scrollContainer
      }, React.createElement(Menu, _extends({}, other, {
        selectable: true,
        indentBase: 0,
        multiple: multiple,
        onChange: this.handleChange,
        className: classNames("".concat(prefixCls, "-menu")),
        value: value,
        role: "listbox",
        size: size
      }), filtered));
    }
  }]);

  return Select;
}(React.Component);

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

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

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

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

  /**
   * 是否过滤
   * */
  filterable: PropTypes.bool,

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

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

  /**
   * Input属性
   * */
  inputProps: PropTypes.object,

  /**
   * 是否多选
   * */
  multiple: PropTypes.bool,

  /**
   * 是否可搜索
   * */
  searchable: PropTypes.bool,

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

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

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

  /**
   * 在change返回值中包含label
   * */
  hasLabelInChange: PropTypes.bool,

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

  /**
   * 是否占满整行
   */
  fullWidth: PropTypes.bool,

  /**
   *  scrollContainer Tooltip兼容自定义可滚动容器
   */
  scrollContainer: PropTypes.node
});

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

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

export default Select;