"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard")["default"];

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _createSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/createSuper"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _react = _interopRequireWildcard(require("react"));

var _reactDom = require("react-dom");

var _classnames = _interopRequireDefault(require("classnames"));

var _noop = _interopRequireDefault(require("lodash/noop"));

var _KeyCode = _interopRequireDefault(require("../../_util/KeyCode"));

var _animate = _interopRequireDefault(require("../../animate"));

var _util = require("./util");

var _SelectTrigger = _interopRequireDefault(require("./SelectTrigger"));

var _TreeNode2 = _interopRequireDefault(require("./TreeNode"));

var _strategies = require("./strategies");

var _Button = _interopRequireDefault(require("../../button/Button"));

var _excluded = ["label", "value", "disabled", "key", "hasOwnProperty", "selectable", "children", "isLeaf"];

function filterFn(input, child) {
  return String((0, _util.getPropValue)(child, (0, _util.labelCompatible)(this.props.treeNodeFilterProp))).indexOf(input) > -1;
}

function loopTreeData(data) {
  var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var treeCheckable = arguments.length > 2 ? arguments[2] : undefined;
  return data.map(function (item, index) {
    var pos = "".concat(level, "-").concat(index);
    var label = item.label,
        value = item.value,
        disabled = item.disabled,
        key = item.key,
        hasOwnProperty = item.hasOwnProperty,
        selectable = item.selectable,
        children = item.children,
        isLeaf = item.isLeaf,
        otherProps = (0, _objectWithoutProperties2["default"])(item, _excluded);
    var props = (0, _objectSpread2["default"])({
      value: value,
      title: label,
      // value: value || String(key || label), // cause onChange callback error
      key: key || value || pos,
      disabled: disabled || false,
      selectable: selectable === false ? selectable : !treeCheckable
    }, otherProps);
    var ret;

    if (children && children.length) {
      ret = /*#__PURE__*/_react["default"].createElement(_TreeNode2["default"], props, loopTreeData(children, pos, treeCheckable));
    } else {
      ret = /*#__PURE__*/_react["default"].createElement(_TreeNode2["default"], (0, _extends2["default"])({}, props, {
        isLeaf: isLeaf
      }));
    }

    return ret;
  });
}

