"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"] = exports.MemoModalContent = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _createForOfIteratorHelper2 = _interopRequireDefault(require("@babel/runtime/helpers/createForOfIteratorHelper"));

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

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

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

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

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

var _mobx = require("mobx");

var _mobxReactLite = require("mobx-react-lite");

var _map = _interopRequireDefault(require("lodash/map"));

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

var _isEmpty = _interopRequireDefault(require("lodash/isEmpty"));

var _isArray = _interopRequireDefault(require("lodash/isArray"));

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

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

var _ConfigContext = _interopRequireDefault(require("../../../../../lib/config-provider/ConfigContext"));

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

var _tag = _interopRequireDefault(require("../../../../../lib/tag"));

var _isEmpty2 = _interopRequireDefault(require("../../../_util/isEmpty"));

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

var _button = _interopRequireDefault(require("../../../button"));

var _select = _interopRequireDefault(require("../../../select"));

var _modal = _interopRequireDefault(require("../../../modal"));

var _textField = _interopRequireDefault(require("../../../text-field"));

var _enum = require("../../../text-field/enum");

var _dropdown = _interopRequireDefault(require("../../../dropdown"));

var _menu = _interopRequireDefault(require("../../../menu"));

var _form = _interopRequireDefault(require("../../../form"));

var _switch = _interopRequireDefault(require("../../../switch"));

var _selectBox = _interopRequireDefault(require("../../../select-box"));

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

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

var _singleton = require("../../../tooltip/singleton");

var _util = _interopRequireDefault(require("../../../overflow-tip/util"));

var _TableDynamicFilterBar = require("../TableDynamicFilterBar");

var _QuickFilterMenuContext = _interopRequireDefault(require("./QuickFilterMenuContext"));

var _QuickFilterDataSet = require("./QuickFilterDataSet");

var modalKey = _modal["default"].key();
/**
 * 判断查询值是否为空
 * @param value
 */


function isEmpty(value) {
  return (0, _isArray["default"])(value) ? !value.length : (0, _isEmpty2["default"])(value);
}
/**
 * 根据数据查找需要处理的字段对象
 * @param queryDataSet
 * @param data
 */


function findFieldObj(queryDataSet, data) {
  var name = data[0];
  var value = data[1];

  if (!queryDataSet.fields.has(data[0]) && (0, _isObject["default"])(data[1]) && !(0, _isEmpty["default"])(data[1]) && !(0, _isArray["default"])(data[1])) {
    name = "".concat(data[0], ".").concat(Object.keys(data[1])[0]);
    value = Object.values(data[1])[0];
  }

  var field = queryDataSet.getField(name);

  if (field && field.get('lovCode')) {
    var _value2;

    var textField = field.get('textField');
    var valueField = field.get('valueField');
    var multipleValue = [];

    if (field.get('multiple')) {
      multipleValue = value.map(function (obj) {
        var _ref;

        return _ref = {}, (0, _defineProperty2["default"])(_ref, valueField, obj[valueField]), (0, _defineProperty2["default"])(_ref, textField, obj[textField]), _ref;
      });
      return {
        name: name,
        value: multipleValue
      };
    }

    if ((0, _isObject["default"])(value)) {
      var _value;

      return {
        name: name,
        value: (_value = {}, (0, _defineProperty2["default"])(_value, valueField, value[valueField]), (0, _defineProperty2["default"])(_value, textField, value[textField]), _value)
      };
    }

    return {
      name: name,
      value: (_value2 = {}, (0, _defineProperty2["default"])(_value2, valueField, value), (0, _defineProperty2["default"])(_value2, textField, value), _value2)
    };
  }

  if (field && field.get('ignore') !== 'always') {
    return {
      name: name,
      value: value
    };
  }
}
/**
 * 当前数据是否有值并需要选中
 * @param data
 */


function isSelect(data) {
  if ((0, _isObject["default"])(data[1])) {
    return !(0, _isEmpty["default"])(data[1]);
  }

  return data[0] !== '__dirty' && !isEmpty(data[1]);
}
/**
 * 编辑/新建筛选弹窗
 * @param modal
 * @param menuDataSet
 * @param queryDataSet
 * @param onLoadData
 * @param type
 * @param selectFields
 * @constructor
 */


