"use strict";

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

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

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

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

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

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 _get2 = _interopRequireDefault(require("@babel/runtime/helpers/get"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

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

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

var _tslib = require("tslib");

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

var _omit = _interopRequireDefault(require("lodash/omit"));

var _isPlainObject = _interopRequireDefault(require("lodash/isPlainObject"));

var _isNil = _interopRequireDefault(require("lodash/isNil"));

var _defer = _interopRequireDefault(require("lodash/defer"));

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

var _debounce = _interopRequireDefault(require("lodash/debounce"));

var _throttle = _interopRequireDefault(require("lodash/throttle"));

var _isString = _interopRequireDefault(require("lodash/isString"));

var _mobxReact = require("mobx-react");

var _moment = require("moment");

var _mobx = require("mobx");

var _UnitConvertor = require("../../../../lib/_util/UnitConvertor");

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

var _icon = _interopRequireDefault(require("../../icon"));

var _TextField2 = require("../../text-field/TextField");

var _autobind = _interopRequireDefault(require("../../_util/autobind"));

var _utils = require("../utils");

var _Select = _interopRequireDefault(require("../../select/Select"));

var _Option = _interopRequireDefault(require("../../option/Option"));

var _isSameLike = _interopRequireDefault(require("../../_util/isSameLike"));

var _enum = require("../../data-set/enum");

var _utils2 = require("../../field/utils");

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

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

  function FilterSelect(props, context) {
    var _this;

    (0, _classCallCheck2["default"])(this, FilterSelect);
    _this = _super.call(this, props, context);
    _this.setFilterText = (0, _debounce["default"])((0, _mobx.action)(function (text) {
      _this.filterText = text;
    }), 500);
    _this.doQuery = (0, _throttle["default"])(function () {
      var _this$props$onQuery = _this.props.onQuery,
          onQuery = _this$props$onQuery === void 0 ? _noop["default"] : _this$props$onQuery;
      var optionDataSet = _this.observableProps.optionDataSet;
      optionDataSet.query();
      onQuery();
    }, 500);

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

    _this.on(observableProps.queryDataSet);

    _this.reaction = (0, _mobx.reaction)(function () {
      return observableProps.queryDataSet;
    }, _this.on);
    return _this;
  }

  (0, _createClass2["default"])(FilterSelect, [{
    key: "getPrefix",
    value: function getPrefix() {
      var _this$props$prefix = this.props.prefix,
          prefix = _this$props$prefix === void 0 ? /*#__PURE__*/_react["default"].createElement(_icon["default"], {
        type: "filter_list"
      }) : _this$props$prefix;

      if (prefix) {
        return this.wrapperPrefix(prefix);
      }
    }
  }, {
    key: "value",
    get: function get() {
      var filter = this.props.filter;
      var _this$observableProps = this.observableProps,
          value = _this$observableProps.value,
          queryDataSet = _this$observableProps.queryDataSet;

      if (value) {
        return filter ? value.filter(filter) : value;
      }

      var paramName = this.props.paramName;

      if (queryDataSet) {
        var current = queryDataSet.current;

        if (current) {
          var result = [];
          var keys = queryDataSet.fields.keys();
          (paramName ? (0, _toConsumableArray2["default"])(new Set([].concat((0, _toConsumableArray2["default"])(keys), [paramName]))) : (0, _toConsumableArray2["default"])(keys)).forEach(function (key) {
            if (key && (!filter || filter(key))) {
              var values = current.get(key);

              if ((0, _mobx.isArrayLike)(values)) {
                var field = current.getField(key);

                if (field && field.get('multiple', current)) {
                  values.forEach(function (item) {
                    return !(0, _isNil["default"])(item) && result.push(key);
                  });
                } else if (values.some(function (item) {
                  return !(0, _isNil["default"])(item);
                })) {
                  result.push(key);
                }
              } else if (!(0, _isNil["default"])(values)) {
                result.push(key);
              }
            }
          });
          return result;
        }
      }

      return undefined;
    },
    set: function set(value) {
      var _this2 = this;

      (0, _mobx.runInAction)(function () {
        _this2.observableProps.value = value;
      });
    }
  }, {
    key: "getObservableProps",
    value: function getObservableProps(props, context) {
      return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, (0, _get2["default"])((0, _getPrototypeOf2["default"])(FilterSelect.prototype), "getObservableProps", this).call(this, props, context)), {}, {
        optionDataSet: props.optionDataSet,
        queryDataSet: props.queryDataSet
      });
    }
  }, {
    key: "on",
    value: function on(ds) {
      this.off();

      if (ds) {
        ds.addEventListener(_enum.DataSetEvents.update, this.handleDataSetUpdate);
        ds.addEventListener(_enum.DataSetEvents.reset, this.handleDataSetReset);
      }

      this.queryDataSet = ds;
    }
  }, {
    key: "off",
    value: function off() {
      var queryDataSet = this.queryDataSet;

      if (queryDataSet) {
        queryDataSet.removeEventListener(_enum.DataSetEvents.update, this.handleDataSetUpdate);
        queryDataSet.removeEventListener(_enum.DataSetEvents.reset, this.handleDataSetReset);
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      (0, _get2["default"])((0, _getPrototypeOf2["default"])(FilterSelect.prototype), "componentWillUnmount", this).call(this);
      this.setFilterText.cancel();
      this.off();
      this.reaction();
    }
  }, {
    key: "setText",
    value: function setText(text) {
      (0, _get2["default"])((0, _getPrototypeOf2["default"])(FilterSelect.prototype), "setText", this).call(this, text);
      this.setFilterText(text);
    }
  }, {
    key: "getPlaceholders",
    value: function getPlaceholders() {
      if (!this.selectField) {
        return (0, _get2["default"])((0, _getPrototypeOf2["default"])(FilterSelect.prototype), "getPlaceholders", this).call(this);
      }

      return [];
    }
  }, {
    key: "getOmitPropsKeys",
    value: function getOmitPropsKeys() {
      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(FilterSelect.prototype), "getOmitPropsKeys", this).call(this).concat(['paramName', 'optionDataSet', 'queryDataSet', 'dropdownMenuStyle', 'hiddenIfNone', 'editable', 'filter']);
    }
  }, {
    key: "getRootDomNode",
    value: function getRootDomNode() {
      return this.element;
    }
  }, {
    key: "defaultRenderer",
    value: function defaultRenderer(_ref) {
      var _this3 = this;

      var value = _ref.value,
          _ref$repeat = _ref.repeat,
          repeat = _ref$repeat === void 0 ? 0 : _ref$repeat;
      var paramName = this.props.paramName;
      var queryDataSet = this.observableProps.queryDataSet;

      if (queryDataSet) {
        var current = queryDataSet.current;

        if (current) {
          var fieldValue = current.get(value);

          if (value === paramName) {
            return fieldValue;
          }

          var field = queryDataSet.getField(value);

          if (field) {
            var range = field.get('range', current);

            if (field.get('multiple', current)) {
              fieldValue = (fieldValue || [])[repeat];
            }

            var showInvalidDate = this.getContextConfig('showInvalidDate');
            var processValueOptions = {
              dateFormat: this.getDateFormat(field),
              showInvalidDate: showInvalidDate,
              isNumber: [_enum.FieldType.number, _enum.FieldType.currency, _enum.FieldType.bigNumber].includes(field.get('type', current)),
              precision: field && field.get('precision', current),
              useZeroFilledDecimal: this.getContextConfig('useZeroFilledDecimal')
            };

            if (range) {
              return "".concat(this.getFieldLabel(field, current), ": ").concat((0, _utils2.toRangeValue)(fieldValue, range).map(function (v) {
                return (0, _utils2.processFieldValue)((0, _isPlainObject["default"])(v) ? v : (0, _utils2.processValue)(v, processValueOptions), field, {
                  getProp: function getProp(name) {
                    return _this3.getProp(name);
                  },
                  getValue: function getValue() {
                    return _this3.getValue();
                  },
                  lang: _this3.lang,
                  getDisplayProp: function getDisplayProp(name) {
                    return _this3.getDisplayProp(name);
                  }
                }, undefined, current, _this3.getContextConfig);
              }).join('~'));
            }

            if (field.get('bind', current) || (0, _isNil["default"])(fieldValue)) return;
            var text = this.processText((0, _isNil["default"])(fieldValue) ? (0, _utils2.processValue)(value, processValueOptions) : (0, _moment.isMoment)(fieldValue) ? (0, _utils2.processValue)(fieldValue, processValueOptions) : fieldValue);
            return "".concat(this.getFieldLabel(field, current), ": ").concat((0, _utils2.processFieldValue)((0, _isPlainObject["default"])(fieldValue) ? fieldValue : text, field, {
              getProp: function getProp(name) {
                return _this3.getProp(name);
              },
              getValue: function getValue() {
                return _this3.getValue();
              },
              lang: this.lang,
              getDisplayProp: function getDisplayProp(name) {
                return _this3.getDisplayProp(name);
              }
            }, undefined, current, this.getContextConfig));
          }

          return value;
        }
      }
    }
  }, {
    key: "getQueryRecord",
    value: function getQueryRecord() {
      var queryDataSet = this.observableProps.queryDataSet;

      if (queryDataSet) {
        return queryDataSet.current;
      }
    }
  }, {
    key: "getQueryField",
    value: function getQueryField(fieldName) {
      var queryDataSet = this.observableProps.queryDataSet;

      if (queryDataSet) {
        return queryDataSet.getField(fieldName);
      }
    }
  }, {
    key: "addQueryParams",
    value: function addQueryParams(value) {
      var paramName = this.props.paramName;

      if (paramName) {
        this.setQueryValue(paramName, value);
      }
    }
  }, {
    key: "afterRemoveValue",
    value: function afterRemoveValue(value, repeat) {
      var values = this.getQueryValues(value);

      if (repeat === -1) {
        values.pop();
      } else {
        values.splice(repeat, 1);
      }

      var multiple = this.getQueryFieldMultiple(value);
      this.setQueryValue(value, multiple ? values : values[0]);
    }
  }, {
    key: "getQueryFieldMultiple",
    value: function getQueryFieldMultiple(value) {
      var paramName = this.props.paramName;

      if (paramName !== value) {
        var field = this.getQueryField(value);

        if (field && field.get('multiple', this.getQueryRecord())) {
          return true;
        }
      }

      return false;
    }
  }, {
    key: "handleDataSetReset",
    value: function handleDataSetReset() {
      var _this$props$onReset = this.props.onReset,
          onReset = _this$props$onReset === void 0 ? _noop["default"] : _this$props$onReset;
      this.setValue(undefined);
      onReset();
    }
  }, {
    key: "handleDataSetUpdate",
    value: function handleDataSetUpdate(_ref2) {
      var name = _ref2.name,
          value = _ref2.value,
          record = _ref2.record;
      var values = this.getValues();

      if ((0, _mobx.isArrayLike)(value)) {
        var length = value.length;

        if (length) {
          var field = record.getField(name);

          if (field && field.get('multiple', record)) {
            var repeat = 0;
            var filtered = values.filter(function (item) {
              if (item === name) {
                repeat += 1;

                if (repeat > length) {
                  return false;
                }
              }

              return true;
            });

            for (var i = 0, n = length - repeat; i < n; i += 1) {
              filtered.push(name);
            }

            this.setValue(filtered);
          } else if (values.indexOf(name) === -1) {
            values.push(name);
            this.setValue(values);
          }
        } else {
          this.setValue(values.filter(function (item) {
            return item !== name;
          }));
        }
      } else if ((0, _isNil["default"])(value)) {
        this.setValue(values.filter(function (item) {
          return item !== name;
        }));
      } else {
        if (values.indexOf(name) === -1) {
          values.push(name);
        }

        this.setValue(values);
      }

      if (!this.isDoClear) {
        this.doQuery();
      }
    }
  }, {
    key: "handleBlur",
    value: function handleBlur(e) {
      (0, _get2["default"])((0, _getPrototypeOf2["default"])(FilterSelect.prototype), "handleBlur", this).call(this, e);

      if (!e.isDefaultPrevented()) {
        this.setSelectField(undefined);
      }
    }
  }, {
    key: "isEditorReadOnly",
    value: function isEditorReadOnly() {
      var _this$props = this.props,
          paramName = _this$props.paramName,
          editable = _this$props.editable;
      return this.getQueryValues(paramName).length > 0 && !this.selectField || !editable;
    }
  }, {
    key: "handleFieldChange",
    value: function handleFieldChange(value) {
      var selectField = this.selectField;

      if (selectField) {
        var name = selectField.name;
        this.setQueryValue(name, value);
      } else if ((0, _isString["default"])(value)) {
        this.addQueryParams(value);

        if (this.isFocused) {
          this.element.expand();
        }
      } else {
        this.setSelectField(value);
      }
    }
  }, {
    key: "handleInput",
    value: function handleInput(e) {
      this.setText(e.target.value);
    }
  }, {
    key: "handleFieldEnterDown",
    value: function handleFieldEnterDown() {
      var _this4 = this;

      (0, _defer["default"])(function () {
        return _this4.focus();
      });
    }
  }, {
    key: "handleKeyDown",
    value: function handleKeyDown(e) {
      if (this.selectField) {
        if (e.keyCode === _KeyCode["default"].BACKSPACE && !this.text) {
          this.setSelectField(undefined);
        }
      } else {
        (0, _get2["default"])((0, _getPrototypeOf2["default"])(FilterSelect.prototype), "handleKeyDown", this).call(this, e);
      }
    }
  }, {
    key: "handleEnterDown",
    value: function handleEnterDown() {// noop
    }
  }, {
    key: "setSelectField",
    value: function setSelectField(value) {
      this.selectField = value;
      this.setFilterText(undefined);
    }
  }, {
    key: "getQueryValues",
    value: function getQueryValues(fieldName) {
      var current = this.getQueryRecord();
      var field = this.getQueryField(fieldName);
      var range = field && field.get('range', current);

      if (current) {
        var value = (0, _mobx.toJS)(current.get(fieldName)) || [];
        return [].concat(!range ? value : [value]);
      }

      return [];
    }
  }, {
    key: "syncValueOnBlur",
    value: function syncValueOnBlur() {// noop
    }
  }, {
    key: "setQueryValue",
    value: function setQueryValue(fieldName, value) {
      var current = this.getQueryRecord();

      if (current) {
        current.set(fieldName, value);
      }

      this.setSelectField(undefined);
    }
  }, {
    key: "getFieldLabel",
    value: function getFieldLabel(field, record) {
      return field.get('label', record) || field.name;
    }
  }, {
    key: "multipleFieldExistsValue",
    value: function multipleFieldExistsValue(field, current) {
      if (field.get('multiple', current)) {
        var options = field.getOptions(current);

        if (options && current) {
          var values = current.get(field.name);
          var valueField = field.get('valueField', current);
          return options.some(function (r) {
            return !values.some(function (value) {
              return (0, _isSameLike["default"])(r.get(valueField), value);
            });
          });
        }
      }

      return false;
    }
  }, {
    key: "getInputFilterOptions",
    value: function getInputFilterOptions(filterText) {
      var _this$observableProps2 = this.observableProps,
          optionDataSet = _this$observableProps2.optionDataSet,
          fields = _this$observableProps2.optionDataSet.fields;
      var values = new Set();
      optionDataSet.forEach(function (record) {
        fields.forEach(function (_, key) {
          var value = record.get(key);

          if ((0, _isString["default"])(value) && value.toLowerCase().indexOf(filterText.toLowerCase()) !== -1) {
            values.add(value);
          }
        });
      });
      return (0, _toConsumableArray2["default"])(values).map(function (value) {
        return /*#__PURE__*/_react["default"].createElement(_Option["default"], {
          key: value,
          value: value
        }, value);
      });
    }
  }, {
    key: "getFieldSelectOptions",
    value: function getFieldSelectOptions() {
      var _this5 = this;

      var paramName = this.props.paramName;
      var queryDataSet = this.observableProps.queryDataSet;
      var data = [];

      if (queryDataSet) {
        var current = queryDataSet.current;
        queryDataSet.fields.forEach(function (field, key) {
          if (key !== paramName && (_this5.getValues().indexOf(key) === -1 || _this5.multipleFieldExistsValue(field, current)) && !field.get('bind', current)) {
            data.push( /*#__PURE__*/_react["default"].createElement(_Option["default"], {
              key: String(key),
              value: field
            }, _this5.getFieldLabel(field, current)));
          }
        });
      }

      return data;
    }
  }, {
    key: "getFieldEditor",
    value: function getFieldEditor(props, selectField) {
      var current = this.queryDataSet ? this.queryDataSet.current : undefined;
      var editor = (0, _utils.getEditorByField)(selectField, current, true);
      var editorProps = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, props), {}, {
        key: 'value',
        record: this.getQueryRecord(),
        name: selectField.name,
        autoFocus: true,
        onInput: this.handleInput,
        onEnterDown: this.handleFieldEnterDown,
        renderer: _noop["default"],
        isFlat: true
      });

      if (editor.type.__PRO_SELECT) {
        editorProps.dropdownMenuStyle = this.props.dropdownMenuStyle;
        editorProps.dropdownMatchSelectWidth = false;
      }

      return /*#__PURE__*/(0, _react.cloneElement)(editor, editorProps);
    }
  }, {
    key: "getFieldSelect",
    value: function getFieldSelect(props) {
      var filterText = this.filterText,
          dropdownMenuStyle = this.props.dropdownMenuStyle;
      var editable = !this.isEditorReadOnly();
      var options = editable && filterText ? this.getInputFilterOptions(filterText) : this.getFieldSelectOptions();
      return /*#__PURE__*/_react["default"].createElement(_Select["default"], (0, _extends2["default"])({}, props, {
        key: "key",
        combo: editable,
        searchable: editable,
        value: null,
        onInput: this.handleInput,
        onEnterDown: this.handleFieldEnterDown,
        autoFocus: this.isFocused,
        dropdownMenuStyle: dropdownMenuStyle,
        dropdownMatchSelectWidth: false
      }), options);
    }
  }, {
    key: "clear",
    value: function clear() {
      var record = this.getQueryRecord();
      this.isDoClear = true;

      if (record) {
        record.clear();
        this.doQuery();
      }

      this.setValue(undefined);
      this.setSelectField(undefined);
      this.element.text = undefined;
      this.isDoClear = false;
    }
  }, {
    key: "renderWrapper",
    value: function renderWrapper() {
      var hiddenIfNone = this.props.hiddenIfNone;

      if (this.isEmpty() && hiddenIfNone) {
        return null;
      }

      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(FilterSelect.prototype), "renderWrapper", this).call(this);
    }
  }, {
    key: "renderMultipleEditor",
    value: function renderMultipleEditor(props) {
      var selectField = this.selectField,
          prefixCls = this.prefixCls;
      var editorProps = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, (0, _omit["default"])(props, ['multiple', 'prefixCls'])), {}, {
        clearButton: false,
        prefix: null,
        suffix: null,
        elementClassName: "".concat(prefixCls, "-inner-editor"),
        onChange: this.handleFieldChange
      });
      editorProps.style = {
        width: 'auto'
      };
      return /*#__PURE__*/_react["default"].createElement("li", {
        key: "text"
      }, selectField ? /*#__PURE__*/_react["default"].createElement("span", {
        className: "".concat(prefixCls, "-select-field")
      }, this.getFieldLabel(selectField, this.getQueryRecord()), ":") : null, selectField ? this.getFieldEditor(editorProps, selectField) : this.getFieldSelect(editorProps));
    }
  }, {
    key: "handleMouseDown",
    value: function handleMouseDown(e) {
      if (e.target !== this.element) {
        if (!this.isFocused) {
          this.focus();
        }
      }
    }
  }]);
  return FilterSelect;
}(_TextField2.TextField);

