import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _extends from "@babel/runtime/helpers/extends";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _get from "@babel/runtime/helpers/get";
import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/inherits";
import _createSuper from "@babel/runtime/helpers/createSuper";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { __decorate } from "tslib";
import React from 'react';
import { observer } from 'mobx-react';
import classNames from 'classnames';
import omit from 'lodash/omit';
import isEqual from 'lodash/isEqual';
import isString from 'lodash/isString';
import defaultTo from 'lodash/defaultTo';
import noop from 'lodash/noop';
import isFunction from 'lodash/isFunction';
import isObject from 'lodash/isObject';
import { action, computed, isArrayLike, observable, runInAction, toJS } from 'mobx';
import { pxToRem, scaleSize } from '../../../es/_util/UnitConvertor';
import KeyCode from '../../../es/_util/KeyCode';
import { Size } from '../../../es/_util/enum';
import Icon from '../icon';
import LovView from './LovView';
import Modal from '../modal/Modal';
import DataSet from '../data-set/DataSet';
import Record from '../data-set/Record';
import Spin from '../spin';
import lovStore from '../stores/LovCodeStore';
import autobind from '../_util/autobind';
import { stopEvent } from '../_util/EventManager';
import ObserverSelect, { isSearchTextEmpty, Select } from '../select/Select';
import Option from '../option/Option';
import { TableQueryBarType } from '../table/enum';
import { CheckedStrategy, DataSetStatus, RecordStatus } from '../data-set/enum';
import { PopupSearchMode, SearchAction, ViewMode } from './enum';
import Button from '../button/Button';
import { ButtonColor, FuncType } from '../button/enum';
import { $l } from '../locale-context';
import { getLovPara } from '../stores/utils';
import isIE from '../_util/isIE';
import { TriggerViewMode } from '../trigger-field/TriggerField';
import mergeProps from '../_util/mergeProps';