var ModalContent = function ModalContent(_ref2) {
  var modal = _ref2.modal,
      newFilterDataSet = _ref2.newFilterDataSet,
      menuDataSet = _ref2.menuDataSet,
      record = _ref2.record,
      queryDataSet = _ref2.queryDataSet,
      dataSet = _ref2.dataSet,
      onLoadData = _ref2.onLoadData,
      type = _ref2.type,
      selectFields = _ref2.selectFields;

  var _useContext = (0, _react.useContext)(_ConfigContext["default"]),
      getConfig = _useContext.getConfig;

  modal.handleOk( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
    var putData, statusKey, statusAdd, statusUpdate, shouldSaveValue, status, fuzzySrearchValue, fuzzySrearchData, conditionData, hasValueFields, filterData, otherRecord, res;
    return _regenerator["default"].wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            putData = [];
            statusKey = getConfig('statusKey');
            statusAdd = getConfig('status').add;
            statusUpdate = getConfig('status').update;
            shouldSaveValue = menuDataSet.current.get('saveFilterValue');
            status = {};
            status[statusKey] = statusAdd;
            fuzzySrearchValue = dataSet.getState(_TableDynamicFilterBar.SEARCHTEXT);
            fuzzySrearchData = [(0, _objectSpread2["default"])({
              fieldName: _TableDynamicFilterBar.SEARCHTEXT,
              comparator: 'EQUAL',
              value: fuzzySrearchValue
            }, status)];

            if (type !== 'edit') {
              conditionData = Object.entries((0, _omit["default"])(queryDataSet.current.toData(), ['__dirty']));
              (0, _map["default"])(conditionData, function (data) {
                if (isSelect(data)) {
                  var fieldObj = findFieldObj(queryDataSet, data);

                  if (fieldObj && fieldObj.name) {
                    putData.push((0, _objectSpread2["default"])({
                      comparator: 'EQUAL',
                      fieldName: fieldObj.name,
                      value: shouldSaveValue ? (0, _TableDynamicFilterBar.stringifyValue)(fieldObj.value) : ''
                    }, status));
                  }
                }
              });
              hasValueFields = putData.map(function (pt) {
                return pt.fieldName;
              });
              (0, _map["default"])(selectFields, function (fieldName) {
                var value = queryDataSet.current.get(fieldName); // 加入空值勾选字段

                if (!hasValueFields.includes(fieldName)) {
                  putData.push((0, _objectSpread2["default"])({
                    comparator: 'EQUAL',
                    fieldName: fieldName,
                    value: shouldSaveValue ? (0, _TableDynamicFilterBar.stringifyValue)(value) : ''
                  }, status));
                }
              });
            } // 处理过滤条件


            filterData = [];

            if (newFilterDataSet) {
              filterData = newFilterDataSet.map(function (filterRecord) {
                if (filterRecord.status !== _enum2.RecordStatus.sync) {
                  var _status = {};
                  _status[statusKey] = filterRecord.status === _enum2.RecordStatus.add ? statusAdd : statusUpdate;
                  return (0, _objectSpread2["default"])({
                    fieldName: filterRecord.get(_QuickFilterDataSet.AdvancedFieldSet.fieldName),
                    comparator: filterRecord.get(_QuickFilterDataSet.AdvancedFieldSet.comparator),
                    conditionType: filterRecord.get(_QuickFilterDataSet.AdvancedFieldSet.conditionType),
                    value: filterRecord.get('value')
                  }, _status);
                }

                return null;
              });
            } // 另存为


            if (type === 'save') {
              otherRecord = menuDataSet.current.clone();
              otherRecord.set('conditionList', [].concat(putData, (0, _toConsumableArray2["default"])(filterData)));
              otherRecord.set('queryList', fuzzySrearchData);
              menuDataSet.current.reset();
              menuDataSet.create((0, _objectSpread2["default"])({}, (0, _TableDynamicFilterBar.omitData)(otherRecord.toData()))); // 新建
            } else if (type === 'create') {
              menuDataSet.current.set('conditionList', [].concat(putData, (0, _toConsumableArray2["default"])(filterData)));
              if (fuzzySrearchValue) menuDataSet.current.set('queryList', fuzzySrearchData);
            }

            _context.next = 15;
            return menuDataSet.submit();

          case 15:
            res = _context.sent;

            if (!(res && res.success)) {
              _context.next = 19;
              break;
            }

            onLoadData(res.content ? res.content[0].searchId : undefined);
            return _context.abrupt("return", true);

          case 19:
            return _context.abrupt("return", !(res && res.failed || !res));

          case 20:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  })));
  modal.handleCancel(function () {
    menuDataSet.reset();
  });
  return /*#__PURE__*/_react["default"].createElement(_form["default"], {
    record: record || menuDataSet.current
  }, /*#__PURE__*/_react["default"].createElement(_textField["default"], {
    style: {
      width: '100%'
    },
    name: "searchName",
    placeholder: (0, _localeContext.$l)('Table', 'please_enter'),
    showLengthInfo: true,
    valueChangeAction: _enum.ValueChangeAction.input
  }), /*#__PURE__*/_react["default"].createElement(_selectBox["default"], {
    name: "saveFilterValue"
  }, /*#__PURE__*/_react["default"].createElement(_selectBox["default"].Option, {
    value: 1
  }, (0, _localeContext.$l)('Table', 'query_option_yes')), /*#__PURE__*/_react["default"].createElement(_selectBox["default"].Option, {
    value: 0
  }, (0, _localeContext.$l)('Table', 'query_option_no'))), /*#__PURE__*/_react["default"].createElement(_switch["default"], {
    name: "defaultFlag",
    hidden: type === 'edit'
  }));
};

ModalContent.displayName = 'ModalContent';
var MemoModalContent = /*#__PURE__*/(0, _react.memo)(ModalContent);
/**
 * 快速筛选下拉
 */

exports.MemoModalContent = MemoModalContent;

