"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 _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

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

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

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 = _interopRequireDefault(require("react"));

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

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

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

var _isEqual = _interopRequireDefault(require("lodash/isEqual"));

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

var _defaultTo = _interopRequireDefault(require("lodash/defaultTo"));

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

var _isFunction = _interopRequireDefault(require("lodash/isFunction"));

var _isObject = _interopRequireDefault(require("lodash/isObject"));

var _mobx = require("mobx");

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

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

var _enum = require("../../../lib/_util/enum");

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

var _LovView = _interopRequireDefault(require("./LovView"));

var _Modal = _interopRequireDefault(require("../modal/Modal"));

var _DataSet = _interopRequireDefault(require("../data-set/DataSet"));

var _Record = _interopRequireDefault(require("../data-set/Record"));

var _spin = _interopRequireDefault(require("../spin"));

var _LovCodeStore = _interopRequireDefault(require("../stores/LovCodeStore"));

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

var _EventManager = require("../_util/EventManager");

var _Select2 = _interopRequireWildcard(require("../select/Select"));

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

var _enum2 = require("../table/enum");

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

var _enum4 = require("./enum");

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

var _enum5 = require("../button/enum");

var _localeContext = require("../locale-context");

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

var _isIE = _interopRequireDefault(require("../_util/isIE"));

var _TriggerField = require("../trigger-field/TriggerField");