var Select = /*#__PURE__*/function (_Component) {
  (0, _inherits2["default"])(Select, _Component);

  var _super = (0, _createSuper2["default"])(Select);

  function Select(_props2) {
    var _this;

    (0, _classCallCheck2["default"])(this, Select);
    _this = _super.call(this, _props2);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onInputChange", function (event) {
      var val = event.target.value;

      var _assertThisInitialize = (0, _assertThisInitialized2["default"])(_this),
          props = _assertThisInitialize.props;

      _this.setState({
        inputValue: (0, _util.isEmpty)(_this.props.searchValue) ? val : _this.props.searchValue,
        open: true
      });

      if (props.treeCheckable && !val) {
        _this.setState({
          value: _this.getValue(props, (0, _toConsumableArray2["default"])(_this.state.value), false)
        });
      }

      props.onSearch(val);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onDropdownVisibleChange", function (open) {
      // selection inside combobox cause click
      if (!open && document.activeElement === _this.getInputDOMNode()) {// return;
      } // this.setOpenState(open);
      // setTimeout, then have animation. why?


      setTimeout(function () {
        _this.setOpenState(open, undefined, !open);
      }, 10);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onKeyDown", function (event) {
      var props = _this.props;

      if (props.disabled) {
        return;
      }

      var keyCode = event.keyCode;

      if (_this.state.open && !_this.getInputDOMNode()) {
        _this.onInputKeyDown(event);
      } else if (keyCode === _KeyCode["default"].ENTER || keyCode === _KeyCode["default"].DOWN) {
        _this.setOpenState(true);

        event.preventDefault();
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onInputKeyDown", function (event) {
      var props = _this.props;

      if (props.disabled) {
        return;
      }

      var state = _this.state;
      var keyCode = event.keyCode;

      if ((0, _util.isMultiple)(props) && !event.target.value && keyCode === _KeyCode["default"].BACKSPACE) {
        var value = state.value.concat();

        if (value.length) {
          var popValue = value.pop();

          _this.removeSelected(_this.isLabelInValue() ? popValue : popValue.value);
        }

        return;
      }

      if (keyCode === _KeyCode["default"].DOWN) {
        if (!state.open) {
          _this.openIfHasChildren();

          event.preventDefault();
          event.stopPropagation();
          return;
        }
      } else if (keyCode === _KeyCode["default"].ESC) {
        if (state.open) {
          _this.setOpenState(false);

          event.preventDefault();
          event.stopPropagation();
        }

        return;
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onSelect", function (selectedKeys, info) {
      var item = info.node;
      var value = _this.state.value;
      var props = _this.props;
      var selectedValue = (0, _util.getValuePropValue)(item);

      var selectedLabel = _this.getLabelFromNode(item);

      var checkableSelect = props.treeCheckable && info.event === 'select';
      var event = selectedValue;

      if (_this.isLabelInValue()) {
        event = {
          value: event,
          label: selectedLabel
        };
      }

      if (info.selected === false) {
        _this.onDeselect(info);

        if (!checkableSelect) return;
      }

      props.onSelect(event, item, info);
      var checkEvt = info.event === 'check';

      if ((0, _util.isMultiple)(props)) {
        _this.clearSearchInput();

        if (checkEvt) {
          value = _this.getCheckedNodes(info, props).map(function (n) {
            return {
              value: (0, _util.getValuePropValue)(n),
              label: _this.getLabelFromNode(n)
            };
          });
        } else {
          if (value.some(function (i) {
            return i.value === selectedValue;
          })) {
            return;
          }

          value = value.concat([{
            value: selectedValue,
            label: selectedLabel
          }]);
        }
      } else {
        if (value.length && value[0].value === selectedValue) {
          _this.setOpenState(false);

          return;
        }

        value = [{
          value: selectedValue,
          label: selectedLabel
        }];

        _this.setOpenState(false);
      }

      var extraInfo = {
        triggerValue: selectedValue,
        triggerNode: item
      };

      if (checkEvt) {
        extraInfo.checked = info.checked; // if inputValue existing, tree is checkStrictly

        extraInfo.allCheckedNodes = props.treeCheckStrictly || _this.state.inputValue ? info.checkedNodes : (0, _util.flatToHierarchy)(info.checkedNodesPositions);
        _this._checkedNodes = info.checkedNodesPositions;
        var _tree = _this.trigger.popupEle;
        _this._treeNodesStates = _tree.checkKeys;
      } else {
        extraInfo.selected = info.selected;
      }

      _this.fireChange(value, extraInfo); // 选中后判断是否需要清楚搜索值


      if (props.autoClearSearchValue) {
        _this.clearSearchInput();
      }

      if (props.inputValue && (0, _util.isEmpty)(_this.props.searchValue)) {
        _this.setState({
          inputValue: ''
        });
      } else {
        _this.setState({
          inputValue: _this.props.searchValue
        });
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onDeselect", function (info) {
      _this.removeSelected((0, _util.getValuePropValue)(info.node));

      if (!(0, _util.isMultiple)(_this.props)) {
        _this.setOpenState(false);
      } else {
        _this.clearSearchInput();
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onPlaceholderClick", function () {
      _this.getInputDOMNode().focus();
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onClearSelection", function (event) {
      var props = _this.props;
      var state = _this.state;

      if (props.disabled) {
        return;
      }

      event.stopPropagation();
      _this._cacheTreeNodesStates = 'no';
      _this._checkedNodes = [];

      if (state.inputValue || state.value.length) {
        _this.setOpenState(false);

        if (typeof props.inputValue === 'undefined') {
          _this.setState({
            inputValue: (0, _util.isEmpty)(_this.props.searchValue) ? '' : _this.props.searchValue
          }, function () {
            _this.fireChange([]);
          });
        } else {
          _this.fireChange([]);
        }
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onChoiceAnimationLeave", function () {
      _this.trigger.trigger.forcePopupAlign();
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onArrowClick", function (e) {
      e.stopPropagation();
      e.preventDefault();

      if (!_this.props.disabled) {
        _this.onDropdownVisibleChange(!_this.state.open);
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getPlaceholderElement", function () {
      var _assertThisInitialize2 = (0, _assertThisInitialized2["default"])(_this),
          props = _assertThisInitialize2.props,
          state = _assertThisInitialize2.state;

      var placeholder = props.placeholder;

      if (placeholder) {
        return /*#__PURE__*/_react["default"].createElement("div", {
          className: "".concat(props.prefixCls, "-selection__placeholder")
        }, placeholder);
      }

      return null;
    });
    var _value = [];

    if ('value' in _props2) {
      _value = (0, _util.toArray)(_props2.value);
    } else {
      _value = (0, _util.toArray)(_props2.defaultValue);
    } // save parsed treeData, for performance (treeData may be very big)


    _this.renderedTreeData = _this.renderTreeData();
    _value = _this.addLabelToValue(_props2, _value);
    _value = _this.getValue(_props2, _value, _props2.inputValue ? '__strict' : true);
    var inputValue = _props2.inputValue || '';

    if (!(0, _util.isEmpty)(_props2.searchValue)) {
      inputValue = String(_props2.searchValue);
    }

    _this.state = {
      value: _value,
      inputValue: inputValue,
      open: _props2.open || _props2.defaultOpen,
      focused: false
    };
    return _this;
  }

  (0, _createClass2["default"])(Select, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props = this.props,
          autoFocus = _this$props.autoFocus,
          disabled = _this$props.disabled;

      if ((0, _util.isMultiple)(this.props)) {
        var inputNode = this.getInputDOMNode();

        if (inputNode.value) {
          inputNode.style.width = '';
          inputNode.style.width = "".concat(this.inputMirrorInstance.clientWidth, "px");
        } else {
          inputNode.style.width = '';
        }
      }

      if (autoFocus && !disabled) {
        this.focus();
      }
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      // save parsed treeData, for performance (treeData may be very big)
      this.renderedTreeData = this.renderTreeData(nextProps); // Detecting whether the object of `onChange`'s argument  is old ref.
      // Better to do a deep equal later.

      this._cacheTreeNodesStates = this._cacheTreeNodesStates !== 'no' && this._savedValue && nextProps.value === this._savedValue;

      if (this.props.treeData !== nextProps.treeData || this.props.children !== nextProps.children) {
        // refresh this._treeNodesStates cache
        this._treeNodesStates = (0, _util.getTreeNodesStates)(this.renderedTreeData || nextProps.children, this.state.value.map(function (item) {
          return item.value;
        }));
      }

      if ('value' in nextProps) {
        var value = (0, _util.toArray)(nextProps.value);
        value = this.addLabelToValue(nextProps, value);
        value = this.getValue(nextProps, value);
        this.setState({
          value: value
        });

        if (nextProps.searchValue !== this.props.searchValue) {
          this.setState({
            inputValue: String(nextProps.searchValue)
          });
        }
      }

      if ((0, _util.isEmpty)(this.props.searchValue)) {
        if (nextProps.inputValue !== this.props.inputValue) {
          this.setState({
            inputValue: nextProps.inputValue
          });
        }
      } else {
        this.setState({
          inputValue: this.props.searchValue
        });
      }

      if ('open' in nextProps) {
        this.setState({
          open: nextProps.open
        });
      }
    }
  }, {
    key: "componentWillUpdate",
    value: function componentWillUpdate(nextProps) {
      if (this._savedValue && nextProps.value && nextProps.value !== this._savedValue && nextProps.value === this.props.value) {
        this._cacheTreeNodesStates = false;
        this.getValue(nextProps, this.addLabelToValue(nextProps, (0, _util.toArray)(nextProps.value)));
      }
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      var state = this.state;
      var props = this.props;

      if (state.open && (0, _util.isMultiple)(props)) {
        var inputNode = this.getInputDOMNode();

        if (inputNode.value) {
          inputNode.style.width = '';
          inputNode.style.width = "".concat(this.inputMirrorInstance.clientWidth, "px");
        } else {
          inputNode.style.width = '';
        }
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.clearDelayTimer();

      if (this.dropdownContainer) {
        (0, _reactDom.unmountComponentAtNode)(this.dropdownContainer);
        document.body.removeChild(this.dropdownContainer);
        this.dropdownContainer = null;
      }
    }
  }, {
    key: "getLabelFromNode",
    value: function getLabelFromNode(child) {
      return (0, _util.getPropValue)(child, this.props.treeNodeLabelProp);
    }
  }, {
    key: "getLabelFromProps",
    value: function getLabelFromProps(props, value) {
      var _this2 = this;

      if (value === undefined) {
        return null;
      }

      var label = null;
      (0, _util.loopAllChildren)(this.renderedTreeData || props.children, function (item) {
        if ((0, _util.getValuePropValue)(item) === value) {
          label = _this2.getLabelFromNode(item);
        }
      });

      if (label === null) {
        return value;
      }

      return label;
    }
  }, {
    key: "getDropdownContainer",
    value: function getDropdownContainer() {
      if (!this.dropdownContainer) {
        this.dropdownContainer = document.createElement('div');
        document.body.appendChild(this.dropdownContainer);
      }

      return this.dropdownContainer;
    }
  }, {
    key: "getSearchPlaceholderElement",
    value: function getSearchPlaceholderElement(hidden) {
      var props = this.props;
      var placeholder;

      if ((0, _util.isMultiple)(props)) {
        placeholder = props.placeholder || props.searchPlaceholder;
      } else {
        placeholder = props.searchPlaceholder;
      }

      if (placeholder) {
        return /*#__PURE__*/_react["default"].createElement("span", {
          style: {
            display: hidden ? 'none' : 'block'
          },
          onClick: this.onPlaceholderClick,
          className: "".concat(props.prefixCls, "-search__field__placeholder")
        }, placeholder);
      }

      return null;
    }
  }, {
    key: "getInputElement",
    value: function getInputElement() {
      var inputValue = this.state.inputValue;
      var _this$props2 = this.props,
          prefixCls = _this$props2.prefixCls,
          disabled = _this$props2.disabled;
      return /*#__PURE__*/_react["default"].createElement("span", {
        className: "".concat(prefixCls, "-search__field__wrap")
      }, /*#__PURE__*/_react["default"].createElement("input", {
        ref: (0, _util.saveRef)(this, 'inputInstance'),
        onChange: this.onInputChange,
        onKeyDown: this.onInputKeyDown,
        value: inputValue,
        disabled: disabled,
        className: "".concat(prefixCls, "-search__field"),
        role: "textbox"
      }), /*#__PURE__*/_react["default"].createElement("span", {
        ref: (0, _util.saveRef)(this, 'inputMirrorInstance'),
        className: "".concat(prefixCls, "-search__field__mirror")
      }, inputValue, "\xA0"), (0, _util.isMultiple)(this.props) ? null : this.getSearchPlaceholderElement(!!inputValue));
    }
  }, {
    key: "getInputDOMNode",
    value: function getInputDOMNode() {
      return this.inputInstance;
    }
  }, {
    key: "getPopupDOMNode",
    value: function getPopupDOMNode() {
      return this.trigger.getPopupDOMNode();
    }
  }, {
    key: "getPopupComponentRefs",
    value: function getPopupComponentRefs() {
      return this.trigger.getPopupEleRefs();
    }
  }, {
    key: "getValue",
    value: function getValue(_props, val) {
      var _this3 = this;

      var init = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
      var value = val; // if inputValue existing, tree is checkStrictly

      var _strict = init === '__strict' || init && (this.state && this.state.inputValue || this.props.inputValue !== _props.inputValue);

      if (_props.treeCheckable && (_props.treeCheckStrictly || _strict)) {
        this.halfCheckedValues = [];
        value = [];
        val.forEach(function (i) {
          if (!i.halfChecked) {
            value.push(i);
          } else {
            _this3.halfCheckedValues.push(i);
          }
        });
      } // if (!(_props.treeCheckable && !_props.treeCheckStrictly)) {


      if (!!!_props.treeCheckable || _props.treeCheckable && (_props.treeCheckStrictly || _strict)) {
        return value;
      }

      var checkedTreeNodes;

      if (this._cachetreeData && this._cacheTreeNodesStates && this._checkedNodes && this.state && !this.state.inputValue) {
        this.checkedTreeNodes = checkedTreeNodes = this._checkedNodes;
      } else {
        /**
         * Note: `this._treeNodesStates`'s treeNodesStates must correspond to nodes of the
         * final tree (`processTreeNode` function from SelectTrigger.jsx produce the final tree).
         *
         * And, `this._treeNodesStates` from `onSelect` is previous value,
         * so it perhaps only have a few nodes, but the newly filtered tree can have many nodes,
         * thus, you cannot use previous _treeNodesStates.
         */
        // getTreeNodesStates is not effective.
        this._treeNodesStates = (0, _util.getTreeNodesStates)(this.renderedTreeData || _props.children, value.map(function (item) {
          return item.value;
        }));
        this.checkedTreeNodes = checkedTreeNodes = this._treeNodesStates.checkedNodes;
      }

      var mapLabVal = function mapLabVal(arr) {
        return arr.map(function (itemObj) {
          return {
            value: (0, _util.getValuePropValue)(itemObj.node),
            label: (0, _util.getPropValue)(itemObj.node, _props.treeNodeLabelProp)
          };
        });
      };

      var props = this.props;
      var checkedValues = [];

      if (props.showCheckedStrategy === _strategies.SHOW_ALL) {
        checkedValues = mapLabVal(checkedTreeNodes);
      } else if (props.showCheckedStrategy === _strategies.SHOW_PARENT) {
        var posArr = (0, _util.filterParentPosition)(checkedTreeNodes.map(function (itemObj) {
          return itemObj.pos;
        }));
        checkedValues = mapLabVal(checkedTreeNodes.filter(function (itemObj) {
          return posArr.indexOf(itemObj.pos) !== -1;
        }));
      } else {
        checkedValues = mapLabVal(checkedTreeNodes.filter(function (itemObj) {
          return !itemObj.node.props.children;
        }));
      }

      return checkedValues;
    }
  }, {
    key: "getCheckedNodes",
    value: function getCheckedNodes(info, props) {
      // TODO treeCheckable does not support tags/dynamic
      var checkedNodes = info.checkedNodes;
      var checkNodeProps = checkedNodes.forEach(function (item) {
        if (!item.props) {
          item.props = item;
        }

        return item;
      });

      if (props.treeCheckStrictly || this.state.inputValue) {
        return checkNodeProps;
      }

      var checkedNodesPositions = info.checkedNodesPositions;

      if (props.showCheckedStrategy === _strategies.SHOW_ALL) {
        checkNodeProps = checkNodeProps;
      } else if (props.showCheckedStrategy === _strategies.SHOW_PARENT) {
        var posArr = (0, _util.filterParentPosition)(checkedNodesPositions.map(function (itemObj) {
          return itemObj.pos;
        }));
        checkNodeProps = checkedNodesPositions.filter(function (itemObj) {
          return posArr.indexOf(itemObj.pos) !== -1;
        }).map(function (itemObj) {
          return itemObj.node;
        });
      } else {
        checkNodeProps = checkNodeProps.filter(function (n) {
          return !n.props.children;
        });
      }

      return checkNodeProps;
    }
  }, {
    key: "getDeselectedValue",
    value: function getDeselectedValue(selectedValue) {
      var checkedTreeNodes = this.checkedTreeNodes;
      var unCheckPos;
      checkedTreeNodes.forEach(function (itemObj) {
        if (itemObj.node.props.value === selectedValue) {
          unCheckPos = itemObj.pos;
        }
      });
      var newVals = [];
      var newCkTns = [];
      checkedTreeNodes.forEach(function (itemObj) {
        if ((0, _util.isPositionPrefix)(itemObj.pos, unCheckPos) || (0, _util.isPositionPrefix)(unCheckPos, itemObj.pos)) {
          // Filter ancestral and children nodes when uncheck a node.
          return;
        }

        newCkTns.push(itemObj);
        newVals.push(itemObj.node.props.value);
      });
      this.checkedTreeNodes = this._checkedNodes = newCkTns;
      var nv = this.state.value.filter(function (val) {
        return newVals.indexOf(val.value) !== -1;
      });
      this.fireChange(nv, {
        triggerValue: selectedValue,
        clear: true
      });
    }
  }, {
    key: "setOpenState",
    value: function setOpenState(open, needFocus) {
      var _this4 = this;

      var documentClickClose = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      this.clearDelayTimer();
      var props = this.props; // can not optimize, if children is empty
      // if (this.state.open === open) {
      //   return;
      // }

      if (!this.props.onDropdownVisibleChange(open, {
        documentClickClose: documentClickClose
      })) {
        return;
      }

      this.setState({
        open: open
      }, function () {
        if (needFocus || open) {
          // Input dom init after first time component render
          // Add delay for this to get focus
          Promise.resolve().then(function () {
            if (open || (0, _util.isMultiple)(props)) {
              var input = _this4.getInputDOMNode();

              if (input && document.activeElement !== input) {
                input.focus();
              }
            } else if (_this4.selection) {
              _this4.selection.focus();
            }
          });
        }
      });
    }
  }, {
    key: "clearSearchInput",
    value: function clearSearchInput() {
      var input = this.getInputDOMNode();

      if (input && document.activeElement !== input) {
        input.focus();
      }

      if (!('inputValue' in this.props)) {
        this.setState({
          inputValue: (0, _util.isEmpty)(this.props.searchValue) ? '' : (0, _util.isEmpty)(this.props.searchValue)
        });
      }
    }
  }, {
    key: "addLabelToValue",
    value: function addLabelToValue(props, value_) {
      var _this5 = this;

      var value = value_;

      if (this.isLabelInValue()) {
        value.forEach(function (v, i) {
          if (Object.prototype.toString.call(value[i]) !== '[object Object]') {
            value[i] = {
              value: '',
              label: ''
            };
            return;
          }

          v.label = v.label || _this5.getLabelFromProps(props, v.value);
        });
      } else {
        value = value.map(function (v) {
          return {
            value: v,
            label: _this5.getLabelFromProps(props, v)
          };
        });
      }

      return value;
    }
  }, {
    key: "clearDelayTimer",
    value: function clearDelayTimer() {
      if (this.delayTimer) {
        clearTimeout(this.delayTimer);
        this.delayTimer = null;
      }
    }
    /**
     * 移除select值
     * @param {*} selectedVal
     */

  }, {
    key: "removeSelected",
    value: function removeSelected(selectedVal) {
      var props = this.props;

      if (props.disabled) {
        return;
      }

      this._cacheTreeNodesStates = 'no';

      if (props.treeCheckable && (props.showCheckedStrategy === _strategies.SHOW_ALL || props.showCheckedStrategy === _strategies.SHOW_PARENT) && !(props.treeCheckStrictly || this.state.inputValue)) {
        this.getDeselectedValue(selectedVal);
        return;
      } // click the node's `x`(in select box), likely trigger the TreeNode's `unCheck` event,
      // cautiously, they are completely different, think about it, the tree may not render at first,
      // but the nodes in select box are ready.


      var label;
      var value = this.state.value.filter(function (singleValue) {
        if (singleValue.value === selectedVal) {
          label = singleValue.label;
        }

        return singleValue.value !== selectedVal;
      });
      var canMultiple = (0, _util.isMultiple)(props);

      if (canMultiple) {
        var event = selectedVal;

        if (this.isLabelInValue()) {
          event = {
            value: selectedVal,
            label: label
          };
        }

        props.onDeselect(event);
      }

      if (props.treeCheckable) {
        if (this.checkedTreeNodes && this.checkedTreeNodes.length) {
          this.checkedTreeNodes = this._checkedNodes = this.checkedTreeNodes.filter(function (item) {
            return value.some(function (i) {
              return i.value === item.node.props.value;
            });
          });
        }
      }

      this.fireChange(value, {
        triggerValue: selectedVal,
        clear: true
      });
    }
  }, {
    key: "openIfHasChildren",
    value: function openIfHasChildren() {
      var props = this.props;

      if (_react.Children.count(props.children) || !(0, _util.isMultiple)(props)) {
        this.setOpenState(true);
      }
    }
  }, {
    key: "fireChange",
    value: function fireChange(value) {
      var _this6 = this;

      var extraInfo = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var props = this.props;
      var vals = value.map(function (i) {
        return i.value;
      });
      var sv = this.state.value.map(function (i) {
        return i.value;
      });

      if (vals.length !== sv.length || !vals.every(function (val, index) {
        return sv[index] === val;
      })) {
        var ex = (0, _objectSpread2["default"])({
          preValue: (0, _toConsumableArray2["default"])(this.state.value)
        }, extraInfo);
        var labs = null;
        var vls = value;

        if (!this.isLabelInValue()) {
          labs = value.map(function (i) {
            return i.label;
          });
          vls = vls.map(function (v) {
            return v.value;
          });
        } else if (this.halfCheckedValues && this.halfCheckedValues.length) {
          this.halfCheckedValues.forEach(function (i) {
            if (!vls.some(function (v) {
              return v.value === i.value;
            })) {
              vls.push(i);
            }
          });
        }

        if (props.treeCheckable && ex.clear) {
          var treeData = this.renderedTreeData || props.children;
          ex.allCheckedNodes = (0, _util.flatToHierarchy)((0, _util.filterAllCheckedData)(vals, treeData));
        }

        if (props.treeCheckable && this.state.inputValue) {
          var _vls = (0, _toConsumableArray2["default"])(this.state.value);

          if (ex.checked) {
            value.forEach(function (i) {
              if (_vls.every(function (ii) {
                return ii.value !== i.value;
              })) {
                _vls.push((0, _objectSpread2["default"])({}, i));
              }
            });
          } else {
            var index;

            var includeVal = _vls.some(function (i, ind) {
              if (i.value === ex.triggerValue) {
                index = ind;
                return true;
              }
            });

            if (includeVal) {
              _vls.splice(index, 1);
            }
          }

          vls = _vls;

          if (!this.isLabelInValue()) {
            labs = _vls.map(function (v) {
              return v.label;
            });
            vls = _vls.map(function (v) {
              return v.value;
            });
          }
        }

        this._savedValue = (0, _util.isMultiple)(props) ? vls : vls[0];
        props.onChange(this._savedValue, labs, ex);

        if (!('value' in props)) {
          this._cacheTreeNodesStates = false;
          this.setState({
            value: this.getValue(props, (0, _util.toArray)(this._savedValue).map(function (v, i) {
              return _this6.isLabelInValue() ? v : {
                value: v,
                label: labs && labs[i]
              };
            }))
          });
        }
      }
    }
  }, {
    key: "isLabelInValue",
    value: function isLabelInValue() {
      var _this$props3 = this.props,
          treeCheckable = _this$props3.treeCheckable,
          treeCheckStrictly = _this$props3.treeCheckStrictly,
          labelInValue = _this$props3.labelInValue;

      if (treeCheckable && treeCheckStrictly) {
        return true;
      }

      return labelInValue || false;
    }
  }, {
    key: "focus",
    value: function focus() {
      if (!(0, _util.isMultiple)(this.props)) {
        this.selection.focus();
      } else {
        this.getInputDOMNode().focus();
      }
    }
  }, {
    key: "blur",
    value: function blur() {
      if (!(0, _util.isMultiple)(this.props)) {
        this.selection.blur();
      } else {
        this.getInputDOMNode().blur();
      }
    }
  }, {
    key: "renderClear",
    value: function renderClear() {
      var _this$props4 = this.props,
          prefixCls = _this$props4.prefixCls,
          allowClear = _this$props4.allowClear;
      var _this$state = this.state,
          value = _this$state.value,
          inputValue = _this$state.inputValue;

      var clear = /*#__PURE__*/_react["default"].createElement(_Button["default"], (0, _extends2["default"])({
        key: "clear",
        className: "".concat(prefixCls, "-clear"),
        style: _util.UNSELECTABLE_STYLE
      }, _util.UNSELECTABLE_ATTRIBUTE, {
        shape: "circle",
        icon: "close",
        size: "small",
        onClick: this.onClearSelection,
        onMouseDown: _util.preventDefaultEvent
      }));

      if (!allowClear) {
        return null;
      }

      if (inputValue || value.length) {
        return clear;
      }

      return null;
    }
  }, {
    key: "renderTopControlNode",
    value: function renderTopControlNode() {
      var _this7 = this;

      var value = this.state.value;
      var props = this.props;
      var labelInValue = props.labelInValue,
          choiceTransitionName = props.choiceTransitionName,
          prefixCls = props.prefixCls,
          maxTagTextLength = props.maxTagTextLength,
          maxTagCount = props.maxTagCount,
          maxTagPlaceholder = props.maxTagPlaceholder,
          choiceRender = props.choiceRender;
      var multiple = (0, _util.isMultiple)(props); // single and not combobox, input is inside dropdown

      if (!multiple) {
        var singleValue = value && value[0];

        var _ref = singleValue || {},
            label = _ref.label;

        var innerNode = /*#__PURE__*/_react["default"].createElement("span", {
          key: "value",
          title: label,
          className: "".concat(prefixCls, "-selection-selected-value")
        }, choiceRender ? choiceRender(label) : label);

        return /*#__PURE__*/_react["default"].createElement("div", {
          className: "".concat(prefixCls, "-selection__rendered")
        }, this.getPlaceholderElement(), innerNode, this.renderClear(), multiple || !props.showArrow ? null : /*#__PURE__*/_react["default"].createElement("span", (0, _extends2["default"])({
          key: "arrow",
          className: "".concat(prefixCls, "-arrow"),
          style: _util.UNSELECTABLE_STYLE
        }, _util.UNSELECTABLE_ATTRIBUTE, {
          onClick: this.onArrowClick
        }), /*#__PURE__*/_react["default"].createElement("i", {
          className: "icon icon-arrow_drop_down"
        }), /*#__PURE__*/_react["default"].createElement("b", null)));
      } // Check if `maxTagCount` is set


      var myValueList = value;

      if (maxTagCount >= 0) {
        myValueList = value.slice(0, maxTagCount);
      }

      var selectedValueNodes = myValueList.map(function (singleValue) {
        var content = singleValue.label;
        var title = content;

        if (maxTagTextLength && typeof content === 'string' && content.length > maxTagTextLength) {
          content = "".concat(content.slice(0, maxTagTextLength), "...");
        }

        return /*#__PURE__*/_react["default"].createElement("li", (0, _extends2["default"])({
          style: _util.UNSELECTABLE_STYLE
        }, _util.UNSELECTABLE_ATTRIBUTE, {
          onMouseDown: _util.preventDefaultEvent,
          className: "".concat(prefixCls, "-selection__choice"),
          key: singleValue.value,
          title: title
        }), /*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-selection__choice__remove"),
          onClick: _this7.removeSelected.bind(_this7, singleValue.value)
        }, /*#__PURE__*/_react["default"].createElement("i", {
          className: "icon icon-cancel"
        })), /*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-selection__choice__content")
        }, content));
      });

      if (maxTagCount >= 0 && maxTagCount < value.length) {
        var content = "+ ".concat(value.length - maxTagCount, " ...");

        if (typeof maxTagPlaceholder === 'string') {
          content = maxTagPlaceholder;
        } else if (typeof maxTagPlaceholder === 'function') {
          var restValueList = value.slice(maxTagCount);
          content = maxTagPlaceholder(labelInValue ? restValueList : restValueList.map(function (_ref2) {
            var value = _ref2.value;
            return value;
          }));
        }

        var restNodeSelect = /*#__PURE__*/_react["default"].createElement("li", (0, _extends2["default"])({
          style: _util.UNSELECTABLE_STYLE
        }, _util.UNSELECTABLE_ATTRIBUTE, {
          onMouseDown: _util.preventDefaultEvent,
          className: "".concat(prefixCls, "-selection__choice"),
          key: "rc-tree-select-internal-max-tag-counter",
          title: content
        }), /*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-selection__choice__content")
        }, content));

        selectedValueNodes.push(restNodeSelect);
      }

      selectedValueNodes.push( /*#__PURE__*/_react["default"].createElement("li", {
        className: "".concat(prefixCls, "-search ").concat(prefixCls, "-search--inline"),
        key: "__input"
      }, this.getInputElement()));
      var className = "".concat(prefixCls, "-selection__rendered");

      if (choiceTransitionName) {
        return /*#__PURE__*/_react["default"].createElement("div", {
          className: className
        }, /*#__PURE__*/_react["default"].createElement(_animate["default"], {
          component: "ul",
          transitionName: choiceTransitionName,
          onLeave: this.onChoiceAnimationLeave
        }, selectedValueNodes));
      }

      return /*#__PURE__*/_react["default"].createElement("ul", {
        className: className
      }, selectedValueNodes);
    }
  }, {
    key: "renderTreeData",
    value: function renderTreeData(props) {
      var validProps = props || this.props;

      if (validProps.treeData) {
        if (props && props.treeData === this.props.treeData && this.renderedTreeData) {
          // cache and use pre data.
          this._cachetreeData = true;
          return this.renderedTreeData;
        }

        this._cachetreeData = false;
        var treeData = (0, _toConsumableArray2["default"])(validProps.treeData); // process treeDataSimpleMode

        if (validProps.treeDataSimpleMode) {
          var simpleFormat = {
            id: 'id',
            pId: 'pId',
            rootPId: null
          };

          if (Object.prototype.toString.call(validProps.treeDataSimpleMode) === '[object Object]') {
            simpleFormat = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, simpleFormat), validProps.treeDataSimpleMode);
          }

          treeData = (0, _util.processSimpleTreeData)(treeData, simpleFormat);
        }

        return loopTreeData(treeData, undefined, this.props.treeCheckable);
      }
    }
  }, {
    key: "getUnderLine",
    value: function getUnderLine() {
      var _this$props5 = this.props,
          prefixCls = _this$props5.prefixCls,
          className = _this$props5.className;

      if (className && className.includes("".concat(prefixCls, "-auto-complete"))) {
        return null;
      }

      return /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(prefixCls, "-underline")
      }, /*#__PURE__*/_react["default"].createElement("span", {
        className: "".concat(prefixCls, "-ripple")
      }));
    }
  }, {
    key: "render",
    value: function render() {
      var _rootCls;

      var props = this.props;
      var multiple = (0, _util.isMultiple)(props);
      var _this$state2 = this.state,
          open = _this$state2.open,
          focused = _this$state2.focused,
          inputValue = _this$state2.inputValue,
          value = _this$state2.value;
      var className = props.className,
          disabled = props.disabled,
          label = props.label,
          prefixCls = props.prefixCls;
      var ctrlNode = this.renderTopControlNode();
      var extraSelectionProps = {};

      if (!multiple) {
        extraSelectionProps = {
          onKeyDown: this.onKeyDown,
          tabIndex: 0
        };
      }

      var rootCls = (_rootCls = {}, (0, _defineProperty2["default"])(_rootCls, className, !!className), (0, _defineProperty2["default"])(_rootCls, prefixCls, 1), (0, _defineProperty2["default"])(_rootCls, "".concat(prefixCls, "-has-border"), 1), (0, _defineProperty2["default"])(_rootCls, "".concat(prefixCls, "-open"), open), (0, _defineProperty2["default"])(_rootCls, "".concat(prefixCls, "-focused"), open || focused), (0, _defineProperty2["default"])(_rootCls, "".concat(prefixCls, "-has-value"), inputValue || value.length && value[0]), (0, _defineProperty2["default"])(_rootCls, "".concat(prefixCls, "-has-label"), label), (0, _defineProperty2["default"])(_rootCls, "".concat(prefixCls, "-multiple"), multiple), (0, _defineProperty2["default"])(_rootCls, "".concat(prefixCls, "-disabled"), disabled), (0, _defineProperty2["default"])(_rootCls, "".concat(prefixCls, "-enabled"), !disabled), (0, _defineProperty2["default"])(_rootCls, "".concat(prefixCls, "-allow-clear"), !!props.allowClear), _rootCls);
      return /*#__PURE__*/_react["default"].createElement(_SelectTrigger["default"], (0, _extends2["default"])({}, props, {
        treeNodes: props.children,
        treeData: this.renderedTreeData,
        _cachetreeData: this._cachetreeData,
        _treeNodesStates: this._treeNodesStates,
        halfCheckedValues: this.halfCheckedValues,
        multiple: multiple,
        disabled: disabled,
        visible: open,
        inputValue: inputValue,
        inputElement: this.getInputElement(),
        value: value,
        onDropdownVisibleChange: this.onDropdownVisibleChange,
        getPopupContainer: props.getPopupContainer,
        onSelect: this.onSelect,
        ref: (0, _util.saveRef)(this, 'trigger')
      }), /*#__PURE__*/_react["default"].createElement("div", {
        style: props.style,
        onClick: props.onClick,
        className: (0, _classnames["default"])(rootCls),
        onBlur: props.onBlur,
        onFocus: props.onFocus
      }, /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({
        ref: (0, _util.saveRef)(this, 'selection'),
        key: "selection",
        className: "".concat(prefixCls, "-selection\n            ").concat(prefixCls, "-selection--").concat(multiple ? 'multiple' : 'single'),
        role: "combobox",
        "aria-autocomplete": "list",
        "aria-haspopup": "true",
        "aria-expanded": open
      }, extraSelectionProps), ctrlNode, multiple ? this.getSearchPlaceholderElement(!!inputValue || value.length) : null), this.getUnderLine()));
    }
  }]);
  return Select;
}(_react.Component);

