import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import React, { useContext, useEffect } from 'react';
import { runInAction } from 'mobx';
import { observer } from 'mobx-react-lite';
import map from 'lodash/map';
import noop from 'lodash/noop';
import omit from 'lodash/omit';
import { $l } from '../../../locale-context';
import Select from '../../../select';
import Record from '../../../data-set/Record';
import { RecordStatus } from '../../../data-set/enum';
import { hide, show } from '../../../tooltip/singleton';
import isOverflow from '../../../overflow-tip/util';
import { SELECTFIELDS } from '../TableComboBar';
import { isEqualDynamicProps, parseValue } from '../TableDynamicFilterBar';
import Store from './QuickFilterMenuContext';
/**
 * 快速筛选下拉
 */

var QuickFilterMenu = function QuickFilterMenu() {
  var _useContext = useContext(Store),
      tempQueryFields = _useContext.tempQueryFields,
      autoQuery = _useContext.autoQuery,
      dataSet = _useContext.dataSet,
      menuDataSet = _useContext.menuDataSet,
      prefixCls = _useContext.prefixCls,
      queryDataSet = _useContext.queryDataSet,
      filterMenuDataSet = _useContext.filterMenuDataSet,
      conditionDataSet = _useContext.conditionDataSet,
      _useContext$onChange = _useContext.onChange,
      onChange = _useContext$onChange === void 0 ? noop : _useContext$onChange,
      _useContext$onStatusC = _useContext.onStatusChange,
      onStatusChange = _useContext$onStatusC === void 0 ? noop : _useContext$onStatusC,
      _useContext$onOrigina = _useContext.onOriginalChange,
      onOriginalChange = _useContext$onOrigina === void 0 ? noop : _useContext$onOrigina,
      shouldLocateData = _useContext.shouldLocateData,
      initSearchId = _useContext.initSearchId,
      _useContext$filterCal = _useContext.filterCallback,
      filterCallback = _useContext$filterCal === void 0 ? noop : _useContext$filterCal,
      _useContext$filterOpt = _useContext.filterOptionRenderer,
      filterOptionRenderer = _useContext$filterOpt === void 0 ? noop : _useContext$filterOpt,
      tableStore = _useContext.tableStore;
  /**
   * queryDS 筛选赋值并更新初始勾选项
   * @param init
   */


  var conditionAssign = function conditionAssign(init) {
    onOriginalChange();
    var current = menuDataSet.current;
    var shouldQuery = false;

    if (current) {
      var conditionList = current.get('personalFilter') && parseValue(current.get('personalFilter'));
      var initData = {};

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

      var 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));
        var 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);

        var _emptyRecord = new Record({}, queryDataSet);

        dataSet.setState(SELECTFIELDS, []);
        runInAction(function () {
          queryDataSet.records.push(_emptyRecord);
          queryDataSet.current = _emptyRecord;
        });
        onStatusChange(RecordStatus.sync);
      }

      var 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) {
        dataSet.query();
      }
    }
  };

  var handleQueryReset = function handleQueryReset() {
    if (filterMenuDataSet && filterMenuDataSet.current && filterMenuDataSet.current.get('filterName')) {
      // 筛选项重置重新赋值
      conditionAssign();
    } else {
      /**
       * 未选择或清除筛选项
       * 重置初始勾选项及初始赋值
       */
      queryDataSet.locate(0);
      var first = queryDataSet.get(0);

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

      onOriginalChange();

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

    onStatusChange(RecordStatus.sync);
  };
  /**
   * 定位数据源
   * @param searchId
   * @param init 初始化
   */


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

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

      if (menuRecord) {
        var conditionList = menuRecord.get('personalFilter') && parseValue(menuRecord.get('personalFilter'));
        conditionDataSet.loadData(conditionList);
      }

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

      conditionAssign(init);
    } else if (searchId === null) {
      handleQueryReset();
    } else if (menuDataSet.length) {
      menuDataSet.locate(0);
      var _menuRecord = menuDataSet.current;

      if (_menuRecord) {
        var _conditionList = _menuRecord.get('personalFilter') && parseValue(_menuRecord.get('personalFilter'));

        conditionDataSet.loadData(_conditionList);

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

        var customizedColumn = _menuRecord.get('personalColumn') && parseValue(_menuRecord.get('personalColumn'));

        if (tableStore) {
          runInAction(function () {
            var newCustomized = {
              columns: _objectSpread({}, customizedColumn)
            };
            tableStore.tempCustomized = {
              columns: {}
            };
            tableStore.saveCustomized(newCustomized);
            tableStore.initColumns();
          });
        }
      }

      conditionAssign(init);
    } else if (current) {
      current.set('filterName', undefined);
    }
  };

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

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

    locateData(value);
  };

  useEffect(function () {
    if (shouldLocateData) {
      locateData(initSearchId, true);
    }
  }, [shouldLocateData, initSearchId]);
  /**
   * 渲染下拉选项
   * @param record
   * @param text
   */

  var optionRenderer = function optionRenderer(_ref) {
    var value = _ref.value,
        text = _ref.text;
    var menuRecord = menuDataSet.find(function (menu) {
      return menu.get('searchId').toString() === value.toString();
    });
    var icon = menuRecord && menuRecord.get('searchIcon');
    return /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-combo-filter-menu-option")
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-combo-filter-menu-option-content"),
      onMouseEnter: function onMouseEnter(e) {
        var currentTarget = e.currentTarget;

        if (isOverflow(currentTarget)) {
          show(currentTarget, {
            title: text
          });
        }
      },
      onMouseLeave: function onMouseLeave() {
        return hide();
      }
    }, filterOptionRenderer(value, text, icon) || text));
  };

  return /*#__PURE__*/React.createElement(Select, {
    isFlat: true,
    placeholder: $l('Table', 'fast_filter'),
    className: "".concat(prefixCls, "-combo-filterName-select"),
    popupCls: "".concat(prefixCls, "-combo-filterName-select-content"),
    dataSet: filterMenuDataSet,
    name: "filterName",
    dropdownMatchSelectWidth: false,
    dropdownMenuStyle: {
      width: '1.72rem'
    },
    optionRenderer: optionRenderer,
    onChange: handleChange,
    notFoundContent: $l('Table', 'no_save_filter'),
    clearButton: false,
    searchable: false
  });
};

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