import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _createForOfIteratorHelper from "@babel/runtime/helpers/createForOfIteratorHelper";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _typeof from "@babel/runtime/helpers/typeof";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import React, { useContext, useEffect, useState } from 'react';
import { runInAction } from 'mobx';
import { observer } from 'mobx-react-lite';
import map from 'lodash/map';
import isObject from 'lodash/isObject';
import isEnumEmpty from 'lodash/isEmpty';
import isArray from 'lodash/isArray';
import noop from 'lodash/noop';
import omit from 'lodash/omit';
import isEqual from 'lodash/isEqual';
import ConfigContext from '../../../../../es/config-provider/ConfigContext';
import { $l } from '../../../locale-context';
import Button from '../../../button';
import { ButtonColor } from '../../../button/enum';
import Record from '../../../data-set/Record';
import { RecordStatus } from '../../../data-set/enum';
import { SELECTFIELDS } from '../TableComboBar';
import { isEqualDynamicProps, parseValue, stringifyValue, isSelect } from '../TableDynamicFilterBar';
import Store from './QuickFilterMenuContext';
/**
 * 根据数据查找需要处理的字段对象
 * @param queryDataSet
 * @param data
 */

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

  if (!queryDataSet.fields.has(data[0]) && isObject(data[1]) && !isEnumEmpty(data[1]) && !isArray(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 (_typeof(value) !== 'object') {
      return {
        name: name,
        value: value,
        originalValue: field.getValue().slice()
      };
    }

    return {
      name: name,
      value: (_value = {}, _defineProperty(_value, valueField, value[valueField]), _defineProperty(_value, textField, value[textField]), _value)
    };
  }

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


var QuickFilterButton = function QuickFilterButton() {
  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      customizedChange = _useState2[0],
      setCustomizedChange = _useState2[1];

  var _useContext = useContext(ConfigContext),
      getConfig = _useContext.getConfig;

  var _useContext2 = useContext(Store),
      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 : _useContext2$onChange,
      conditionStatus = _useContext2.conditionStatus,
      _useContext2$onStatus = _useContext2.onStatusChange,
      onStatusChange = _useContext2$onStatus === void 0 ? noop : _useContext2$onStatus,
      selectFields = _useContext2.selectFields,
      _useContext2$onOrigin = _useContext2.onOriginalChange,
      onOriginalChange = _useContext2$onOrigin === void 0 ? noop : _useContext2$onOrigin,
      _useContext2$filterSa = _useContext2.filterSave,
      filterSave = _useContext2$filterSa === void 0 ? true : _useContext2$filterSa,
      _useContext2$filterSa2 = _useContext2.filterSaveCallback,
      filterSaveCallback = _useContext2$filterSa2 === void 0 ? noop : _useContext2$filterSa2,
      _useContext2$onReset = _useContext2.onReset,
      onReset = _useContext2$onReset === void 0 ? noop : _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') && parseValue(menuDataSet.current.get('personalColumn')) || {};
  var customized = tableStore && tableStore.customized;
  useEffect(function () {
    if (customized || personalColumn) {
      var columns = customized && customized.columns;
      setCustomizedChange(isEqual(parseValue(columns), personalColumn));
    }
  }, [customized, personalColumn]);
  /**
   * queryDS 筛选赋值并更新初始勾选项
   * @param init
   */

  var conditionAssign = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(init) {
      var current, shouldQuery, conditionList, initData, currentQueryRecord, emptyRecord, _emptyRecord, customizedColumn, hasFocus, _iterator, _step, _step$value, key, value;

      return _regeneratorRuntime.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') && parseValue(current.get('personalFilter'));
              initData = {};

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

              currentQueryRecord = queryDataSet.current;

              if (conditionList && conditionList.length) {
                map(conditionList, function (condition) {
                  var fieldName = condition.fieldName,
                      value = condition.value;
                  initData[fieldName] = parseValue(value);
                  onChange(fieldName);
                });
                onOriginalChange(Object.keys(initData));
                emptyRecord = new Record(_objectSpread({}, initData), queryDataSet);
                dataSet.setState(SELECTFIELDS, Object.keys(initData));
                shouldQuery = !isEqualDynamicProps(initData, currentQueryRecord ? omit(currentQueryRecord.toData(true), ['__dirty']) : {}, queryDataSet, currentQueryRecord);
                runInAction(function () {
                  queryDataSet.records.push(emptyRecord);
                  queryDataSet.current = emptyRecord;
                });
                onStatusChange(RecordStatus.sync, emptyRecord.toData());
              } else {
                shouldQuery = !isEqualDynamicProps(initData, currentQueryRecord ? omit(currentQueryRecord.toData(true), ['__dirty']) : {}, queryDataSet, currentQueryRecord);
                _emptyRecord = new Record({}, queryDataSet);
                dataSet.setState(SELECTFIELDS, []);
                runInAction(function () {
                  queryDataSet.records.push(_emptyRecord);
                  queryDataSet.current = _emptyRecord;
                });
                onStatusChange(RecordStatus.sync);
              }

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

              if (tableStore) {
                runInAction(function () {
                  var newCustomized = {
                    columns: _objectSpread({}, 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 = _createForOfIteratorHelper(refEditors.entries());

                try {
                  for (_iterator.s(); !(_step = _iterator.n()).done;) {
                    _step$value = _slicedToArray(_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 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
      var first, hasFocus, _iterator2, _step2, _step2$value, key, value;

      return _regeneratorRuntime.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 = _createForOfIteratorHelper(refEditors.entries());

                try {
                  for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
                    _step2$value = _slicedToArray(_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(RecordStatus.sync);

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

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

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

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

                  return null;
                });
                map(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 (isSelect(data)) {
                        conditionDataSet.create({
                          fieldName: name,
                          value: fieldObj.value,
                          originalValue: fieldObj.originalValue
                        });
                      }
                    }
                  }
                });
                putData = [];
                map(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(_objectSpread({
                      fieldName: fieldName,
                      value: value
                    }, status));
                  }
                });
                data = [].concat(_toConsumableArray(conditionDataSet.toJSONData()), putData);
                customizedColumns = tableStore && tableStore.customized && tableStore.customized.columns;
                filterSaveCallback({
                  personalFilter: stringifyValue(data),
                  personalColumn: stringifyValue(customizedColumns)
                });
              } else {
                dataSet.query();
              }

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

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

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

QuickFilterButton.displayName = 'QuickFilterButton';
export default observer(QuickFilterButton);
//# sourceMappingURL=QuickFilterButton.js.map