var _mergeProps = _interopRequireDefault(require("../_util/mergeProps"));

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

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

  function Lov() {
    (0, _classCallCheck2["default"])(this, Lov);
    return _super.apply(this, arguments);
  }

  (0, _createClass2["default"])(Lov, [{
    key: "searchMatcher",
    get: function get() {
      var searchMatcher = this.observableProps.searchMatcher;

      if ((0, _isString["default"])(searchMatcher)) {
        return searchMatcher;
      }

      var viewMode = this.observableProps.viewMode;
      var textField = this.textField;

      if (viewMode === _TriggerField.TriggerViewMode.popup) {
        var queryDataSet = this.options.queryDataSet;

        if (queryDataSet) {
          var queryFields = Array.from(queryDataSet.fields.keys());

          if (queryFields.length && !queryFields.includes(textField)) {
            return queryFields[0];
          }
        }
      }

      return textField;
    }
  }, {
    key: "searchable",
    get: function get() {
      var searchable = this.observableProps.searchable;

      if (searchable === false) {
        return searchable;
      }

      var config = this.getConfig();

      if (config) {
        return config.editableFlag === 'Y';
      }

      return true;
    }
  }, {
    key: "lovCode",
    get: function get() {
      var field = this.field;

      if (field) {
        return field.get('lovCode', this.record);
      }

      return undefined;
    }
  }, {
    key: "popup",
    get: function get() {
      var popupSearchMode = this.props.popupSearchMode;
      var viewMode = this.observableProps.viewMode;

      if (viewMode === _TriggerField.TriggerViewMode.popup && popupSearchMode === _enum4.PopupSearchMode.single) {
        return this.modal || this.isSearchFieldInPopup() && !this.searchText ? false : this.statePopup;
      }

      return this.modal || !this.isSearchFieldInPopup() && !this.searchText ? false : this.statePopup;
    }
    /**
     * 点击查询仅存在一条数据时自动选中, Button 模式禁用
     */

  }, {
    key: "autoSelectSingle",
    get: function get() {
      var viewMode = this.observableProps.viewMode;
      var mode = this.props.mode;

      if (viewMode === _TriggerField.TriggerViewMode.popup || mode === _enum4.ViewMode.button) {
        return false;
      }

      if ('autoSelectSingle' in this.props) {
        return this.props.autoSelectSingle;
      }

      var autoSelectSingle = this.getContextConfig('lovAutoSelectSingle');

      if (typeof autoSelectSingle !== 'undefined') {
        return autoSelectSingle;
      }

      return false;
    }
  }, {
    key: "options",
    get: function get() {
      var field = this.field,
          lovCode = this.lovCode,
          record = this.record;

      if (field) {
        var options = field.getOptions(record);

        if (options) {
          return options;
        }
      }

      if (lovCode) {
        var lovDataSet = _LovCodeStore["default"].getLovDataSet(lovCode, field, field && field.get('optionsProps', record), record);

        if (lovDataSet) {
          return lovDataSet;
        }
      }

      return new _DataSet["default"](undefined, {
        getConfig: this.getContextConfig
      });
    }
  }, {
    key: "showSelectedInView",
    get: function get() {
      if ('showSelectedInView' in this.props) {
        return this.props.showSelectedInView;
      }

      var lovShowSelectedInView = this.getContextConfig('lovShowSelectedInView');

      if ((0, _isFunction["default"])(lovShowSelectedInView)) {
        return lovShowSelectedInView(this.props.viewMode);
      }

      return lovShowSelectedInView;
    }
  }, {
    key: "getSearchFieldProps",
    value: function getSearchFieldProps() {
      var searchFieldProps = (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "getSearchFieldProps", this).call(this);
      var viewMode = this.observableProps.viewMode;

      if (viewMode === _TriggerField.TriggerViewMode.popup) {
        return (0, _objectSpread2["default"])({
          multiple: true
        }, searchFieldProps);
      }

      return searchFieldProps;
    }
  }, {
    key: "isSearchFieldInPopup",
    value: function isSearchFieldInPopup() {
      var searchFieldInPopup = (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "isSearchFieldInPopup", this).call(this);

      if (searchFieldInPopup === undefined) {
        var viewMode = this.observableProps.viewMode;

        if (viewMode === _TriggerField.TriggerViewMode.popup) {
          var popupSearchMode = this.props.popupSearchMode;
          return popupSearchMode !== _enum4.PopupSearchMode.single;
        }
      }

      return searchFieldInPopup;
    }
  }, {
    key: "popupEditable",
    value: function popupEditable() {
      return !(0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "disabled", this) && !(0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "readOnly", this) && this.searchable;
    }
  }, {
    key: "isEditable",
    value: function isEditable() {
      var viewMode = this.observableProps.viewMode;
      var popupSearchMode = this.props.popupSearchMode;

      if (viewMode === _TriggerField.TriggerViewMode.popup) {
        return popupSearchMode === _enum4.PopupSearchMode.single && this.popupEditable();
      }

      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "isEditable", this).call(this);
    }
  }, {
    key: "handleSearchMatcherChange",
    value: function handleSearchMatcherChange(searchMatcher) {
      this.observableProps.searchMatcher = searchMatcher;
      this.searchText = undefined;
      var _this$props$onSearchM = this.props.onSearchMatcherChange,
          onSearchMatcherChange = _this$props$onSearchM === void 0 ? _noop["default"] : _this$props$onSearchM;
      onSearchMatcherChange(searchMatcher);
    }
  }, {
    key: "renderSearchFieldPrefix",
    value: function renderSearchFieldPrefix(props) {
      if (props) {
        var queryDataSet = props.queryDataSet;

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

          if (fields.size > 0) {
            var options = [];
            var searchMatcher = this.searchMatcher;
            fields.forEach(function (field, name) {
              options.push( /*#__PURE__*/_react["default"].createElement(_Option["default"], {
                key: String(name),
                value: name
              }, field.get('label')));
            });
            var prefixCls = this.prefixCls;
            return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_Select2["default"], {
              value: searchMatcher,
              onChange: this.handleSearchMatcherChange,
              border: false,
              clearButton: false,
              className: "".concat(prefixCls, "-lov-search-option"),
              getPopupContainer: this.getPopupWrapper,
              isFlat: true
            }, options), /*#__PURE__*/_react["default"].createElement("div", {
              className: "".concat(prefixCls, "-lov-search-option-divide")
            }));
          }
        }
      }
    }
  }, {
    key: "getPopupLovView",
    value: function getPopupLovView() {
      var _this = this;

      var config = this.getConfig();
      this.autoCreate();
      var options = this.options;

      if (config && options) {
        var lovViewProps;
        if (!this.popup) delete this.fetched;

        if (this.popup && !this.fetched) {
          (0, _mobx.runInAction)(function () {
            lovViewProps = _this.beforeOpen(options);

            _this.afterOpen(options);

            _this.fetched = true;
          });
        }

        var tableProps = this.getTableProps(lovViewProps && lovViewProps.tableProps);
        var popupSearchMode = this.props.popupSearchMode;
        var mergedTableProps = (0, _mergeProps["default"])(tableProps, {
          style: {
            maxHeight: 250
          },
          pagination: {
            showSizeChanger: false
          },
          queryBar: popupSearchMode === _enum4.PopupSearchMode.single ? _enum2.TableQueryBarType.none : this.renderSearchField,
          border: false,
          size: _enum.Size.small
        });
        var _this$props = this.props,
            onBeforeSelect = _this$props.onBeforeSelect,
            viewMode = _this$props.viewMode;
        return /*#__PURE__*/_react["default"].createElement(_LovView["default"], (0, _extends2["default"])({}, lovViewProps, {
          viewMode: viewMode,
          dataSet: options,
          config: config,
          context: this.context,
          tableProps: mergedTableProps,
          onSelect: this.handleLovViewSelect,
          onBeforeSelect: onBeforeSelect,
          multiple: this.multiple,
          values: this.getValues(),
          popupHidden: !this.popup
        }));
      }
    }
  }, {
    key: "getPopupContent",
    value: function getPopupContent() {
      var searchAction = this.props.searchAction;
      var viewMode = this.observableProps.viewMode;

      if (viewMode === _TriggerField.TriggerViewMode.popup) {
        return this.getPopupLovView();
      }

      if (searchAction === _enum4.SearchAction.input) {
        return (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "getPopupContent", this).call(this);
      }

      return null;
    }
  }, {
    key: "syncOptionsSelectedAfterValueRemove",
    value: function syncOptionsSelectedAfterValueRemove(values) {
      var viewMode = this.props.viewMode;

      if (viewMode === _TriggerField.TriggerViewMode.popup) {
        var options = this.options,
            valueField = this.valueField,
            primitive = this.primitive;

        if (options) {
          var selected = options.selected;
          values.forEach(function (value) {
            var primitiveValue = primitive ? value : value[valueField];
            var oldSelected = selected.find(function (r) {
              return r.get(valueField) === primitiveValue;
            });

            if (oldSelected) {
              options.unSelect(oldSelected);
            }
          });
        }
      }
    }
  }, {
    key: "removeValues",
    value: function removeValues(values, index) {
      (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "removeValues", this).call(this, values, index);
      this.syncOptionsSelectedAfterValueRemove(values);
    }
  }, {
    key: "removeLastValue",
    value: function removeLastValue() {
      var value = (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "removeLastValue", this).call(this);

      if (value) {
        this.syncOptionsSelectedAfterValueRemove([value]);
      }

      return value;
    }
  }, {
    key: "clear",
    value: function clear() {
      (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "clear", this).call(this);
      var viewMode = this.props.viewMode;

      if (viewMode === _TriggerField.TriggerViewMode.popup) {
        var options = this.options;

        if (options) {
          options.unSelectAll();
          options.clearCachedSelected();
        }
      }
    }
  }, {
    key: "beforeOpen",
    value: function beforeOpen(options) {
      var multiple = this.multiple,
          primitive = this.primitive,
          valueField = this.valueField;

      if (multiple) {
        options.selectionStrategy = this.getProp('showCheckedStrategy') || _enum3.CheckedStrategy.SHOW_ALL;
      }

      var _this$props2 = this.props,
          viewMode = _this$props2.viewMode,
          viewRenderer = _this$props2.viewRenderer;
      var selected = options.selected;

      if (viewMode === _TriggerField.TriggerViewMode.modal || viewMode === _TriggerField.TriggerViewMode.drawer) {
        options.unSelectAll(); // TODO：lovEvents deprecated

        var lovEvents = this.props.lovEvents;

        if (lovEvents) {
          Object.keys(lovEvents).forEach(function (event) {
            return options.addEventListener(event, lovEvents[event]);
          });
        }
      }

      if (multiple) {
        var needToFetch = new Map();
        options.setCachedSelected(this.getValues().map(function (value) {
          var primitiveValue = primitive ? value : value[valueField];
          var oldSelected = selected.find(function (r) {
            return r.get(valueField) === primitiveValue;
          });

          if (oldSelected) {
            oldSelected.isSelected = true;
            return oldSelected;
          }

          var newSelected = new _Record["default"](primitive ? (0, _defineProperty2["default"])({}, valueField, value) : (0, _mobx.toJS)(value), options, _enum3.RecordStatus.sync);
          newSelected.isSelected = true;
          newSelected.isCached = true;
          needToFetch.set(primitiveValue, newSelected);
          return newSelected;
        }));
        var lovCode = this.lovCode;

        if (lovCode) {
          var lovQueryCachedSelected = this.getContextConfig('lovQueryCachedSelected');

          if (lovQueryCachedSelected) {
            var fetchCachedSelected = function fetchCachedSelected() {
              if (needToFetch.size) {
                lovQueryCachedSelected(lovCode, needToFetch).then((0, _mobx.action)(function (results) {
                  results.forEach(function (data) {
                    var record = needToFetch.get(data[valueField]);

                    if (record) {
                      record.init(data);
                    }
                  });
                  needToFetch.clear();
                }));
              }
            };

            if (viewMode === _TriggerField.TriggerViewMode.popup) {
              fetchCachedSelected();
            } else if (viewMode === _TriggerField.TriggerViewMode.drawer && viewRenderer !== undefined) {
              return {};
            } else {
              return {
                tableProps: {
                  onShowCachedSelectionChange: function onShowCachedSelectionChange(visible) {
                    if (visible) {
                      fetchCachedSelected();
                    }
                  },
                  pagination: {
                    onChange: function onChange() {
                      fetchCachedSelected();
                    }
                  }
                }
              };
            }
          }
        }
      }
    }
  }, {
    key: "afterOpen",
    value: function afterOpen(options, fetchSingle) {
      var tableProps = this.props.tableProps;
      var modal = this.modal;
      var viewMode = this.observableProps.viewMode; // 模态框模式下， tableProps 支持获取 modal 实例

      if ((0, _isFunction["default"])(tableProps) && [_TriggerField.TriggerViewMode.modal, _TriggerField.TriggerViewMode.drawer].includes(viewMode) && modal) {
        var lovViewProps = this.beforeOpen(options);

        var _tableProps = this.getTableProps(lovViewProps && lovViewProps.tableProps);

        modal.update({
          children: /*#__PURE__*/_react["default"].createElement(_LovView["default"], (0, _extends2["default"])({}, this.initedModalLovViewProps, {
            tableProps: _tableProps
          }))
        });
      }

      if (this.autoSelectSingle) {
        if (this.multiple) options.releaseCachedSelected();
      } else {
        var noCache = (0, _defaultTo["default"])(this.getProp('noCache'), this.getContextConfig('lovNoCache'));

        if (this.resetOptions(noCache) && fetchSingle !== true && !this.multiple) {
          options.query(1, undefined, true);
        } else if (this.multiple) {
          if (this.resetOptions(noCache)) {
            options.query(1, undefined, true);
          }

          options.releaseCachedSelected();
        }
      }
    }
  }, {
    key: "getSelectionProps",
    value: function getSelectionProps() {
      var _this$props3 = this.props,
          nodeRenderer = _this$props3.nodeRenderer,
          selectionProps = _this$props3.selectionProps;
      var lovSelectionProps = this.getContextConfig('lovSelectionProps');
      var props = (0, _objectSpread2["default"])({}, lovSelectionProps);

      if (nodeRenderer) {
        props.nodeRenderer = nodeRenderer;
      }

      return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, props), selectionProps);
    }
  }, {
    key: "openModal",
    value: function openModal(fetchSingle) {
      this.collapse();
      var viewMode = this.observableProps.viewMode;
      var _this$props4 = this.props,
          onBeforeSelect = _this$props4.onBeforeSelect,
          viewRenderer = _this$props4.viewRenderer;
      var drawer = viewMode === _TriggerField.TriggerViewMode.drawer;

      if (viewMode === _TriggerField.TriggerViewMode.modal || drawer) {
        var config = this.getConfig();
        this.autoCreate();
        var options = this.options;

        if (config && options) {
          var modal = this.modal;

          if (modal) {
            modal.open();
          } else {
            var width = config.width,
                title = config.title;
            var lovViewProps = this.beforeOpen(options);
            var modalProps = this.getModalProps();
            var tableProps = this.getTableProps(lovViewProps && lovViewProps.tableProps);
            var valueField = this.getProp('valueField');
            var textField = this.getProp('textField');
            this.initedModalLovViewProps = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, lovViewProps), {}, {
              viewMode: viewMode,
              dataSet: options,
              config: config,
              context: this.context,
              tableProps: tableProps,
              onSelect: this.handleLovViewSelect,
              onBeforeSelect: onBeforeSelect,
              multiple: this.multiple,
              values: this.getValues(),
              valueField: valueField,
              textField: textField,
              viewRenderer: viewRenderer,
              showSelectedInView: this.showSelectedInView,
              getSelectionProps: this.getSelectionProps
            });
            this.modal = _Modal["default"].open((0, _mergeProps["default"])({
              title: title || this.getLabel(),
              children: /*#__PURE__*/_react["default"].createElement(_LovView["default"], (0, _extends2["default"])({}, this.initedModalLovViewProps)),
              onClose: this.handleLovViewClose,
              destroyOnClose: true,
              closable: true,
              autoFocus: false,
              className: this.getModalClassName(),
              bodyStyle: {
                minHeight: (0, _isIE["default"])() ? (0, _UnitConvertor.pxToRem)(Math.min((0, _UnitConvertor.scaleSize)(350), window.innerHeight), true) : 'min(3.5rem, 100vh)'
              },
              drawer: drawer,
              drawerBorder: !drawer,
              style: {
                width: (0, _UnitConvertor.pxToRem)(width)
              },
              afterClose: this.handleLovViewAfterClose
            }, modalProps) || {});
            this.afterOpen(options, fetchSingle);
          }
        }
      }
    }
  }, {
    key: "getModalClassName",
    value: function getModalClassName() {
      var _classNames;

      var viewMode = this.props.viewMode;
      return (0, _classnames["default"])((_classNames = {}, (0, _defineProperty2["default"])(_classNames, "".concat(this.prefixCls, "-lov-selection-wrapper"), viewMode === _TriggerField.TriggerViewMode.modal && this.showSelectedInView), (0, _defineProperty2["default"])(_classNames, "".concat(this.prefixCls, "-lov-custom-drawer"), viewMode === _TriggerField.TriggerViewMode.drawer && this.multiple && this.showSelectedInView), (0, _defineProperty2["default"])(_classNames, "".concat(this.prefixCls, "-lov-modal"), viewMode === _TriggerField.TriggerViewMode.modal), (0, _defineProperty2["default"])(_classNames, "".concat(this.prefixCls, "-lov-modal-drawer"), viewMode === _TriggerField.TriggerViewMode.drawer), (0, _defineProperty2["default"])(_classNames, "".concat(this.prefixCls, "-lov-popup"), viewMode === _TriggerField.TriggerViewMode.popup), _classNames));
    }
  }, {
    key: "setText",
    value: function setText(text) {
      this.searching = true;
      (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "setText", this).call(this, text);
    }
    /**
     * 处理 Lov input 查询参数
     * @param text
     */

  }, {
    key: "searchRemote",
    value: function searchRemote(text) {
      var _this2 = this;

      var options = this.options,
          searchMatcher = this.searchMatcher,
          viewMode = this.observableProps.viewMode;

      if ((0, _isString["default"])(searchMatcher) && (viewMode === _TriggerField.TriggerViewMode.popup || !(0, _Select2.isSearchTextEmpty)(text))) {
        this.resetOptions(true);
        var searchPara = this.getSearchPara(searchMatcher, text);
        Object.keys(searchPara).forEach(function (key) {
          var value = searchPara[key];
          options.setQueryParameter(key, value === '' ? undefined : value);
        });

        if (this.isSearchFieldInPopup() || this.props.searchAction === _enum4.SearchAction.input) {
          options.query(1, undefined, true).then(function () {
            return delete _this2.searching;
          });
        }
      }
    }
  }, {
    key: "handlePopupHiddenChange",
    value: function handlePopupHiddenChange(hidden) {
      (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "handlePopupHiddenChange", this).call(this, hidden);

      if (hidden) {
        delete this.fetched;
      }
    }
  }, {
    key: "handleLovViewClose",
    value: function handleLovViewClose() {
      this.focus();
    }
    /**
     * 关闭弹窗移除时间监听 后续废弃
     */

  }, {
    key: "handleLovViewAfterClose",
    value: function handleLovViewAfterClose() {
      // TODO：lovEvents deprecated
      var options = this.options,
          lovEvents = this.props.lovEvents;

      if (lovEvents) {
        Object.keys(lovEvents).forEach(function (event) {
          return options.removeEventListener(event, lovEvents[event]);
        });
      }

      this.setPopup(false);
      this.modal = undefined;
      this.focus();
    }
  }, {
    key: "handleLovViewSelect",
    value: function handleLovViewSelect(records) {
      var _this3 = this;

      var viewMode = this.observableProps.viewMode;

      if (viewMode === _TriggerField.TriggerViewMode.popup && !this.multiple) {
        this.collapse();
      }

      if ((0, _mobx.isArrayLike)(records)) {
        this.setValue(records.map(function (record) {
          return _this3.processRecordToObject(record);
        }));
      } else {
        this.setValue(records && this.processRecordToObject(records) || this.emptyValue);
      }
    }
  }, {
    key: "processRecordToObject",
    value: function processRecordToObject(record) {
      var config = this.getConfig();

      if (config) {
        var transformSelectedData = config.transformSelectedData;

        if (transformSelectedData) {
          var data = transformSelectedData(record.toData());
          return this.primitive ? this.restrictInput(data[this.valueField]) : data;
        }
      }

      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "processRecordToObject", this).call(this, record);
    }
  }, {
    key: "resetOptions",
    value: function resetOptions() {
      var noCache = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
      var field = this.field,
          record = this.record,
          options = this.options;
      var queryDataSet = options.queryDataSet,
          pageSize = options.props.pageSize;
      var dirty = noCache;

      if (noCache) {
        options.pageSize = pageSize || 10;
      }

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

        if (current && current.dirty) {
          dirty = true;
          current.reset();
        }
      }

      if (field) {
        var lovPara = (0, _utils.getLovPara)(field, record);

        if (!(0, _isEqual["default"])(lovPara, options.queryParameter)) {
          options.queryParameter = lovPara;
          return true;
        }

        options.first();

        if (!options.length) {
          return true;
        }
      }

      return dirty;
    }
  }, {
    key: "handleKeyDown",
    value: function handleKeyDown(e) {
      if (!this.popup && e.keyCode === _KeyCode["default"].DOWN) {
        (0, _EventManager.stopEvent)(e);
        this.handleOpenModal();
      }

      if (e.keyCode === _KeyCode["default"].ENTER && this.props.searchAction === _enum4.SearchAction.blur) {
        (0, _EventManager.stopEvent)(e);
        this.blur();
      }

      if (!(e.keyCode === _KeyCode["default"].ENTER && this.searching)) {
        (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "handleKeyDown", this).call(this, e);
      }
    }
  }, {
    key: "handleBlur",
    value: function handleBlur(e) {
      if (this.modal) {
        e.preventDefault();
      }

      if (this.props.popupSearchMode !== _enum4.PopupSearchMode.single) {
        (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "handleBlur", this).call(this, e);
      }
    }
  }, {
    key: "getWrapperProps",
    value: function getWrapperProps() {
      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "getWrapperProps", this).call(this, {
        onDoubleClick: this.disabled || this.readOnly ? undefined : this.handleOpenModal,
        // Support ued to distinguish between select and lov
        className: this.getWrapperClassNames("".concat(this.prefixCls, "-lov"))
      });
    }
  }, {
    key: "getPopupClassName",
    value: function getPopupClassName(defaultClassName) {
      var viewMode = this.observableProps.viewMode;
      return (0, _classnames["default"])(defaultClassName, (0, _defineProperty2["default"])({}, "".concat(this.prefixCls, "-lov-popup"), viewMode === _TriggerField.TriggerViewMode.popup));
    }
  }, {
    key: "syncValueOnBlur",
    value: function syncValueOnBlur(value) {
      var _this4 = this;

      var textField = this.textField;
      var _this$props5 = this.props,
          mode = _this$props5.mode,
          searchAction = _this$props5.searchAction,
          fetchSingle = _this$props5.fetchSingle;

      if (mode !== _enum4.ViewMode.button) {
        var hasRecord = false;

        if (this.getValue()) {
          hasRecord = this.getValue()[textField] === value;
        }

        if (searchAction === _enum4.SearchAction.blur && value && !hasRecord) {
          var options = this.options;
          options.query(1, undefined, true).then(function () {
            var length = options.length;

            if (length > 1 && !fetchSingle || length === 1) {
              var record = options.get(0);

              if (!_this4.optionIsSelected(record, _this4.getValues())) {
                _this4.choose(record);
              }
            } else if (length && fetchSingle) {
              _this4.openModal(fetchSingle);
            }
          });
        } else if (!this.multiple) {
          (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "syncValueOnBlur", this).call(this, value);
        } else if (this.getProp('required')) {
          var oldValues = this.getValues();
          this.validate(oldValues, false);
        }
      }
    }
  }, {
    key: "getConfig",
    value: function getConfig() {
      var lovCode = this.lovCode;

      if (lovCode) {
        return _LovCodeStore["default"].getConfig(lovCode);
      }
    }
  }, {
    key: "getPlaceholders",
    value: function getPlaceholders() {
      var placeholder = (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "getPlaceholders", this).call(this);

      if (placeholder.length) {
        return placeholder;
      }

      var config = this.getConfig();

      if (config) {
        var holder = config.placeholder;
        var holders = [];
        return holder ? holders.concat(holder) : holders;
      }

      return [];
    }
  }, {
    key: "getModalProps",
    value: function getModalProps() {
      var modalProps = this.props.modalProps;
      return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, this.getContextConfig('lovModalProps')), modalProps);
    }
  }, {
    key: "getTableProps",
    value: function getTableProps(localTableProps) {
      var tableProps = this.props.tableProps;
      var lovTablePropsConfig = this.getContextConfig('lovTableProps');
      var lovTablePropsConfigData = (0, _isFunction["default"])(lovTablePropsConfig) ? lovTablePropsConfig(this.multiple) : lovTablePropsConfig;
      var tablePropsData;

      if ((0, _isObject["default"])(tableProps)) {
        tablePropsData = tableProps;
      }

      if ((0, _isFunction["default"])(tableProps)) {
        var modal = this.modal;
        var viewMode = this.observableProps.viewMode;
        var lovTableProps = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, lovTablePropsConfig), localTableProps);

        if (viewMode === _TriggerField.TriggerViewMode.popup) {
          tablePropsData = tableProps(lovTableProps);
        } else if ([_TriggerField.TriggerViewMode.modal, _TriggerField.TriggerViewMode.drawer].includes(viewMode) && modal) {
          tablePropsData = tableProps(lovTableProps, modal);
        }
      }

      return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, lovTablePropsConfigData), (0, _mergeProps["default"])(localTableProps, tablePropsData));
    }
  }, {
    key: "selectSingle",
    value: function () {
      var _selectSingle = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
        var options, values, record;
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                options = this.options;
                this.resetOptions(options.length === 1);
                _context.next = 4;
                return options.query(1, undefined, true);

              case 4:
                if (options.length === 1) {
                  values = this.getValues();
                  record = options.get(0);

                  if (!this.optionIsSelected(record, values)) {
                    this.choose(record);
                  }
                } else {
                  this.openModal();
                }

              case 5:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function selectSingle() {
        return _selectSingle.apply(this, arguments);
      }

      return selectSingle;
    }()
  }, {
    key: "handleOpenModal",
    value: function handleOpenModal() {
      if (!this.disabled && !this.readOnly) {
        return this.autoSelectSingle ? this.selectSingle() : this.openModal();
      }
    }
  }, {
    key: "getOmitPropsKeys",
    value: function getOmitPropsKeys() {
      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "getOmitPropsKeys", this).call(this).concat(['modalProps', 'noCache', 'tableProps', 'lovEvents', 'searchAction', 'fetchSingle', 'autoSelectSingle', 'showCheckedStrategy', 'onBeforeSelect', 'onSearchMatcherChange', 'viewRenderer', 'nodeRenderer', 'showSelectedInView', 'selectionProps', 'popupSearchMode']);
    }
  }, {
    key: "getButtonProps",
    value: function getButtonProps() {
      var _this$props6 = this.props,
          className = _this$props6.className,
          type = _this$props6.type;
      var options = this.options;
      var props = (0, _objectSpread2["default"])((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _Button["default"].defaultProps), (0, _omit["default"])(this.getOtherProps(), ['name'])), {}, {
        dataSet: options,
        className: (0, _classnames["default"])(className, "".concat(this.prefixCls, "-lov")),
        type: type
      });

      if (!this.valid) {
        props.color = _enum5.ButtonColor.red;
      }

      return props;
    }
  }, {
    key: "loading",
    get: function get() {
      var options = this.options;
      return options.status === _enum3.DataSetStatus.loading;
    }
  }, {
    key: "saveSuffixRef",
    value: function saveSuffixRef(node) {
      this.suffixRef = node;
    }
  }, {
    key: "getSuffix",
    value: function getSuffix() {
      var viewMode = this.observableProps.viewMode;
      var suffix = this.props.suffix;

      if (viewMode === _TriggerField.TriggerViewMode.popup) {
        return (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "getSuffix", this).call(this);
      }

      var icon = this.loading && !this.modal ? /*#__PURE__*/_react["default"].createElement(_spin["default"], {
        className: "".concat(this.prefixCls, "-lov-spin")
      }) : /*#__PURE__*/_react["default"].createElement(_icon["default"], {
        type: "search"
      });
      return this.wrapperSuffix(suffix || icon, {
        onClick: this.disabled || this.readOnly || this.loading ? undefined : this.handleOpenModal
      });
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "componentWillUnmount", this).call(this);

      if (this.modal) {
        this.modal.close();
      }
    }
  }, {
    key: "select",
    value: function select() {
      var mode = this.props.mode;

      if (mode !== _enum4.ViewMode.button) {
        (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "select", this).call(this);
      }
    }
  }, {
    key: "handleButtonClick",
    value: function handleButtonClick(e) {
      var _this$props$onClick = this.props.onClick,
          onClick = _this$props$onClick === void 0 ? _noop["default"] : _this$props$onClick;
      onClick(e);

      if (!e.isDefaultPrevented()) {
        return this.handleOpenModal();
      }
    }
  }, {
    key: "getTextByValue",
    value: function getTextByValue(value) {
      var mode = this.props.mode;
      return mode === _enum4.ViewMode.button ? this.processRenderer(value) : (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "getTextByValue", this).call(this, value);
    }
  }, {
    key: "renderWrapper",
    value: function renderWrapper() {
      var _this$props7 = this.props,
          mode = _this$props7.mode,
          children = _this$props7.children,
          clearButton = _this$props7.clearButton;

      if (mode === _enum4.ViewMode.button) {
        var elements = [/*#__PURE__*/_react["default"].createElement(_Button["default"], (0, _extends2["default"])({
          key: "lov_button"
        }, this.getButtonProps(), {
          disabled: this.disabled,
          onClick: this.handleButtonClick
        }), children || this.getTextNode() || this.getPlaceholders()[0] || (0, _localeContext.$l)('Lov', 'choose'))];

        if (clearButton) {
          elements.push( /*#__PURE__*/_react["default"].createElement(_Button["default"], {
            key: "lov_clear_button",
            size: _enum.Size.small,
            funcType: _enum5.FuncType.flat,
            icon: "close",
            onClick: this.handleClearButtonClick
          }));
        }

        return elements;
      }

      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(Lov.prototype), "renderWrapper", this).call(this);
    }
  }]);
  return Lov;
}(_Select2.Select);