var QuickFilterMenu = function QuickFilterMenu() {
  var _useContext2 = (0, _react.useContext)(_ConfigContext["default"]),
      getConfig = _useContext2.getConfig;

  var _useContext3 = (0, _react.useContext)(_QuickFilterMenuContext["default"]),
      tempQueryFields = _useContext3.tempQueryFields,
      autoQuery = _useContext3.autoQuery,
      dataSet = _useContext3.dataSet,
      menuDataSet = _useContext3.menuDataSet,
      prefixCls = _useContext3.prefixCls,
      queryDataSet = _useContext3.queryDataSet,
      filterMenuDataSet = _useContext3.filterMenuDataSet,
      conditionDataSet = _useContext3.conditionDataSet,
      newFilterDataSet = _useContext3.newFilterDataSet,
      _useContext3$onChange = _useContext3.onChange,
      onChange = _useContext3$onChange === void 0 ? _noop["default"] : _useContext3$onChange,
      conditionStatus = _useContext3.conditionStatus,
      _useContext3$onStatus = _useContext3.onStatusChange,
      onStatusChange = _useContext3$onStatus === void 0 ? _noop["default"] : _useContext3$onStatus,
      selectFields = _useContext3.selectFields,
      _useContext3$onOrigin = _useContext3.onOriginalChange,
      onOriginalChange = _useContext3$onOrigin === void 0 ? _noop["default"] : _useContext3$onOrigin,
      _useContext3$initCond = _useContext3.initConditionFields,
      initConditionFields = _useContext3$initCond === void 0 ? _noop["default"] : _useContext3$initCond,
      optionDataSet = _useContext3.optionDataSet,
      shouldLocateData = _useContext3.shouldLocateData,
      refEditors = _useContext3.refEditors,
      _useContext3$searchTe = _useContext3.searchText,
      searchText = _useContext3$searchTe === void 0 ? 'params' : _useContext3$searchTe,
      _useContext3$loadCond = _useContext3.loadConditionData,
      loadConditionData = _useContext3$loadCond === void 0 ? _noop["default"] : _useContext3$loadCond,
      defaultActiveKey = _useContext3.defaultActiveKey;

  var isChooseMenu = filterMenuDataSet && filterMenuDataSet.current && filterMenuDataSet.current.get('filterName');
  var isTenant = menuDataSet && menuDataSet.current && menuDataSet.current.get('isTenant');
  var shouldSaveValue = menuDataSet && menuDataSet.current && menuDataSet.current.get('saveFilterValue');
  /**
   * 替换个性化字段
   * @param conditionList
   */

  var initCustomFields = function initCustomFields(conditionList) {
    var fields = conditionList.map(function (condition) {
      return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, condition), {}, {
        name: condition.fieldName,
        defaultValue: condition.value
      });
    });
    (0, _mobx.runInAction)(function () {
      queryDataSet.fields = _mobx.observable.map(conditionList ? queryDataSet.initFields(fields) : undefined);
    });
  };
  /**
   * queryDS 筛选赋值并更新初始勾选项
   * @param init
   */


  var conditionAssign = /*#__PURE__*/function () {
    var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(init) {
      var current, shouldQuery, orgObj, conditionList, initData, tenantSelectFields, _isTenant, currentQueryRecord, emptyRecord, _emptyRecord, hasFocus, _iterator, _step, _step$value, key, value;

      return _regenerator["default"].wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              onOriginalChange();
              current = menuDataSet.current;
              shouldQuery = false; // 重置模糊搜素并判断是否查询

              orgObj = dataSet.getState(_TableDynamicFilterBar.ORIGINALVALUEOBJ);
              shouldQuery = dataSet.getState(_TableDynamicFilterBar.SEARCHTEXT) !== orgObj.fuzzy;
              dataSet.setState(_TableDynamicFilterBar.SEARCHTEXT, orgObj.fuzzy);
              dataSet.setQueryParameter(searchText, orgObj.fuzzy); // 重置高级搜索并判断是否查询

              shouldQuery = shouldQuery || newFilterDataSet.dirty;

              if (newFilterDataSet.dirty) {
                newFilterDataSet.reset();
                (0, _TableDynamicFilterBar.processFilterParam)(dataSet);
              }

              if (!current) {
                _context2.next = 36;
                break;
              }

              conditionList = current.get('conditionList');
              initData = {};
              tenantSelectFields = [];
              _isTenant = current.get('isTenant');

              if (_isTenant) {
                initCustomFields(conditionList);
              } else if (tempQueryFields) {
                (0, _mobx.runInAction)(function () {
                  queryDataSet.fields = tempQueryFields;
                });
              }

              currentQueryRecord = queryDataSet.current;

              if (conditionList && conditionList.length) {
                (0, _map["default"])(conditionList, function (condition) {
                  if (condition.comparator === 'EQUAL') {
                    var fieldName = condition.fieldName,
                        value = condition.value;
                    initData[fieldName] = (0, _TableDynamicFilterBar.parseValue)(value);
                    onChange(fieldName);
                  }

                  if (condition.usedFlag) {
                    tenantSelectFields.push(condition.fieldName);
                  }
                });
                onOriginalChange(Object.keys(initData));
                emptyRecord = new _Record["default"]((0, _objectSpread2["default"])({}, initData), queryDataSet);
                dataSet.setState(_TableDynamicFilterBar.SELECTFIELDS, _isTenant ? tenantSelectFields : Object.keys(initData));
                queryDataSet.setState(_TableDynamicFilterBar.SELECTFIELDS, _isTenant ? tenantSelectFields : Object.keys(initData));
                shouldQuery = shouldQuery || !(0, _TableDynamicFilterBar.isEqualDynamicProps)(initData, currentQueryRecord ? (0, _omit["default"])(currentQueryRecord.toData(true), ['__dirty']) : {}, queryDataSet, currentQueryRecord);
                (0, _mobx.runInAction)(function () {
                  queryDataSet.records.push(emptyRecord);
                  queryDataSet.current = emptyRecord;
                });

                if (_isTenant) {
                  initConditionFields({
                    dataSet: queryDataSet,
                    record: queryDataSet.current
                  });
                }

                onStatusChange(_enum2.RecordStatus.sync, emptyRecord.toData());
              } else {
                shouldQuery = shouldQuery || !(0, _TableDynamicFilterBar.isEqualDynamicProps)(initData, currentQueryRecord ? (0, _omit["default"])(currentQueryRecord.toData(true), ['__dirty']) : {}, queryDataSet, currentQueryRecord);
                _emptyRecord = new _Record["default"]({}, queryDataSet);
                dataSet.setState(_TableDynamicFilterBar.SELECTFIELDS, []);
                queryDataSet.setState(_TableDynamicFilterBar.SELECTFIELDS, []);
                (0, _mobx.runInAction)(function () {
                  queryDataSet.records.push(_emptyRecord);
                  queryDataSet.current = _emptyRecord;
                });
                onStatusChange(_enum2.RecordStatus.sync);
              }

              if (!(!init && shouldQuery && autoQuery)) {
                _context2.next = 36;
                break;
              }

              _context2.next = 20;
              return dataSet.modifiedCheck(undefined, dataSet, 'query');

            case 20:
              _context2.t2 = _context2.sent;

              if (!_context2.t2) {
                _context2.next = 23;
                break;
              }

              _context2.t2 = queryDataSet;

            case 23:
              _context2.t1 = _context2.t2;

              if (!_context2.t1) {
                _context2.next = 26;
                break;
              }

              _context2.t1 = queryDataSet.current;

            case 26:
              _context2.t0 = _context2.t1;

              if (!_context2.t0) {
                _context2.next = 31;
                break;
              }

              _context2.next = 30;
              return queryDataSet.current.validate();

            case 30:
              _context2.t0 = _context2.sent;

            case 31:
              if (!_context2.t0) {
                _context2.next = 35;
                break;
              }

              dataSet.query();
              _context2.next = 36;
              break;

            case 35:
              if (refEditors) {
                hasFocus = false;
                _iterator = (0, _createForOfIteratorHelper2["default"])(refEditors.entries());

                try {
                  for (_iterator.s(); !(_step = _iterator.n()).done;) {
                    _step$value = (0, _slicedToArray2["default"])(_step.value, 2), key = _step$value[0], value = _step$value[1];

                    if (value && !value.valid && !hasFocus) {
                      refEditors.get(key).focus();
                      hasFocus = true;
                    }
                  }
                } catch (err) {
                  _iterator.e(err);
                } finally {
                  _iterator.f();
                }
              }

            case 36:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));

    return function conditionAssign(_x) {
      return _ref4.apply(this, arguments);
    };
  }();

  var handleQueryReset = /*#__PURE__*/function () {
    var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() {
      var first, hasFocus, _iterator2, _step2, _step2$value, key, value;

      return _regenerator["default"].wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              if (!(filterMenuDataSet && filterMenuDataSet.current && filterMenuDataSet.current.get('filterName'))) {
                _context3.next = 4;
                break;
              }

              // 筛选项重置重新赋值
              conditionAssign();
              _context3.next = 28;
              break;

            case 4:
              /**
               * 未选择或清除筛选项
               * 重置初始勾选项及初始赋值
               */
              if (tempQueryFields) {
                (0, _mobx.runInAction)(function () {
                  queryDataSet.fields = tempQueryFields;
                });
              }

              queryDataSet.locate(0);
              menuDataSet.current = undefined;
              first = queryDataSet.get(0);

              if (first) {
                first.reset();
              }

              onOriginalChange();
              setFuzzyQuery();

              if (newFilterDataSet.dirty) {
                newFilterDataSet.reset();
                (0, _TableDynamicFilterBar.processFilterParam)(dataSet);
              }

              if (!autoQuery) {
                _context3.next = 28;
                break;
              }

              _context3.next = 15;
              return dataSet.modifiedCheck(undefined, dataSet, 'query');

            case 15:
              _context3.t1 = _context3.sent;

              if (!_context3.t1) {
                _context3.next = 18;
                break;
              }

              _context3.t1 = queryDataSet.current;

            case 18:
              _context3.t0 = _context3.t1;

              if (!_context3.t0) {
                _context3.next = 23;
                break;
              }

              _context3.next = 22;
              return queryDataSet.current.validate();

            case 22:
              _context3.t0 = _context3.sent;

            case 23:
              if (!_context3.t0) {
                _context3.next = 27;
                break;
              }

              dataSet.query();
              _context3.next = 28;
              break;

            case 27:
              if (refEditors) {
                hasFocus = false;
                _iterator2 = (0, _createForOfIteratorHelper2["default"])(refEditors.entries());

                try {
                  for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
                    _step2$value = (0, _slicedToArray2["default"])(_step2.value, 2), key = _step2$value[0], value = _step2$value[1];

                    if (value && !value.valid && !hasFocus) {
                      refEditors.get(key).focus();
                      hasFocus = true;
                    }
                  }
                } catch (err) {
                  _iterator2.e(err);
                } finally {
                  _iterator2.f();
                }
              }

            case 28:
              onStatusChange(_enum2.RecordStatus.sync);

            case 29:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }));

    return function handleQueryReset() {
      return _ref5.apply(this, arguments);
    };
  }();
  /**
   * 模糊搜索是否变更
   * @returns
   */


  var isFuzzyQueryChange = function isFuzzyQueryChange() {
    var menuRecord = menuDataSet && menuDataSet.current;

    if (menuRecord && menuRecord.get('queryList') && menuRecord.get('queryList').length) {
      var searchObj = menuRecord.get('queryList').find(function (ql) {
        return ql.fieldName === _TableDynamicFilterBar.SEARCHTEXT;
      });
      return searchObj ? searchObj.value !== dataSet.getState(_TableDynamicFilterBar.SEARCHTEXT) : false;
    }

    return dataSet.getState(_TableDynamicFilterBar.SEARCHTEXT) === null;
  };
  /**
   * 赋值模糊搜索
   * @param menuRecord
   */


  var setFuzzyQuery = function setFuzzyQuery(menuRecord) {
    var searchTextValue = null;

    if (menuRecord && menuRecord.get('queryList') && menuRecord.get('queryList').length) {
      var searchObj = menuRecord.get('queryList').find(function (ql) {
        return ql.fieldName === _TableDynamicFilterBar.SEARCHTEXT;
      });
      searchTextValue = searchObj ? searchObj.value : null;
    } // 切换数据更新初始化模糊搜索


    var newObj = dataSet.getState(_TableDynamicFilterBar.ORIGINALVALUEOBJ);
    dataSet.setState(_TableDynamicFilterBar.ORIGINALVALUEOBJ, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, newObj), {}, {
      fuzzy: searchTextValue
    }));
    dataSet.setState(_TableDynamicFilterBar.SEARCHTEXT, searchTextValue);
    dataSet.setQueryParameter(searchText, searchTextValue);
  };
  /**
   * 定位数据源
   * @param searchId
   * @param init 初始化
   */


  var locateData = function locateData(searchId, init) {
    var current = filterMenuDataSet ? filterMenuDataSet.current : undefined;

    if (searchId) {
      menuDataSet.locate(menuDataSet.findIndex(function (menu) {
        return menu.get('searchId').toString() === searchId.toString();
      }));
      var menuRecord = menuDataSet.current;

      if (menuRecord) {
        loadConditionData({
          menuRecord: menuRecord,
          conditionDataSet: conditionDataSet,
          newFilterDataSet: newFilterDataSet,
          dataSet: dataSet,
          searchText: searchText
        });
      }

      if (current) {
        current.set('filterName', searchId);
      }

      conditionAssign(init);
    } else if (searchId === null) {
      handleQueryReset();
    } else {
      var defaultMenus = menuDataSet ? menuDataSet.filter(function (menu) {
        return defaultActiveKey ? menu.get('searchId') === defaultActiveKey : menu.get('defaultFlag');
      }) : [];
      var defaultMenu = defaultMenus.length > 1 ? defaultMenus.find(function (menu) {
        return menu.get('isTenant') !== 1;
      }).index : defaultMenus.length && defaultMenus[0].index;

      if (defaultMenus.length && defaultMenu !== -1) {
        menuDataSet.locate(defaultMenu);
        var _menuRecord = menuDataSet.current;

        if (_menuRecord) {
          loadConditionData({
            menuRecord: _menuRecord,
            conditionDataSet: conditionDataSet,
            newFilterDataSet: newFilterDataSet,
            dataSet: dataSet,
            searchText: searchText
          });

          if (current) {
            current.set('filterName', _menuRecord.get('searchId'));
          }
        }

        conditionAssign(init);
      } else if (current) {
        current.set('filterName', undefined);
        setFuzzyQuery();
      }
    }
  };
  /**
   * 加载筛选数据并赋值查询
   * @param searchId
   */


  var loadData = /*#__PURE__*/function () {
    var _ref6 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(searchId) {
      var result, menuRecord, current;
      return _regenerator["default"].wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              _context4.next = 2;
              return menuDataSet.query();

            case 2:
              result = _context4.sent;

              if (optionDataSet) {
                optionDataSet.loadData(result);
              }

              menuRecord = menuDataSet.current;

              if (menuRecord) {
                loadConditionData({
                  menuRecord: menuRecord,
                  conditionDataSet: conditionDataSet,
                  newFilterDataSet: newFilterDataSet,
                  dataSet: dataSet,
                  searchText: searchText
                });
              }

              if (result && result.length) {
                locateData(searchId);
              } else {
                current = filterMenuDataSet.current;
                if (current) current.set('filterName', undefined);
                locateData(searchId);

                if (dataSet.props.autoQuery) {
                  dataSet.query();
                }
              }

            case 7:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4);
    }));

    return function loadData(_x2) {
      return _ref6.apply(this, arguments);
    };
  }();

  var handleChange = function handleChange(value) {
    var current = queryDataSet.current;

    if (current) {
      current.reset();
    }

    locateData(value);
  };
  /**
   * 删除该条筛选
   * @param record 下拉数据源
   */


  function handleDelete(_x3) {
    return _handleDelete.apply(this, arguments);
  }

  function _handleDelete() {
    _handleDelete = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(record) {
      var searchId, menuRecord, currentId, delRecord;
      return _regenerator["default"].wrap(function _callee7$(_context7) {
        while (1) {
          switch (_context7.prev = _context7.next) {
            case 0:
              searchId = record.get('searchId');
              menuRecord = menuDataSet.current;

              if (menuRecord) {
                currentId = menuRecord.get('searchId').toString();
                searchId = record.get('searchId').toString() === currentId ? null : currentId;
              } else if (typeof menuRecord === 'undefined') {
                searchId = undefined;
              }

              delRecord = menuDataSet.find(function (menu) {
                return menu.get('searchId').toString() === record.get('searchId').toString();
              });
              _context7.next = 6;
              return menuDataSet["delete"](delRecord, "".concat((0, _localeContext.$l)('Table', 'whether_delete_filter'), "\uFF1A").concat(record.get('searchName'), "\uFF1F"));

            case 6:
              loadData(searchId);

            case 7:
            case "end":
              return _context7.stop();
          }
        }
      }, _callee7);
    }));
    return _handleDelete.apply(this, arguments);
  }

  function getTitle(type) {
    switch (type) {
      case 'create':
        return (0, _localeContext.$l)('Table', 'save_filter');

      case 'edit':
        return (0, _localeContext.$l)('Table', 'filter_edit');

      default:
        return (0, _localeContext.$l)('Table', 'save_filter_as');
    }
  }

  function openModal(type, searchId, record) {
    if (searchId) {
      menuDataSet.locate(menuDataSet.findIndex(function (menu) {
        return menu.get('searchId').toString() === searchId.toString();
      }));
      var menuRecord = menuDataSet.current;

      if (menuRecord) {
        loadConditionData({
          menuRecord: menuRecord,
          conditionDataSet: conditionDataSet,
          newFilterDataSet: newFilterDataSet,
          dataSet: dataSet,
          searchText: searchText
        });
      }
    }

    _modal["default"].open({
      key: modalKey,
      closable: true,
      title: getTitle(type),
      children: /*#__PURE__*/_react["default"].createElement(MemoModalContent, {
        type: type,
        menuDataSet: menuDataSet,
        conditionDataSet: conditionDataSet,
        newFilterDataSet: newFilterDataSet,
        onLoadData: loadData,
        queryDataSet: queryDataSet,
        dataSet: dataSet,
        record: record,
        selectFields: selectFields
      }),
      okFirst: false,
      destroyOnClose: true
    });
  }

  var handleSave = /*#__PURE__*/function () {
    var _ref7 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5() {
      var filterMenuRecord, current, conditionData, putData, statusKey, statusAdd, statusUpdate, menuRecord, filterData, fuzzySrearchValue, fuzzySrearchData, res;
      return _regenerator["default"].wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              filterMenuRecord = filterMenuDataSet ? filterMenuDataSet.current : undefined;

              if (!((!filterMenuRecord || !filterMenuRecord.get('filterName')) && menuDataSet)) {
                _context5.next = 6;
                break;
              }

              openModal('create', '', menuDataSet.create({
                conExpression: dataSet.getState(_TableDynamicFilterBar.SEARCHEXP) ? dataSet.getState(_TableDynamicFilterBar.SEARCHEXP) : dataSet.getState(_TableDynamicFilterBar.EXPTYPE) || 'all'
              }));
              menuDataSet.setState('noLocate', true);
              _context5.next = 26;
              break;

            case 6:
              current = queryDataSet.current;

              if (!(current && conditionDataSet)) {
                _context5.next = 25;
                break;
              }

              conditionData = Object.entries((0, _omit["default"])(current.toData(), ['__dirty']));
              conditionDataSet.reset();
              conditionDataSet.map(function (record) {
                if (!selectFields || !selectFields.includes(record.get('fieldName'))) {
                  conditionDataSet.remove(record);
                }

                return null;
              });
              (0, _map["default"])(conditionData, function (data) {
                var fieldObj = findFieldObj(queryDataSet, data);

                if (fieldObj) {
                  var name = fieldObj.name;

                  if (name) {
                    var currentRecord = conditionDataSet.find(function (record) {
                      return record.get('fieldName') === name;
                    });

                    if (currentRecord) {
                      currentRecord.set('value', fieldObj.value);
                    } else if (isSelect(data)) {
                      conditionDataSet.create({
                        fieldName: name,
                        value: fieldObj.value
                      });
                    }
                  }
                }
              });
              putData = [];
              statusKey = getConfig('statusKey');
              statusAdd = getConfig('status').add;
              statusUpdate = getConfig('status').update;
              (0, _map["default"])(selectFields, function (fieldName) {
                var value = current.get(fieldName);
                var status = {};
                var toJSONFields = conditionDataSet.toJSONData().map(function (condition) {
                  return condition.fieldName;
                });
                status[statusKey] = statusAdd; // 处理空值已勾选条件

                if (!toJSONFields.includes(fieldName)) {
                  putData.push((0, _objectSpread2["default"])({
                    comparator: 'EQUAL',
                    fieldName: fieldName,
                    value: value
                  }, status));
                }
              });
              menuRecord = menuDataSet.current;

              if (menuRecord) {
                filterData = [];

                if (newFilterDataSet) {
                  filterData = newFilterDataSet.map(function (filterRecord) {
                    if (filterRecord.status !== _enum2.RecordStatus.sync) {
                      var status = {};
                      status[statusKey] = filterRecord.status === _enum2.RecordStatus.add ? statusAdd : statusUpdate;
                      return (0, _objectSpread2["default"])({
                        fieldName: filterRecord.get(_QuickFilterDataSet.AdvancedFieldSet.fieldName),
                        comparator: filterRecord.get(_QuickFilterDataSet.AdvancedFieldSet.comparator),
                        conditionType: filterRecord.get(_QuickFilterDataSet.AdvancedFieldSet.conditionType),
                        value: filterRecord.get('value')
                      }, status);
                    }

                    return null;
                  });
                }

                menuRecord.set('conditionList', [].concat((0, _toConsumableArray2["default"])(conditionDataSet.toJSONData()), putData, (0, _toConsumableArray2["default"])(filterData))); // 保存模糊搜素值

                fuzzySrearchValue = dataSet.getState(_TableDynamicFilterBar.SEARCHTEXT);
                fuzzySrearchData = [{
                  fieldName: _TableDynamicFilterBar.SEARCHTEXT,
                  comparator: 'EQUAL',
                  value: fuzzySrearchValue,
                  status: statusUpdate
                }];
                menuRecord.set('queryList', fuzzySrearchData);
              }

              _context5.next = 21;
              return menuDataSet.submit();

            case 21:
              res = _context5.sent;

              if (res && res.success) {
                loadData(res.content ? res.content[0].searchId : undefined);
              }

              _context5.next = 26;
              break;

            case 25:
              dataSet.query();

            case 26:
            case "end":
              return _context5.stop();
          }
        }
      }, _callee5);
    }));

    return function handleSave() {
      return _ref7.apply(this, arguments);
    };
  }();
  /**
   * 重命名，定位到重命名记录
   * @param record
   */


  var handleEdit = function handleEdit(record) {
    locateData(record.get('searchId'));
    openModal('edit', record.get('searchId'));
  };

  var handleSaveOther = function handleSaveOther() {
    var current = menuDataSet.current;

    if (current) {
      var searchName = current.get('searchName');
      current.set('searchName', "".concat(searchName, "_copy"));
    }

    openModal('save');
  };

  (0, _react.useEffect)(function () {
    var status = menuDataSet ? !menuDataSet.getState('noLocate') : true;

    if (shouldLocateData && status) {
      locateData(undefined, true);
    }
  }, [shouldLocateData, menuDataSet && menuDataSet.length]);
  /**
   * 默认设置
   * @param defaultFlag
   * @param record
   */

  var setDefaultFlag = /*#__PURE__*/function () {
    var _ref8 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(defaultFlag, record) {
      var currentRecord, res, result;
      return _regenerator["default"].wrap(function _callee6$(_context6) {
        while (1) {
          switch (_context6.prev = _context6.next) {
            case 0:
              record.set('defaultFlag', defaultFlag);
              currentRecord = menuDataSet.find(function (menu) {
                return menu.get('searchId').toString() === record.get('searchId').toString();
              });

              if (currentRecord) {
                currentRecord.set('defaultFlag', defaultFlag);
              }

              _context6.next = 5;
              return menuDataSet.submit();

            case 5:
              res = _context6.sent;
              _context6.next = 8;
              return menuDataSet.query();

            case 8:
              result = _context6.sent;

              if (optionDataSet) {
                optionDataSet.loadData(result);
              }

              if (res && res.failed || !res) {
                record.reset();

                if (currentRecord) {
                  currentRecord.reset();
                }
              }

            case 11:
            case "end":
              return _context6.stop();
          }
        }
      }, _callee6);
    }));

    return function setDefaultFlag(_x4, _x5) {
      return _ref8.apply(this, arguments);
    };
  }();
  /**
   * 渲染下拉选项
   * @param record
   * @param text
   */


  var optionRenderer = function optionRenderer(_ref9) {
    var record = _ref9.record,
        text = _ref9.text;
    var filterMenuRecord = filterMenuDataSet ? filterMenuDataSet.current : undefined;
    var isSelected = String(filterMenuRecord && filterMenuRecord.get('filterName')) === String(record.get('searchId'));
    var isDefault = record.get('defaultFlag') === 1;
    var isTenant = record.get('isTenant') === (0, _localeContext.$l)('Table', 'preset');

    var menu = /*#__PURE__*/_react["default"].createElement(_menu["default"], {
      onClick: function onClick(_ref10) {
        var key = _ref10.key,
            domEvent = _ref10.domEvent;
        domEvent.preventDefault();
        domEvent.stopPropagation();

        if (key === 'filter_default') {
          setDefaultFlag(record.get('defaultFlag') ? 0 : 1, record);
        } else if (key === 'filter_edit') {
          handleEdit(record);
        } else {
          handleDelete(record);
        }
      }
    }, /*#__PURE__*/_react["default"].createElement(_menu["default"].Item, {
      key: 'filter_default'
    }, record.get('defaultFlag') ? (0, _localeContext.$l)('Table', 'cancel_default') : (0, _localeContext.$l)('Table', 'set_default')), /*#__PURE__*/_react["default"].createElement(_menu["default"].Item, {
      key: 'filter_edit'
    }, (0, _localeContext.$l)('Table', 'filter_edit')), /*#__PURE__*/_react["default"].createElement(_menu["default"].Item, {
      key: 'filter_delete'
    }, (0, _localeContext.$l)('Table', 'delete_button')));

    return /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefixCls, "-filter-menu-option")
    }, /*#__PURE__*/_react["default"].createElement("span", {
      className: "".concat(prefixCls, "-filter-menu-option-content"),
      onMouseEnter: function onMouseEnter(e) {
        var currentTarget = e.currentTarget;

        if ((0, _util["default"])(currentTarget)) {
          (0, _singleton.show)(currentTarget, {
            title: text
          });
        }
      },
      onMouseLeave: function onMouseLeave() {
        return (0, _singleton.hide)();
      }
    }, text), isDefault && /*#__PURE__*/_react["default"].createElement(_tag["default"], null, (0, _localeContext.$l)('Table', 'default_flag')), isSelected && /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefixCls, "-filter-menu-option-selected")
    }, /*#__PURE__*/_react["default"].createElement(_icon["default"], {
      type: "check"
    })), !isTenant && /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefixCls, "-filter-menu-option-icons")
    }, /*#__PURE__*/_react["default"].createElement(_dropdown["default"], {
      overlay: menu
    }, /*#__PURE__*/_react["default"].createElement("span", {
      style: {
        userSelect: 'none'
      }
    }, /*#__PURE__*/_react["default"].createElement(_icon["default"], {
      type: "more_horiz"
    })))));
  }; // 租户预置筛选，无保存按钮和另存为


  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_select["default"], {
    isFlat: true,
    placeholder: (0, _localeContext.$l)('Table', 'fast_filter'),
    className: "".concat(prefixCls, "-filterName-select"),
    dataSet: filterMenuDataSet,
    name: "filterName",
    dropdownMatchSelectWidth: false,
    dropdownMenuStyle: {
      width: '1.72rem'
    },
    optionRenderer: optionRenderer,
    onChange: handleChange,
    notFoundContent: (0, _localeContext.$l)('Table', 'no_save_filter')
  }), conditionStatus === _enum2.RecordStatus.update ? /*#__PURE__*/_react["default"].createElement(_tag["default"], {
    className: "".concat(prefixCls, "-filter-status")
  }, /*#__PURE__*/_react["default"].createElement("span", null, (0, _localeContext.$l)('Table', 'modified'))) : null, conditionStatus === _enum2.RecordStatus.update && /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(prefixCls, "-filter-buttons")
  }, isChooseMenu && (isTenant ? null : /*#__PURE__*/_react["default"].createElement(_button["default"], {
    onClick: handleSaveOther
  }, (0, _localeContext.$l)('Table', 'save_as'))), !isFuzzyQueryChange() && (isChooseMenu ? isTenant || conditionStatus === _enum2.RecordStatus.update && dataSet.getState(_TableDynamicFilterBar.SELECTCHANGE) && !shouldSaveValue && menuDataSet && menuDataSet.length : false) ? null : /*#__PURE__*/_react["default"].createElement(_button["default"], {
    onClick: handleSave,
    hidden: isTenant
  }, (0, _localeContext.$l)('Table', 'save_button')), /*#__PURE__*/_react["default"].createElement(_button["default"], {
    onClick: handleQueryReset
  }, (0, _localeContext.$l)('Table', 'reset_button'))));
};

QuickFilterMenu.displayName = 'QuickFilterMenu';

var _default = (0, _mobxReactLite.observer)(QuickFilterMenu);

exports["default"] = _default;
//# sourceMappingURL=QuickFilterMenu.js.map
