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

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

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

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

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

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

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

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 _isEqual = _interopRequireDefault(require("lodash/isEqual"));

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

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

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

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

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

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

var _TableComboBar = require("../TableComboBar");

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

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

/**
 * 根据数据查找需要处理的字段对象
 * @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 _value;

    var textField = field.get('textField');
    var valueField = field.get('valueField');

    if ((0, _typeof2["default"])(value) !== 'object') {
      return {
        name: name,
        value: value,
        originalValue: field.getValue().slice()
      };
    }

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

  if (field && field.get('ignore') !== 'always') {
    return {
      name: name,
      value: value
    };
  }
}
/**
 * 快速筛选下拉
 */


var QuickFilterButton = function QuickFilterButton() {
  var _useState = (0, _react.useState)(false),
      _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
      customizedChange = _useState2[0],
      setCustomizedChange = _useState2[1];

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

  var _useContext2 = (0, _react.useContext)(_QuickFilterMenuContext["default"]),
      tempQueryFields = _useContext2.tempQueryFields,
      autoQuery = _useContext2.autoQuery,
      dataSet = _useContext2.dataSet,
      menuDataSet = _useContext2.menuDataSet,
      prefixCls = _useContext2.prefixCls,
      queryDataSet = _useContext2.queryDataSet,
      filterMenuDataSet = _useContext2.filterMenuDataSet,
      conditionDataSet = _useContext2.conditionDataSet,
      _useContext2$onChange = _useContext2.onChange,
      onChange = _useContext2$onChange === void 0 ? _noop["default"] : _useContext2$onChange,
      conditionStatus = _useContext2.conditionStatus,
      _useContext2$onStatus = _useContext2.onStatusChange,
      onStatusChange = _useContext2$onStatus === void 0 ? _noop["default"] : _useContext2$onStatus,
      selectFields = _useContext2.selectFields,
      _useContext2$onOrigin = _useContext2.onOriginalChange,
      onOriginalChange = _useContext2$onOrigin === void 0 ? _noop["default"] : _useContext2$onOrigin,
      _useContext2$filterSa = _useContext2.filterSave,
      filterSave = _useContext2$filterSa === void 0 ? true : _useContext2$filterSa,
      _useContext2$filterSa2 = _useContext2.filterSaveCallback,
      filterSaveCallback = _useContext2$filterSa2 === void 0 ? _noop["default"] : _useContext2$filterSa2,
      _useContext2$onReset = _useContext2.onReset,
      onReset = _useContext2$onReset === void 0 ? _noop["default"] : _useContext2$onReset,
      tableStore = _useContext2.tableStore,
      refEditors = _useContext2.refEditors;

  var isChooseMenu = filterMenuDataSet && filterMenuDataSet.current && filterMenuDataSet.current.get('filterName');
  var personalColumn = menuDataSet && menuDataSet.current && menuDataSet.current.get('personalColumn') && (0, _TableDynamicFilterBar.parseValue)(menuDataSet.current.get('personalColumn')) || {};
  var customized = tableStore && tableStore.customized;
  (0, _react.useEffect)(function () {
    if (customized || personalColumn) {
      var columns = customized && customized.columns;
      setCustomizedChange((0, _isEqual["default"])((0, _TableDynamicFilterBar.parseValue)(columns), personalColumn));
    }
  }, [customized, personalColumn]);
  /**
   * queryDS 筛选赋值并更新初始勾选项
   * @param init
   */

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

      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              onOriginalChange();
              current = menuDataSet.current;
              shouldQuery = false;

              if (!current) {
                _context.next = 30;
                break;
              }

              conditionList = current.get('personalFilter') && (0, _TableDynamicFilterBar.parseValue)(current.get('personalFilter'));
              initData = {};

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

              currentQueryRecord = queryDataSet.current;

              if (conditionList && conditionList.length) {
                (0, _map["default"])(conditionList, function (condition) {
                  var fieldName = condition.fieldName,
                      value = condition.value;
                  initData[fieldName] = (0, _TableDynamicFilterBar.parseValue)(value);
                  onChange(fieldName);
                });
                onOriginalChange(Object.keys(initData));
                emptyRecord = new _Record["default"]((0, _objectSpread2["default"])({}, initData), queryDataSet);
                dataSet.setState(_TableComboBar.SELECTFIELDS, Object.keys(initData));
                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;
                });
                onStatusChange(_enum2.RecordStatus.sync, emptyRecord.toData());
              } else {
                shouldQuery = !(0, _TableDynamicFilterBar.isEqualDynamicProps)(initData, currentQueryRecord ? (0, _omit["default"])(currentQueryRecord.toData(true), ['__dirty']) : {}, queryDataSet, currentQueryRecord);
                _emptyRecord = new _Record["default"]({}, queryDataSet);
                dataSet.setState(_TableComboBar.SELECTFIELDS, []);
                (0, _mobx.runInAction)(function () {
                  queryDataSet.records.push(_emptyRecord);
                  queryDataSet.current = _emptyRecord;
                });
                onStatusChange(_enum2.RecordStatus.sync);
              }

              customizedColumn = current.get('personalColumn') && (0, _TableDynamicFilterBar.parseValue)(current.get('personalColumn'));

              if (tableStore) {
                (0, _mobx.runInAction)(function () {
                  var newCustomized = {
                    columns: (0, _objectSpread2["default"])({}, customizedColumn)
                  };
                  tableStore.tempCustomized = {
                    columns: {}
                  };
                  tableStore.saveCustomized(newCustomized);
                  tableStore.initColumns();
                });
              }

              if (!(!init && shouldQuery && autoQuery)) {
                _context.next = 30;
                break;
              }

              _context.next = 14;
              return dataSet.modifiedCheck(undefined, dataSet, 'query');

            case 14:
              _context.t2 = _context.sent;

              if (!_context.t2) {
                _context.next = 17;
                break;
              }

              _context.t2 = queryDataSet;

            case 17:
              _context.t1 = _context.t2;

              if (!_context.t1) {
                _context.next = 20;
                break;
              }

              _context.t1 = queryDataSet.current;

            case 20:
              _context.t0 = _context.t1;

              if (!_context.t0) {
                _context.next = 25;
                break;
              }

              _context.next = 24;
              return queryDataSet.current.validate();

            case 24:
              _context.t0 = _context.sent;

            case 25:
              if (!_context.t0) {
                _context.next = 29;
                break;
              }

              dataSet.query();
              _context.next = 30;
              break;

            case 29:
              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 30:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

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

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

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

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

            case 4:
              /**
               * 未选择或清除筛选项
               * 重置初始勾选项及初始赋值
               */
              queryDataSet.locate(0);
              first = queryDataSet.get(0);

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

              onOriginalChange();

              if (!autoQuery) {
                _context2.next = 24;
                break;
              }

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

            case 11:
              _context2.t1 = _context2.sent;

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

              _context2.t1 = queryDataSet;

            case 14:
              _context2.t0 = _context2.t1;

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

              _context2.next = 18;
              return queryDataSet.validate();

            case 18:
              _context2.t0 = _context2.sent;

            case 19:
              if (!_context2.t0) {
                _context2.next = 23;
                break;
              }

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

            case 23:
              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 24:
              onReset();
              onStatusChange(_enum2.RecordStatus.sync);

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

    return function handleQueryReset() {
      return _ref2.apply(this, arguments);
    };
  }();

  var handleSave = /*#__PURE__*/function () {
    var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() {
      var current, conditionData, putData, data, customizedColumns;
      return _regenerator["default"].wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              current = queryDataSet.current;

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

                  if (!toJSONFields.includes(fieldName)) {
                    putData.push((0, _objectSpread2["default"])({
                      fieldName: fieldName,
                      value: value
                    }, status));
                  }
                });
                data = [].concat((0, _toConsumableArray2["default"])(conditionDataSet.toJSONData()), putData);
                customizedColumns = tableStore && tableStore.customized && tableStore.customized.columns;
                filterSaveCallback({
                  personalFilter: (0, _TableDynamicFilterBar.stringifyValue)(data),
                  personalColumn: (0, _TableDynamicFilterBar.stringifyValue)(customizedColumns)
                });
              } else {
                dataSet.query();
              }

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

    return function handleSave() {
      return _ref3.apply(this, arguments);
    };
  }();

  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, (conditionStatus === _enum2.RecordStatus.update || !customizedChange) && /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(prefixCls, "-combo-filter-buttons")
  }, isChooseMenu && filterSave && /*#__PURE__*/_react["default"].createElement(_button["default"], {
    onClick: handleSave,
    color: _enum.ButtonColor.primary
  }, (0, _localeContext.$l)('Table', 'save_button')), /*#__PURE__*/_react["default"].createElement(_button["default"], {
    onClick: handleQueryReset,
    color: _enum.ButtonColor.secondary
  }, (0, _localeContext.$l)('Table', 'reset_button'))));
};

QuickFilterButton.displayName = 'QuickFilterButton';

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

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