FilterSelect.displayName = 'FilterSelect';
FilterSelect.defaultProps = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _TextField2.TextField.defaultProps), {}, {
  multiple: true,
  clearButton: true,
  editable: true,
  dropdownMenuStyle: {
    minWidth: (0, _UnitConvertor.pxToRem)(180)
  }
});
(0, _tslib.__decorate)([_mobx.observable], FilterSelect.prototype, "selectField", void 0);
(0, _tslib.__decorate)([_mobx.observable], FilterSelect.prototype, "filterText", void 0);
(0, _tslib.__decorate)([_mobx.computed], FilterSelect.prototype, "value", null);
(0, _tslib.__decorate)([_autobind["default"]], FilterSelect.prototype, "on", null);
(0, _tslib.__decorate)([_mobx.action], FilterSelect.prototype, "setText", null);
(0, _tslib.__decorate)([_autobind["default"]], FilterSelect.prototype, "getRootDomNode", null);
(0, _tslib.__decorate)([_autobind["default"]], FilterSelect.prototype, "defaultRenderer", null);
(0, _tslib.__decorate)([_autobind["default"]], FilterSelect.prototype, "handleDataSetReset", null);
(0, _tslib.__decorate)([_autobind["default"], _mobx.action], FilterSelect.prototype, "handleDataSetUpdate", null);
(0, _tslib.__decorate)([_autobind["default"]], FilterSelect.prototype, "handleBlur", null);
(0, _tslib.__decorate)([_autobind["default"]], FilterSelect.prototype, "handleFieldChange", null);
(0, _tslib.__decorate)([_autobind["default"]], FilterSelect.prototype, "handleInput", null);
(0, _tslib.__decorate)([_autobind["default"]], FilterSelect.prototype, "handleFieldEnterDown", null);
(0, _tslib.__decorate)([_autobind["default"]], FilterSelect.prototype, "handleKeyDown", null);
(0, _tslib.__decorate)([_autobind["default"]], FilterSelect.prototype, "handleEnterDown", null);
(0, _tslib.__decorate)([_mobx.action], FilterSelect.prototype, "setSelectField", null);
(0, _tslib.__decorate)([_mobx.action], FilterSelect.prototype, "setQueryValue", null);
(0, _tslib.__decorate)([_mobx.action], FilterSelect.prototype, "clear", null);
(0, _tslib.__decorate)([_autobind["default"]], FilterSelect.prototype, "handleMouseDown", null);
FilterSelect = (0, _tslib.__decorate)([_mobxReact.observer], FilterSelect);
var _default = FilterSelect;
exports["default"] = _default;
//# sourceMappingURL=FilterSelect.js.map