Lov.displayName = 'Lov';
Lov.defaultProps = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _Select2.Select.defaultProps), {}, {
  clearButton: true,
  checkValueOnOptionsChange: false,
  dropdownMatchSelectWidth: false,
  searchAction: _enum4.SearchAction.input,
  fetchSingle: false,
  viewMode: _TriggerField.TriggerViewMode.modal,
  popupSearchMode: _enum4.PopupSearchMode.multiple
});
(0, _tslib.__decorate)([_mobx.observable], Lov.prototype, "modal", void 0);
(0, _tslib.__decorate)([_mobx.computed], Lov.prototype, "searchMatcher", null);
(0, _tslib.__decorate)([_mobx.computed], Lov.prototype, "searchable", null);
(0, _tslib.__decorate)([_mobx.computed], Lov.prototype, "lovCode", null);
(0, _tslib.__decorate)([_mobx.computed], Lov.prototype, "options", null);
(0, _tslib.__decorate)([_autobind["default"], _mobx.action], Lov.prototype, "handleSearchMatcherChange", null);
(0, _tslib.__decorate)([_autobind["default"]], Lov.prototype, "renderSearchFieldPrefix", null);
(0, _tslib.__decorate)([_autobind["default"]], Lov.prototype, "getPopupContent", null);
(0, _tslib.__decorate)([_mobx.action], Lov.prototype, "removeValues", null);
(0, _tslib.__decorate)([_mobx.action], Lov.prototype, "beforeOpen", null);
(0, _tslib.__decorate)([_mobx.action], Lov.prototype, "afterOpen", null);
(0, _tslib.__decorate)([_autobind["default"]], Lov.prototype, "getSelectionProps", null);
(0, _tslib.__decorate)([_mobx.action], Lov.prototype, "openModal", null);
(0, _tslib.__decorate)([_mobx.action], Lov.prototype, "setText", null);
(0, _tslib.__decorate)([_mobx.action], Lov.prototype, "searchRemote", null);
(0, _tslib.__decorate)([_autobind["default"]], Lov.prototype, "handlePopupHiddenChange", null);
(0, _tslib.__decorate)([_autobind["default"]], Lov.prototype, "handleLovViewClose", null);
(0, _tslib.__decorate)([_autobind["default"], _mobx.action], Lov.prototype, "handleLovViewAfterClose", null);
(0, _tslib.__decorate)([_autobind["default"]], Lov.prototype, "handleLovViewSelect", null);
(0, _tslib.__decorate)([_autobind["default"]], Lov.prototype, "handleKeyDown", null);
(0, _tslib.__decorate)([_autobind["default"]], Lov.prototype, "handleBlur", null);
(0, _tslib.__decorate)([_autobind["default"], _mobx.action], Lov.prototype, "selectSingle", null);
(0, _tslib.__decorate)([_autobind["default"]], Lov.prototype, "handleOpenModal", null);
(0, _tslib.__decorate)([_mobx.computed], Lov.prototype, "loading", null);
(0, _tslib.__decorate)([_autobind["default"], _mobx.action], Lov.prototype, "saveSuffixRef", null);
(0, _tslib.__decorate)([_autobind["default"]], Lov.prototype, "handleButtonClick", null);
Lov = (0, _tslib.__decorate)([_mobxReact.observer], Lov);
var _default = Lov;
exports["default"] = _default;
//# sourceMappingURL=Lov.js.map