var Lov = /*#__PURE__*/function (_Select) {
  _inherits(Lov, _Select);

  var _super = _createSuper(Lov);

  function Lov() {
    _classCallCheck(this, Lov);

    return _super.apply(this, arguments);
  }

  _createClass(Lov, [{
    key: "searchMatcher",
    get: function get() {
      var searchMatcher = this.observableProps.searchMatcher;

      if (isString(searchMatcher)) {
        return searchMatcher;
      }

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

      if (viewMode === 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 === TriggerViewMode.popup && popupSearchMode === 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 === TriggerViewMode.popup || mode === 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 = lovStore.getLovDataSet(lovCode, field, field && field.get('optionsProps', record), record);

        if (lovDataSet) {
          return lovDataSet;
        }
      }

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

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

      if (isFunction(lovShowSelectedInView)) {
        return lovShowSelectedInView(this.props.viewMode);
      }

      return lovShowSelectedInView;
    }
  }, {
    key: "getSearchFieldProps",
    value: function getSearchFieldProps() {
      var searchFieldProps = _get(_getPrototypeOf(Lov.prototype), "getSearchFieldProps", this).call(this);

      var viewMode = this.observableProps.viewMode;

      if (viewMode === TriggerViewMode.popup) {
        return _objectSpread({
          multiple: true
        }, searchFieldProps);
      }

      return searchFieldProps;
    }
  }, {
    key: "isSearchFieldInPopup",
    value: function isSearchFieldInPopup() {
      var searchFieldInPopup = _get(_getPrototypeOf(Lov.prototype), "isSearchFieldInPopup", this).call(this);

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

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

      return searchFieldInPopup;
    }
  }, {
    key: "popupEditable",
    value: function popupEditable() {
      return !_get(_getPrototypeOf(Lov.prototype), "disabled", this) && !_get(_getPrototypeOf(Lov.prototype), "readOnly", this) && this.searchable;
    }
  }, {
    key: "isEditable",
    value: function isEditable() {
      var viewMode = this.observableProps.viewMode;
      var popupSearchMode = this.props.popupSearchMode;

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

      return _get(_getPrototypeOf(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 : _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.createElement(Option, {
                key: String(name),
                value: name
              }, field.get('label')));
            });
            var prefixCls = this.prefixCls;
            return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(ObserverSelect, {
              value: searchMatcher,
              onChange: this.handleSearchMatcherChange,
              border: false,
              clearButton: false,
              className: "".concat(prefixCls, "-lov-search-option"),
              getPopupContainer: this.getPopupWrapper,
              isFlat: true
            }, options), /*#__PURE__*/React.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) {
          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 = mergeProps(tableProps, {
          style: {
            maxHeight: 250
          },
          pagination: {
            showSizeChanger: false
          },
          queryBar: popupSearchMode === PopupSearchMode.single ? TableQueryBarType.none : this.renderSearchField,
          border: false,
          size: Size.small
        });
        var _this$props = this.props,
            onBeforeSelect = _this$props.onBeforeSelect,
            viewMode = _this$props.viewMode;
        return /*#__PURE__*/React.createElement(LovView, _extends({}, 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 === TriggerViewMode.popup) {
        return this.getPopupLovView();
      }

      if (searchAction === SearchAction.input) {
        return _get(_getPrototypeOf(Lov.prototype), "getPopupContent", this).call(this);
      }

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

      if (viewMode === 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) {
      _get(_getPrototypeOf(Lov.prototype), "removeValues", this).call(this, values, index);

      this.syncOptionsSelectedAfterValueRemove(values);
    }
  }, {
    key: "removeLastValue",
    value: function removeLastValue() {
      var value = _get(_getPrototypeOf(Lov.prototype), "removeLastValue", this).call(this);

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

      return value;
    }
  }, {
    key: "clear",
    value: function clear() {
      _get(_getPrototypeOf(Lov.prototype), "clear", this).call(this);

      var viewMode = this.props.viewMode;

      if (viewMode === 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') || CheckedStrategy.SHOW_ALL;
      }

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

      if (viewMode === TriggerViewMode.modal || viewMode === 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(primitive ? _defineProperty({}, valueField, value) : toJS(value), options, 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(action(function (results) {
                  results.forEach(function (data) {
                    var record = needToFetch.get(data[valueField]);

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

            if (viewMode === TriggerViewMode.popup) {
              fetchCachedSelected();
            } else if (viewMode === 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 (isFunction(tableProps) && [TriggerViewMode.modal, TriggerViewMode.drawer].includes(viewMode) && modal) {
        var lovViewProps = this.beforeOpen(options);

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

        modal.update({
          children: /*#__PURE__*/React.createElement(LovView, _extends({}, this.initedModalLovViewProps, {
            tableProps: _tableProps
          }))
        });
      }

      if (this.autoSelectSingle) {
        if (this.multiple) options.releaseCachedSelected();
      } else {
        var noCache = defaultTo(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 = _objectSpread({}, lovSelectionProps);

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

      return _objectSpread(_objectSpread({}, 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 === TriggerViewMode.drawer;

      if (viewMode === 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 = _objectSpread(_objectSpread({}, 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.open(mergeProps({
              title: title || this.getLabel(),
              children: /*#__PURE__*/React.createElement(LovView, _extends({}, this.initedModalLovViewProps)),
              onClose: this.handleLovViewClose,
              destroyOnClose: true,
              closable: true,
              autoFocus: false,
              className: this.getModalClassName(),
              bodyStyle: {
                minHeight: isIE() ? pxToRem(Math.min(scaleSize(350), window.innerHeight), true) : 'min(3.5rem, 100vh)'
              },
              drawer: drawer,
              drawerBorder: !drawer,
              style: {
                width: pxToRem(width)
              },
              afterClose: this.handleLovViewAfterClose
            }, modalProps) || {});
            this.afterOpen(options, fetchSingle);
          }
        }
      }
    }
  }, {
    key: "getModalClassName",
    value: function getModalClassName() {
      var _classNames;

      var viewMode = this.props.viewMode;
      return classNames((_classNames = {}, _defineProperty(_classNames, "".concat(this.prefixCls, "-lov-selection-wrapper"), viewMode === TriggerViewMode.modal && this.showSelectedInView), _defineProperty(_classNames, "".concat(this.prefixCls, "-lov-custom-drawer"), viewMode === TriggerViewMode.drawer && this.multiple && this.showSelectedInView), _defineProperty(_classNames, "".concat(this.prefixCls, "-lov-modal"), viewMode === TriggerViewMode.modal), _defineProperty(_classNames, "".concat(this.prefixCls, "-lov-modal-drawer"), viewMode === TriggerViewMode.drawer), _defineProperty(_classNames, "".concat(this.prefixCls, "-lov-popup"), viewMode === TriggerViewMode.popup), _classNames));
    }
  }, {
    key: "setText",
    value: function setText(text) {
      this.searching = true;

      _get(_getPrototypeOf(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 (isString(searchMatcher) && (viewMode === TriggerViewMode.popup || !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 === SearchAction.input) {
          options.query(1, undefined, true).then(function () {
            return delete _this2.searching;
          });
        }
      }
    }
  }, {
    key: "handlePopupHiddenChange",
    value: function handlePopupHiddenChange(hidden) {
      _get(_getPrototypeOf(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 === TriggerViewMode.popup && !this.multiple) {
        this.collapse();
      }

      if (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 _get(_getPrototypeOf(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 = getLovPara(field, record);

        if (!isEqual(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.DOWN) {
        stopEvent(e);
        this.handleOpenModal();
      }

      if (e.keyCode === KeyCode.ENTER && this.props.searchAction === SearchAction.blur) {
        stopEvent(e);
        this.blur();
      }

      if (!(e.keyCode === KeyCode.ENTER && this.searching)) {
        _get(_getPrototypeOf(Lov.prototype), "handleKeyDown", this).call(this, e);
      }
    }
  }, {
    key: "handleBlur",
    value: function handleBlur(e) {
      if (this.modal) {
        e.preventDefault();
      }

      if (this.props.popupSearchMode !== PopupSearchMode.single) {
        _get(_getPrototypeOf(Lov.prototype), "handleBlur", this).call(this, e);
      }
    }
  }, {
    key: "getWrapperProps",
    value: function getWrapperProps() {
      return _get(_getPrototypeOf(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 classNames(defaultClassName, _defineProperty({}, "".concat(this.prefixCls, "-lov-popup"), viewMode === 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 !== ViewMode.button) {
        var hasRecord = false;

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

        if (searchAction === 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) {
          _get(_getPrototypeOf(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 lovStore.getConfig(lovCode);
      }
    }
  }, {
    key: "getPlaceholders",
    value: function getPlaceholders() {
      var placeholder = _get(_getPrototypeOf(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 _objectSpread(_objectSpread({}, this.getContextConfig('lovModalProps')), modalProps);
    }
  }, {
    key: "getTableProps",
    value: function getTableProps(localTableProps) {
      var tableProps = this.props.tableProps;
      var lovTablePropsConfig = this.getContextConfig('lovTableProps');
      var lovTablePropsConfigData = isFunction(lovTablePropsConfig) ? lovTablePropsConfig(this.multiple) : lovTablePropsConfig;
      var tablePropsData;

      if (isObject(tableProps)) {
        tablePropsData = tableProps;
      }

      if (isFunction(tableProps)) {
        var modal = this.modal;
        var viewMode = this.observableProps.viewMode;

        var lovTableProps = _objectSpread(_objectSpread({}, lovTablePropsConfig), localTableProps);

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

      return _objectSpread(_objectSpread({}, lovTablePropsConfigData), mergeProps(localTableProps, tablePropsData));
    }
  }, {
    key: "selectSingle",
    value: function () {
      var _selectSingle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var options, values, record;
        return _regeneratorRuntime.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 _get(_getPrototypeOf(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 = _objectSpread(_objectSpread(_objectSpread({}, Button.defaultProps), omit(this.getOtherProps(), ['name'])), {}, {
        dataSet: options,
        className: classNames(className, "".concat(this.prefixCls, "-lov")),
        type: type
      });

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

      return props;
    }
  }, {
    key: "loading",
    get: function get() {
      var options = this.options;
      return options.status === 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 === TriggerViewMode.popup) {
        return _get(_getPrototypeOf(Lov.prototype), "getSuffix", this).call(this);
      }

      var icon = this.loading && !this.modal ? /*#__PURE__*/React.createElement(Spin, {
        className: "".concat(this.prefixCls, "-lov-spin")
      }) : /*#__PURE__*/React.createElement(Icon, {
        type: "search"
      });
      return this.wrapperSuffix(suffix || icon, {
        onClick: this.disabled || this.readOnly || this.loading ? undefined : this.handleOpenModal
      });
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      _get(_getPrototypeOf(Lov.prototype), "componentWillUnmount", this).call(this);

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

      if (mode !== ViewMode.button) {
        _get(_getPrototypeOf(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 : _this$props$onClick;
      onClick(e);

      if (!e.isDefaultPrevented()) {
        return this.handleOpenModal();
      }
    }
  }, {
    key: "getTextByValue",
    value: function getTextByValue(value) {
      var mode = this.props.mode;
      return mode === ViewMode.button ? this.processRenderer(value) : _get(_getPrototypeOf(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 === ViewMode.button) {
        var elements = [/*#__PURE__*/React.createElement(Button, _extends({
          key: "lov_button"
        }, this.getButtonProps(), {
          disabled: this.disabled,
          onClick: this.handleButtonClick
        }), children || this.getTextNode() || this.getPlaceholders()[0] || $l('Lov', 'choose'))];

        if (clearButton) {
          elements.push( /*#__PURE__*/React.createElement(Button, {
            key: "lov_clear_button",
            size: Size.small,
            funcType: FuncType.flat,
            icon: "close",
            onClick: this.handleClearButtonClick
          }));
        }

        return elements;
      }

      return _get(_getPrototypeOf(Lov.prototype), "renderWrapper", this).call(this);
    }
  }]);

  return Lov;
}(Select);

Lov.displayName = 'Lov';
Lov.defaultProps = _objectSpread(_objectSpread({}, Select.defaultProps), {}, {
  clearButton: true,
  checkValueOnOptionsChange: false,
  dropdownMatchSelectWidth: false,
  searchAction: SearchAction.input,
  fetchSingle: false,
  viewMode: TriggerViewMode.modal,
  popupSearchMode: PopupSearchMode.multiple
});

__decorate([observable], Lov.prototype, "modal", void 0);

__decorate([computed], Lov.prototype, "searchMatcher", null);

__decorate([computed], Lov.prototype, "searchable", null);

__decorate([computed], Lov.prototype, "lovCode", null);

__decorate([computed], Lov.prototype, "options", null);

__decorate([autobind, action], Lov.prototype, "handleSearchMatcherChange", null);

__decorate([autobind], Lov.prototype, "renderSearchFieldPrefix", null);

__decorate([autobind], Lov.prototype, "getPopupContent", null);

__decorate([action], Lov.prototype, "removeValues", null);

__decorate([action], Lov.prototype, "beforeOpen", null);

__decorate([action], Lov.prototype, "afterOpen", null);

__decorate([autobind], Lov.prototype, "getSelectionProps", null);

__decorate([action], Lov.prototype, "openModal", null);

__decorate([action], Lov.prototype, "setText", null);

__decorate([action], Lov.prototype, "searchRemote", null);

__decorate([autobind], Lov.prototype, "handlePopupHiddenChange", null);

__decorate([autobind], Lov.prototype, "handleLovViewClose", null);

__decorate([autobind, action], Lov.prototype, "handleLovViewAfterClose", null);

__decorate([autobind], Lov.prototype, "handleLovViewSelect", null);

__decorate([autobind], Lov.prototype, "handleKeyDown", null);

__decorate([autobind], Lov.prototype, "handleBlur", null);

__decorate([autobind, action], Lov.prototype, "selectSingle", null);

__decorate([autobind], Lov.prototype, "handleOpenModal", null);

__decorate([computed], Lov.prototype, "loading", null);

__decorate([autobind, action], Lov.prototype, "saveSuffixRef", null);

__decorate([autobind], Lov.prototype, "handleButtonClick", null);

Lov = __decorate([observer], Lov);
export default Lov;
//# sourceMappingURL=Lov.js.map