exports["default"] = Select;
(0, _defineProperty2["default"])(Select, "defaultProps", {
  prefixCls: 'rc-tree-select',
  filterTreeNode: filterFn,
  showSearch: true,
  allowClear: false,
  placeholder: '',
  searchPlaceholder: '',
  labelInValue: false,
  onClick: _noop["default"],
  onChange: _noop["default"],
  onSelect: _noop["default"],
  onDeselect: _noop["default"],
  onSearch: _noop["default"],
  showArrow: true,
  dropdownMatchSelectWidth: true,
  dropdownStyle: {},
  autoClearSearchValue: true,
  onDropdownVisibleChange: function onDropdownVisibleChange() {
    return true;
  },
  optionLabelProp: 'value',
  notFoundContent: 'Not Found',
  showCheckedStrategy: _strategies.SHOW_CHILD,
  // skipHandleInitValue: false, // Deprecated (use treeCheckStrictly)
  treeCheckStrictly: false,
  treeIcon: false,
  treeLine: false,
  treeDataSimpleMode: false,
  treeDefaultExpandAll: false,
  treeCheckable: false,
  treeNodeFilterProp: 'value',
  treeNodeLabelProp: 'title',
  searchValue: ''
});
(0, _defineProperty2["default"])(Select, "SHOW_ALL", _strategies.SHOW_ALL);
(0, _defineProperty2["default"])(Select, "SHOW_PARENT", _strategies.SHOW_PARENT);
(0, _defineProperty2["default"])(Select, "SHOW_CHILD", _strategies.SHOW_CHILD);
//# sourceMappingURL=Select.js.map
