import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _inherits from "@babel/runtime/helpers/inherits";
import _createSuper from "@babel/runtime/helpers/createSuper";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _extends from "@babel/runtime/helpers/extends";
var _excluded = ["afterClick"],
    _excluded2 = ["afterClick"];
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { __decorate } from "tslib";
import React, { cloneElement, Component, isValidElement, useState } from 'react';
import { observer } from 'mobx-react';
import { action, isArrayLike, observable } from 'mobx';
import isObject from 'lodash/isObject';
import isString from 'lodash/isString';
import isNumber from 'lodash/isNumber';
import { pxToRem } from '../../../../es/_util/UnitConvertor';
import Icon from '../../../../es/icon';
import { ProgressStatus } from '../../../../es/progress/enum';
import { math } from 'choerodon-ui/dataset';
import noop from 'lodash/noop';
import { TableButtonType, TableQueryBarType } from '../enum';
import TableButtons from './TableButtons';
import Table from '../Table';
import Button from '../../button/Button';
import Radio from '../../radio';
import { ButtonColor, ButtonType, FuncType } from '../../button/enum';
import { DataSetExportStatus, DataSetStatus, FieldType } from '../../data-set/enum';
import { $l } from '../../locale-context';
import TableContext from '../TableContext';
import autobind from '../../_util/autobind';
import DataSet from '../../data-set';
import Modal from '../../modal';
import Progress from '../../progress';
import Column from '../Column';
import { getEditorByField, getPlaceholderByField, getTableHeaderRows } from '../utils';
import CombineSort from './CombineSort';
import TableToolBar from './TableToolBar';
import TableFilterBar from './TableFilterBar';
import TableAdvancedQueryBar from './TableAdvancedQueryBar';
import TableProfessionalBar from './TableProfessionalBar';
import TableComboBar from './TableComboBar';
import TableDynamicFilterBar from './TableDynamicFilterBar';
import { exportExcel, findBindFieldBy } from '../../data-set/utils';
import Dropdown from '../../dropdown/Dropdown';
import Menu from '../../menu';
import TextField from '../../text-field';
var ExportBody = observer(function (props) {
  var dataSet = props.dataSet,
      prefixCls = props.prefixCls;
  var exportMessage = $l('Table', 'export_ing');
  var exportProgress = {
    percent: 1,
    status: ProgressStatus.active
  };

  switch (dataSet.exportStatus) {
    case DataSetExportStatus.start:
      exportProgress = {
        percent: 1,
        status: ProgressStatus.active
      };
      break;

    case DataSetExportStatus.exporting:
      exportProgress = {
        percent: dataSet.exportProgress,
        status: ProgressStatus.active
      };
      break;

    case DataSetExportStatus.progressing:
      exportProgress = {
        percent: dataSet.exportProgress,
        status: ProgressStatus.active
      };
      break;

    case DataSetExportStatus.failed:
      exportMessage = $l('Table', 'export_failed');
      exportProgress = {
        percent: 50,
        status: ProgressStatus.exception
      };
      break;

    case DataSetExportStatus.success:
      exportMessage = $l('Table', 'export_success');
      exportProgress = {
        percent: 100,
        status: ProgressStatus.success
      };
      break;

    default:
      break;
  }

  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-export-progress-body")
  }, /*#__PURE__*/React.createElement("span", null, exportMessage), /*#__PURE__*/React.createElement(Progress, _extends({}, exportProgress)));
});
var ExportFooter = observer(function (props) {
  var dataSet = props.dataSet,
      prefixCls = props.prefixCls,
      exportButton = props.exportButton;

  var _useState = useState(dataSet.name || $l('Table', 'default_export')),
      _useState2 = _slicedToArray(_useState, 2),
      username = _useState2[0],
      setUsername = _useState2[1];

  var handleClick = function handleClick() {
    exportButton(dataSet.exportStatus, username);
  };

  var _useState3 = useState(undefined),
      _useState4 = _slicedToArray(_useState3, 2),
      messageTimeout = _useState4[0],
      setMessageTimeout = _useState4[1];

  React.useEffect(function () {
    var currentTimeout = null;
    currentTimeout = setTimeout(function () {
      if (dataSet && dataSet.exportStatus !== DataSetExportStatus.success && dataSet.exportStatus !== DataSetExportStatus.failed) {
        setMessageTimeout($l('Table', 'export_waiting'));
      }
    }, 5000);
    return function () {
      if (currentTimeout) {
        clearTimeout(currentTimeout);
      }
    };
  }, []);
  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-export-progress-footer")
  }, dataSet.exportStatus === DataSetExportStatus.failed && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", null, $l('Table', 'export_break')), /*#__PURE__*/React.createElement(Button, {
    onClick: handleClick
  }, $l('Table', 'retry_button'))), dataSet.exportStatus === DataSetExportStatus.success && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("span", null, "".concat($l('Table', 'file_name'), ":")), /*#__PURE__*/React.createElement(TextField, {
    value: username,
    onChange: function onChange(value) {
      setUsername(value);
    }
  })), /*#__PURE__*/React.createElement(Button, {
    color: ButtonColor.primary,
    onClick: handleClick
  }, $l('Table', 'download_button'))), dataSet.exportStatus !== DataSetExportStatus.success && dataSet.exportStatus !== DataSetExportStatus.failed && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", null, messageTimeout || $l('Table', 'export_operating')), /*#__PURE__*/React.createElement(Button, {
    color: ButtonColor.gray,
    onClick: handleClick
  }, $l('Table', 'cancel_button'))));
});

var TableQueryBar = /*#__PURE__*/function (_Component) {
  _inherits(TableQueryBar, _Component);

  var _super = _createSuper(TableQueryBar);

  function TableQueryBar() {
    var _this;

    _classCallCheck(this, TableQueryBar);

    _this = _super.apply(this, arguments);
    _this.queryFieldsElement = [];
    /**
     * 点击汇总条展开收起
     * @param summary
     */

    _this.openMore = function (summary) {
      if (_this.moreSummary && _this.moreSummary.length) {
        _this.moreSummary = [];
      } else {
        _this.moreSummary = _this.renderSummary(summary);
      }

      return _this.moreSummary;
    };

    return _this;
  }

  _createClass(TableQueryBar, [{
    key: "showQueryBar",
    get: function get() {
      var showQueryBar = this.props.showQueryBar,
          queryBar = this.context.tableStore.queryBar;
      return showQueryBar !== false && queryBar !== TableQueryBarType.none;
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      if (this.exportModal) {
        this.exportModal.close(true);
      }
    }
  }, {
    key: "handleButtonCreate",
    value: function handleButtonCreate() {
      var dataSet = this.context.dataSet;
      dataSet.create({}, 0);
    }
  }, {
    key: "handleButtonSubmit",
    value: function handleButtonSubmit() {
      var dataSet = this.context.dataSet;
      return dataSet.submit();
    }
  }, {
    key: "handleButtonDelete",
    value: function handleButtonDelete() {
      var dataSet = this.context.dataSet;
      return dataSet["delete"](dataSet.selected);
    }
  }, {
    key: "handleButtonRemove",
    value: function handleButtonRemove() {
      var dataSet = this.context.dataSet;
      dataSet.remove(dataSet.selected);
    }
  }, {
    key: "handleButtonReset",
    value: function handleButtonReset() {
      var dataSet = this.context.dataSet;
      dataSet.reset();
    }
  }, {
    key: "handleQueryReset",
    value: function handleQueryReset() {
      var queryDataSet = this.context.dataSet.queryDataSet;

      if (queryDataSet) {
        var current = queryDataSet.current;

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

        this.handleQuery();
      }
    }
  }, {
    key: "handleExpandAll",
    value: function handleExpandAll() {
      var tableStore = this.context.tableStore;
      tableStore.expandAll();
    }
  }, {
    key: "handleCollapseAll",
    value: function handleCollapseAll() {
      var tableStore = this.context.tableStore;
      tableStore.collapseAll();
    }
  }, {
    key: "handleChangeExportStrategy",
    value: function handleChangeExportStrategy(value) {
      var dataSet = this.context.dataSet;
      dataSet.setState('__EXPORT-STRATEGY__', value);
    }
  }, {
    key: "handleButtonExport",
    value: function () {
      var _handleButtonExport = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var _this2 = this;

        var _this$context, tableStore, prefixCls, getConfig, columnHeaders;

        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _this$context = this.context, tableStore = _this$context.tableStore, prefixCls = _this$context.prefixCls, getConfig = _this$context.tableStore.getConfig;
                _context.next = 3;
                return tableStore.getColumnHeaders();

              case 3:
                columnHeaders = _context.sent;
                this.exportDataSet = new DataSet({
                  data: columnHeaders,
                  paging: false
                }, {
                  getConfig: getConfig
                });
                this.exportDataSet.selectAll();
                this.handleChangeExportStrategy('ALL');
                this.exportModal = Modal.open({
                  title: $l('Table', 'choose_export_columns'),
                  children: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Table, {
                    dataSet: this.exportDataSet,
                    style: {
                      height: pxToRem(300)
                    }
                  }, /*#__PURE__*/React.createElement(Column, {
                    header: $l('Table', 'column_name'),
                    name: "label",
                    resizable: false
                  }))),
                  closable: true,
                  okText: $l('Table', 'export_button'),
                  onOk: this.handleExport,
                  footer: function footer(okBtn, cancelBtn) {
                    return /*#__PURE__*/React.createElement("div", {
                      className: "".concat(prefixCls, "-export-modal-footer")
                    }, /*#__PURE__*/React.createElement("div", {
                      className: "".concat(prefixCls, "-export-modal-footer-radio")
                    }, /*#__PURE__*/React.createElement(Radio, {
                      name: "exportStrategy",
                      value: "ALL",
                      defaultChecked: true,
                      onChange: _this2.handleChangeExportStrategy
                    }, $l('Table', 'export_all')), /*#__PURE__*/React.createElement(Radio, {
                      name: "exportStrategy",
                      value: "SELECTED",
                      onChange: _this2.handleChangeExportStrategy
                    }, $l('Table', 'export_selected'))), /*#__PURE__*/React.createElement("div", null, okBtn, cancelBtn));
                  },
                  style: {
                    width: pxToRem(500)
                  }
                });

              case 8:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function handleButtonExport() {
        return _handleButtonExport.apply(this, arguments);
      }

      return handleButtonExport;
    }()
  }, {
    key: "handleQuery",
    value: function () {
      var _handleQuery = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
        var _this$context2, tableStore, dataSet, queryDataSet;

        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _this$context2 = this.context, tableStore = _this$context2.tableStore, dataSet = _this$context2.dataSet, queryDataSet = _this$context2.dataSet.queryDataSet;

                if (!(tableStore.queryBar === TableQueryBarType.filterBar)) {
                  _context2.next = 19;
                  break;
                }

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

              case 4:
                _context2.t2 = _context2.sent;

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

                _context2.t2 = queryDataSet;

              case 7:
                _context2.t1 = _context2.t2;

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

                _context2.t1 = queryDataSet.current;

              case 10:
                _context2.t0 = _context2.t1;

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

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

              case 14:
                _context2.t0 = _context2.sent;

              case 15:
                if (!_context2.t0) {
                  _context2.next = 17;
                  break;
                }

                return _context2.abrupt("return", dataSet.query());

              case 17:
                _context2.next = 20;
                break;

              case 19:
                return _context2.abrupt("return", dataSet.query());

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

      function handleQuery() {
        return _handleQuery.apply(this, arguments);
      }

      return handleQuery;
    }()
  }, {
    key: "handleExport",
    value: function handleExport() {
      var _this3 = this;

      var selected = this.exportDataSet.selected;
      var clientExportQuantity = this.props.clientExportQuantity,
          _this$context3 = this.context,
          prefixCls = _this$context3.prefixCls,
          dataSet = _this$context3.dataSet;

      if (selected.length) {
        var exportModal = this.exportModal;
        dataSet["export"](selected.reduce(function (columns, record) {
          var myName = record.get('name');
          var myField = dataSet.getField(myName);

          if (myField && myField.type === FieldType.object) {
            var bindField = findBindFieldBy(myField, dataSet.fields, 'textField');

            if (bindField) {
              myName = bindField.name;
            }
          }

          columns[myName] = record.get('label');
          return columns;
        }, {}), clientExportQuantity).then(function (exportData) {
          _this3.exportData = exportData;
        });

        if (exportModal) {
          exportModal.update({
            title: $l('Table', 'export_button'),
            children: /*#__PURE__*/React.createElement(ExportBody, {
              prefixCls: prefixCls,
              dataSet: dataSet
            }),
            onCancel: this.handleExportButton,
            footer: /*#__PURE__*/React.createElement(ExportFooter, {
              prefixCls: prefixCls,
              exportButton: this.handleExportButton,
              exportModal: exportModal,
              dataSet: dataSet
            })
          });
        }
      }

      return false;
    }
  }, {
    key: "handleExportButton",
    value: function handleExportButton(data, filename) {
      var _this$context4 = this.context,
          dataSet = _this$context4.dataSet,
          tableStore = _this$context4.tableStore;

      if (data === DataSetExportStatus.success) {
        if (this.exportData) {
          exportExcel(this.exportData, filename, tableStore.getConfig('xlsx'));
          this.exportModal.close();
          this.exportData = null;
        }
      } else if (data === DataSetExportStatus.failed) {
        this.exportData = null;
        this.handleExport();
      } else {
        this.exportModal.close();
        this.exportData = null;
      }

      dataSet.exportStatus = undefined;
    }
  }, {
    key: "getButtonProps",
    value: function getButtonProps(type) {
      var _this$context5 = this.context,
          isTree = _this$context5.isTree,
          dataSet = _this$context5.dataSet;
      var disabled = dataSet.status !== DataSetStatus.ready;

      switch (type) {
        case TableButtonType.add:
          return {
            icon: 'playlist_add',
            onClick: this.handleButtonCreate,
            children: $l('Table', 'create_button'),
            disabled: disabled || (dataSet.parent ? !dataSet.parent.current : false)
          };

        case TableButtonType.save:
          return {
            icon: 'save',
            onClick: this.handleButtonSubmit,
            children: $l('Table', 'save_button'),
            type: ButtonType.submit,
            disabled: disabled
          };

        case TableButtonType["delete"]:
          return {
            icon: 'delete',
            onClick: this.handleButtonDelete,
            children: $l('Table', 'delete_button'),
            disabled: disabled || dataSet.selected.length === 0
          };

        case TableButtonType.remove:
          return {
            icon: 'remove_circle',
            onClick: this.handleButtonRemove,
            children: $l('Table', 'remove_button'),
            disabled: disabled || dataSet.selected.length === 0
          };

        case TableButtonType.reset:
          return {
            icon: 'undo',
            onClick: this.handleButtonReset,
            children: $l('Table', 'reset_button'),
            type: ButtonType.reset
          };

        case TableButtonType.query:
          return {
            icon: 'search',
            onClick: this.handleQuery,
            children: $l('Table', 'query_button')
          };

        case TableButtonType["export"]:
          return {
            icon: 'export',
            onClick: this.handleButtonExport,
            children: $l('Table', 'export_button')
          };

        case TableButtonType.expandAll:
          return isTree ? {
            icon: 'add_box',
            onClick: this.handleExpandAll,
            children: $l('Table', 'expand_button')
          } : undefined;

        case TableButtonType.collapseAll:
          return isTree ? {
            icon: 'short_text',
            onClick: this.handleCollapseAll,
            children: $l('Table', 'collapse_button')
          } : undefined;

        default:
      }
    }
    /**
     * 渲染表头汇总列
     * @param summary
     */

  }, {
    key: "renderSummary",
    value: function renderSummary(summary) {
      if (summary) {
        var length = summary.length;

        if (length) {
          var summaryBar = this.props.summaryBar;

          if (summaryBar) {
            var summaryLength = summaryBar.length;
            var _this$props = this.props,
                summaryFieldsLimit = _this$props.summaryFieldsLimit,
                summaryBarFieldWidth = _this$props.summaryBarFieldWidth,
                _this$context6 = this.context,
                tableStore = _this$context6.tableStore,
                dataSet = _this$context6.dataSet,
                prefixCls = _this$context6.prefixCls;
            var queryBarProps = tableStore.props.queryBarProps;

            var tableQueryBarProps = _objectSpread(_objectSpread({}, tableStore.getConfig('queryBarProps')), queryBarProps);

            var summaryFieldsLimits = summaryFieldsLimit || tableQueryBarProps && tableQueryBarProps.summaryFieldsLimit || 3;
            var fieldTypeArr = [FieldType.currency, FieldType.number];
            return summary.reduce(function (list, summaryCol, index) {
              var hasSeparate = length > summaryFieldsLimits || index !== summaryLength - 1;

              if (isString(summaryCol)) {
                var field = dataSet.getField(summaryCol);

                if (field && fieldTypeArr.includes(field.get('type'))) {
                  var summaryValue = dataSet.reduce(function (sum, record) {
                    var n = record.get(summaryCol);

                    if (isNumber(n) || math.isBigNumber(n)) {
                      return math.plus(sum, n);
                    }

                    return sum;
                  }, 0);
                  var name = field.get('name');
                  var label = field.get('label');
                  var sumNode = math.isBigNumber(summaryValue) ? math.toString(summaryValue) : summaryValue;
                  list.push( /*#__PURE__*/React.createElement("div", {
                    key: name
                  }, /*#__PURE__*/React.createElement("div", {
                    className: "".concat(prefixCls, "-summary-col"),
                    style: {
                      width: summaryBarFieldWidth
                    }
                  }, /*#__PURE__*/React.createElement("div", {
                    className: "".concat(prefixCls, "-summary-col-label"),
                    title: String(label)
                  }, label, ":"), /*#__PURE__*/React.createElement("div", {
                    className: "".concat(prefixCls, "-summary-col-value"),
                    title: String(sumNode)
                  }, sumNode)), hasSeparate && /*#__PURE__*/React.createElement("div", {
                    className: "".concat(prefixCls, "-summary-col-separate")
                  }, /*#__PURE__*/React.createElement("div", null))));
                }
              } else if (typeof summaryCol === 'function') {
                var summaryObj = summaryCol({
                  summaryFieldsLimit: summaryFieldsLimits,
                  summaryBarFieldWidth: summaryBarFieldWidth,
                  dataSet: dataSet
                });
                list.push( /*#__PURE__*/React.createElement("div", {
                  key: isString(summaryObj.label) ? summaryObj.label : ''
                }, /*#__PURE__*/React.createElement("div", {
                  className: "".concat(prefixCls, "-summary-col"),
                  style: {
                    width: summaryBarFieldWidth
                  }
                }, /*#__PURE__*/React.createElement("div", {
                  className: "".concat(prefixCls, "-summary-col-label"),
                  title: isString(summaryObj.label) ? summaryObj.label : ''
                }, summaryObj.label, ":"), /*#__PURE__*/React.createElement("div", {
                  className: "".concat(prefixCls, "-summary-col-value"),
                  title: isString(summaryObj.value) || isNumber(summaryObj.value) ? summaryObj.value.toString() : ''
                }, summaryObj.value)), hasSeparate && /*#__PURE__*/React.createElement("div", {
                  className: "".concat(prefixCls, "-summary-col-separate")
                }, /*#__PURE__*/React.createElement("div", null))));
              }

              return list;
            }, []);
          }
        }
      }
    }
    /**
     * 汇总条展开收起按钮
     * @param summary
     */

  }, {
    key: "getMoreSummaryButton",
    value: function getMoreSummaryButton(summary) {
      var _this4 = this;

      if (summary.length) {
        var prefixCls = this.context.prefixCls;
        return /*#__PURE__*/React.createElement("div", {
          className: "".concat(prefixCls, "-summary-button-more")
        }, /*#__PURE__*/React.createElement("a", {
          onClick: function onClick() {
            return _this4.openMore(summary);
          }
        }, $l('Table', 'more'), this.moreSummary && this.moreSummary.length ? /*#__PURE__*/React.createElement(Icon, {
          type: 'expand_less'
        }) : /*#__PURE__*/React.createElement(Icon, {
          type: 'expand_more'
        })));
      }
    }
    /**
     * 渲染汇总条
     */

  }, {
    key: "getSummaryBar",
    value: function getSummaryBar() {
      var _this$props2 = this.props,
          summaryBar = _this$props2.summaryBar,
          summaryFieldsLimit = _this$props2.summaryFieldsLimit,
          _this$context7 = this.context,
          prefixCls = _this$context7.prefixCls,
          tableStore = _this$context7.tableStore;
      var queryBarProps = tableStore.props.queryBarProps;

      var tableQueryBarProps = _objectSpread(_objectSpread({}, tableStore.getConfig('queryBarProps')), queryBarProps);

      var summaryFieldsLimits = summaryFieldsLimit || tableQueryBarProps && tableQueryBarProps.summaryFieldsLimit || 3;

      if (summaryBar) {
        var currentSummaryBar = this.renderSummary(summaryBar.slice(0, summaryFieldsLimits));
        var moreSummary = summaryBar.slice(summaryFieldsLimits);
        var moreSummaryButton = this.getMoreSummaryButton(moreSummary);
        return /*#__PURE__*/React.createElement("div", {
          className: "".concat(prefixCls, "-summary-group-wrapper")
        }, /*#__PURE__*/React.createElement("div", {
          className: "".concat(prefixCls, "-summary-group")
        }, currentSummaryBar, this.moreSummary), moreSummaryButton);
      }
    }
    /**
     * buttons 大于 buttonsLimits 放入下拉
     * @param buttonsLimits
     * @param hasCombineSort
     */

  }, {
    key: "getMoreButton",
    value: function getMoreButton(buttonsLimits, hasCombineSort) {
      var _this5 = this;

      var buttons = this.props.buttons;
      var _this$context8 = this.context,
          prefixCls = _this$context8.prefixCls,
          tableStore = _this$context8.tableStore;
      var tableButtonProps = tableStore.getConfig('tableButtonProps');
      var children = [];

      if (buttons && buttons.length && buttonsLimits) {
        buttons.slice(hasCombineSort ? buttonsLimits - 1 : buttonsLimits).forEach(function (button) {
          var props = {};

          if (isArrayLike(button)) {
            props = button[1] || {};
            button = button[0];
          }

          if (isString(button) && button in TableButtonType) {
            var _props = props,
                afterClick = _props.afterClick,
                buttonProps = _objectWithoutProperties(_props, _excluded);

            var defaultButtonProps = _this5.getButtonProps(button);

            if (defaultButtonProps) {
              if (afterClick) {
                var onClick = defaultButtonProps.onClick;

                defaultButtonProps.onClick = /*#__PURE__*/function () {
                  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(e) {
                    return _regeneratorRuntime.wrap(function _callee3$(_context3) {
                      while (1) {
                        switch (_context3.prev = _context3.next) {
                          case 0:
                            e.persist();
                            _context3.prev = 1;
                            _context3.next = 4;
                            return onClick(e);

                          case 4:
                            _context3.prev = 4;
                            afterClick(e);
                            return _context3.finish(4);

                          case 7:
                          case "end":
                            return _context3.stop();
                        }
                      }
                    }, _callee3, null, [[1,, 4, 7]]);
                  }));

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

              children.push( /*#__PURE__*/React.createElement(Menu.Item, {
                hidden: tableButtonProps.hidden,
                key: button
              }, /*#__PURE__*/React.createElement(Button, _extends({
                key: "".concat(button, "-btn")
              }, tableButtonProps, defaultButtonProps, buttonProps, {
                funcType: FuncType.link
              }))));
            }
          } else if ( /*#__PURE__*/isValidElement(button)) {
            children.push( /*#__PURE__*/React.createElement(Menu.Item, {
              hidden: button.props.hidden,
              key: button.key
            }, /*#__PURE__*/cloneElement(button, _objectSpread(_objectSpread(_objectSpread({}, tableButtonProps), button.props), {}, {
              funcType: FuncType.link
            }))));
          } else if (isObject(button)) {
            children.push( /*#__PURE__*/React.createElement(Menu.Item, {
              hidden: props.hidden,
              key: button.key
            }, /*#__PURE__*/React.createElement(Button, _extends({}, tableButtonProps, button, {
              funcType: FuncType.link
            }))));
          }
        });
      }

      var menu = /*#__PURE__*/React.createElement(Menu, {
        prefixCls: "".concat(prefixCls, "-dropdown-menu")
      }, children);
      return /*#__PURE__*/React.createElement(Dropdown, {
        overlay: menu,
        key: "dropdown_button"
      }, /*#__PURE__*/React.createElement(Button, _extends({}, tableButtonProps, {
        key: "more_button"
      }), /*#__PURE__*/React.createElement("span", null, $l('Table', 'more')), /*#__PURE__*/React.createElement(Icon, {
        type: 'expand_more'
      })));
    }
  }, {
    key: "getButtons",
    value: function getButtons() {
      var _this6 = this;

      var _this$context$tableSt = this.context.tableStore,
          queryBar = _this$context$tableSt.queryBar,
          prefixCls = _this$context$tableSt.prefixCls,
          dataSet = _this$context$tableSt.dataSet,
          customizedBtn = _this$context$tableSt.customizedBtn,
          customizable = _this$context$tableSt.customizable,
          customizedColumnHeader = _this$context$tableSt.customizedColumnHeader;
      var _this$props3 = this.props,
          originalButtons = _this$props3.buttons,
          summaryBar = _this$props3.summaryBar,
          buttonsLimit = _this$props3.buttonsLimit;
      var tableStore = this.context.tableStore;
      var children = [];
      var buttons = originalButtons;

      if (customizable && customizedBtn) {
        buttons = [customizedColumnHeader()].concat(_toConsumableArray(buttons || []));
      }

      var hasCombineSort = queryBar !== TableQueryBarType.filterBar && dataSet.props.combineSort;

      if (hasCombineSort) {
        var sortableFieldNames = this.getSortableFieldNames();

        if (sortableFieldNames.length > 0) {
          buttons = [/*#__PURE__*/React.createElement(CombineSort, {
            key: "CombineSort",
            dataSet: dataSet,
            prefixCls: prefixCls,
            sortableFieldNames: sortableFieldNames
          })].concat(_toConsumableArray(buttons || []));
        }
      }

      if (buttons) {
        // 汇总条存在下 buttons 大于 3 个放入下拉
        var buttonsLimits = summaryBar ? buttonsLimit || 3 : buttonsLimit;
        var tableButtonProps = tableStore.getConfig('tableButtonProps');
        var buttonsArr = buttons.slice(0, buttonsLimits);
        buttonsArr.forEach(function (button) {
          var props = {};

          if (isArrayLike(button)) {
            props = button[1] || {};
            button = button[0];
          }

          if (isString(button) && button in TableButtonType) {
            var _props2 = props,
                afterClick = _props2.afterClick,
                buttonProps = _objectWithoutProperties(_props2, _excluded2);

            var defaultButtonProps = _this6.getButtonProps(button);

            if (defaultButtonProps) {
              if (afterClick) {
                var onClick = defaultButtonProps.onClick;

                defaultButtonProps.onClick = /*#__PURE__*/function () {
                  var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(e) {
                    return _regeneratorRuntime.wrap(function _callee4$(_context4) {
                      while (1) {
                        switch (_context4.prev = _context4.next) {
                          case 0:
                            e.persist();
                            _context4.prev = 1;
                            _context4.next = 4;
                            return onClick(e);

                          case 4:
                            _context4.prev = 4;
                            afterClick(e);
                            return _context4.finish(4);

                          case 7:
                          case "end":
                            return _context4.stop();
                        }
                      }
                    }, _callee4, null, [[1,, 4, 7]]);
                  }));

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

              children.push( /*#__PURE__*/React.createElement(Button, _extends({
                key: button
              }, tableButtonProps, defaultButtonProps, buttonProps)));
            }
          } else if ( /*#__PURE__*/isValidElement(button)) {
            children.push( /*#__PURE__*/cloneElement(button, _objectSpread(_objectSpread({}, tableButtonProps), button.props)));
          } else if (isObject(button)) {
            children.push( /*#__PURE__*/React.createElement(Button, _extends({}, tableButtonProps, button)));
          }
        });

        if (buttonsLimits && buttons.length > buttonsLimits) {
          var moreButton = this.getMoreButton(buttonsLimits, hasCombineSort);
          children.push(moreButton);
        }
      }

      return children;
    }
  }, {
    key: "getQueryFields",
    value: function getQueryFields() {
      var _this$context9 = this.context,
          dataSet = _this$context9.dataSet,
          _this$context9$tableS = _this$context9.tableStore,
          queryBar = _this$context9$tableS.queryBar,
          getConfig = _this$context9$tableS.getConfig,
          _this$props4 = this.props,
          queryFields = _this$props4.queryFields,
          buttons = _this$props4.buttons;
      var queryDataSet = dataSet.queryDataSet;
      var result = [];

      if (queryDataSet) {
        var fields = queryDataSet.fields,
            current = queryDataSet.current,
            _queryDataSet$props$f = queryDataSet.props.fields,
            propFields = _queryDataSet$props$f === void 0 ? [] : _queryDataSet$props$f; // 减少重复渲染
        // 使用了 buttons 判断，是因为 getButtons 中有用 DataSet.status 可观察对象判断，确保 buttons 用到 status 时，此处才用 status 判断，减少渲染

        if (this.queryFieldsElement.length && (!current || buttons && buttons.some(function (button) {
          return isString(button) && button in TableButtonType;
        }) && dataSet.status !== DataSetStatus.ready)) return this.queryFieldsElement;
        var cloneFields = fields.toJS();
        var tlsKey = getConfig('tlsKey');

        var processField = function processField(field, name) {
          if (!field.get('bind', current) && !name.includes(tlsKey)) {
            var element = queryFields[name];
            var filterBarProps = {};

            if (queryBar === TableQueryBarType.filterBar) {
              var placeholder = /*#__PURE__*/isValidElement(element) && element.props.placeholder ? element.props.placeholder : getPlaceholderByField(field, current);
              filterBarProps = {
                placeholder: placeholder,
                border: false,
                clearButton: true
              };
            }

            var props = _objectSpread({
              key: name,
              name: name,
              dataSet: queryDataSet,
              isFlat: queryBar === TableQueryBarType.filterBar
            }, filterBarProps);

            result.push( /*#__PURE__*/isValidElement(element) ? /*#__PURE__*/cloneElement(element, props) : /*#__PURE__*/cloneElement(getEditorByField(field, current, queryBar !== TableQueryBarType.professionalBar, queryBar === TableQueryBarType.filterBar || queryBar === TableQueryBarType.comboBar), _objectSpread(_objectSpread({}, props), isObject(element) ? element : {})));
          }
        };

        propFields.forEach(function (_ref3) {
          var name = _ref3.name;

          if (name) {
            var field = cloneFields.get(name);

            if (field) {
              cloneFields["delete"](name);
              processField(field, name);
            }
          }
        });
        cloneFields.forEach(function (field, name) {
          processField(field, name);
        });
      }

      this.queryFieldsElement = result;
      return result;
    }
  }, {
    key: "getSortableFieldNames",
    value: function getSortableFieldNames() {
      var columnGroups = this.context.tableStore.columnGroups;
      var columns = columnGroups.columns;
      var headerRows = getTableHeaderRows(columns);
      var sortableFieldNames = new Set();
      headerRows.forEach(function (cols) {
        cols.forEach(function (col) {
          if (col.column && col.column.name && col.column.sortable) {
            sortableFieldNames.add(col.column.name);
          }
        });
      });
      return _toConsumableArray(sortableFieldNames);
    }
  }, {
    key: "renderToolBar",
    value: function renderToolBar(props) {
      var prefixCls = this.context.prefixCls;
      return /*#__PURE__*/React.createElement(TableToolBar, _extends({
        key: "toolbar",
        prefixCls: prefixCls
      }, props));
    }
  }, {
    key: "renderFilterBar",
    value: function renderFilterBar(props) {
      var prefixCls = this.context.prefixCls;
      var _this$props5 = this.props,
          filterBarFieldName = _this$props5.filterBarFieldName,
          filterBarPlaceholder = _this$props5.filterBarPlaceholder;
      return /*#__PURE__*/React.createElement(TableFilterBar, _extends({
        key: "toolbar",
        prefixCls: prefixCls,
        paramName: filterBarFieldName,
        placeholder: filterBarPlaceholder
      }, props));
    }
  }, {
    key: "renderAdvancedQueryBar",
    value: function renderAdvancedQueryBar(props) {
      var prefixCls = this.context.prefixCls;
      return /*#__PURE__*/React.createElement(TableAdvancedQueryBar, _extends({
        key: "toolbar",
        prefixCls: prefixCls
      }, props));
    }
  }, {
    key: "renderProfessionalBar",
    value: function renderProfessionalBar(props) {
      var prefixCls = this.context.prefixCls;
      return /*#__PURE__*/React.createElement(TableProfessionalBar, _extends({
        key: "toolbar",
        prefixCls: prefixCls
      }, props));
    }
  }, {
    key: "renderDynamicFilterBar",
    value: function renderDynamicFilterBar(props) {
      var _this$props6 = this.props,
          dynamicFilterBar = _this$props6.dynamicFilterBar,
          searchCode = _this$props6.searchCode;
      var _this$context10 = this.context,
          prefixCls = _this$context10.prefixCls,
          tableStore = _this$context10.tableStore;
      var sortableFieldNames = this.getSortableFieldNames();
      return /*#__PURE__*/React.createElement(TableDynamicFilterBar, _extends({
        key: "toolbar",
        searchCode: searchCode,
        dynamicFilterBar: dynamicFilterBar,
        prefixCls: prefixCls,
        sortableFieldNames: sortableFieldNames,
        tableStore: tableStore
      }, props));
    }
  }, {
    key: "renderComboBar",
    value: function renderComboBar(props) {
      var comboFilterBar = this.props.comboFilterBar;
      var prefixCls = this.context.prefixCls;
      return /*#__PURE__*/React.createElement(TableComboBar, _extends({
        key: "toolbar",
        comboFilterBar: comboFilterBar,
        prefixCls: prefixCls
      }, props));
    }
  }, {
    key: "expandTree",
    value: function expandTree() {
      var tableStore = this.context.tableStore;
      var queryBarProps = tableStore.props.queryBarProps;

      if (queryBarProps && typeof queryBarProps.onQuery === 'function') {
        queryBarProps.onQuery();
      }

      tableStore.expandAll();
    }
  }, {
    key: "collapseTree",
    value: function collapseTree() {
      var tableStore = this.context.tableStore;
      var queryBarProps = tableStore.props.queryBarProps;

      if (queryBarProps && typeof queryBarProps.onReset === 'function') {
        queryBarProps.onReset();
      }

      tableStore.collapseAll();
    }
  }, {
    key: "render",
    value: function render() {
      var buttons = this.getButtons();
      var summaryBar = this.getSummaryBar();
      var _this$context11 = this.context,
          prefixCls = _this$context11.prefixCls,
          dataSet = _this$context11.dataSet,
          isTree = _this$context11.isTree,
          tableStore = _this$context11.tableStore,
          _this$context11$table = _this$context11.tableStore,
          queryBar = _this$context11$table.queryBar,
          queryBarProps = _this$context11$table.props.queryBarProps,
          _this$props7 = this.props,
          queryFieldsLimit = _this$props7.queryFieldsLimit,
          summaryFieldsLimit = _this$props7.summaryFieldsLimit,
          pagination = _this$props7.pagination,
          treeQueryExpanded = _this$props7.treeQueryExpanded,
          showQueryBar = this.showQueryBar;

      if (showQueryBar) {
        var queryDataSet = dataSet.queryDataSet;
        var queryFields = this.getQueryFields();

        var tableQueryBarProps = _objectSpread(_objectSpread({}, tableStore.getConfig('queryBarProps')), queryBarProps);

        var onReset = typeof tableQueryBarProps.onReset === 'function' ? tableQueryBarProps.onReset : noop;
        var onQuery = typeof tableQueryBarProps.onQuery === 'function' ? tableQueryBarProps.onQuery : noop;
        var queryFieldsLimits = queryFieldsLimit || tableQueryBarProps.queryFieldsLimit;
        var summaryFieldsLimits = summaryFieldsLimit || tableQueryBarProps.summaryFieldsLimit || 3;

        var props = _objectSpread(_objectSpread({}, tableQueryBarProps), {}, {
          dataSet: dataSet,
          queryDataSet: queryDataSet,
          buttons: buttons,
          pagination: pagination,
          queryFields: queryFields,
          queryFieldsLimit: queryFieldsLimits,
          summaryFieldsLimit: summaryFieldsLimits,
          summaryBar: summaryBar,
          onQuery: treeQueryExpanded && isTree ? this.expandTree : onQuery,
          onReset: treeQueryExpanded && isTree ? this.collapseTree : onReset
        });

        if (typeof queryBar === 'function') {
          return queryBar(props);
        }

        switch (queryBar) {
          case TableQueryBarType.normal:
            return this.renderToolBar(props);

          case TableQueryBarType.bar:
            return this.renderFilterBar(props);

          case TableQueryBarType.advancedBar:
            return this.renderAdvancedQueryBar(props);

          case TableQueryBarType.professionalBar:
            return this.renderProfessionalBar(props);

          case TableQueryBarType.filterBar:
            return this.renderDynamicFilterBar(props);

          case TableQueryBarType.comboBar:
            return this.renderComboBar(props);

          default:
        }
      }

      return [/*#__PURE__*/React.createElement(TableButtons, {
        key: "toolbar",
        prefixCls: prefixCls,
        buttons: buttons
      }, summaryBar), pagination];
    }
  }], [{
    key: "contextType",
    get: function get() {
      return TableContext;
    }
  }]);

  return TableQueryBar;
}(Component);

TableQueryBar.displayName = 'TableQueryBar';
TableQueryBar.defaultProps = {
  summaryBarFieldWidth: 170
};

__decorate([observable], TableQueryBar.prototype, "moreSummary", void 0);

__decorate([autobind], TableQueryBar.prototype, "handleButtonCreate", null);

__decorate([autobind], TableQueryBar.prototype, "handleButtonSubmit", null);

__decorate([autobind], TableQueryBar.prototype, "handleButtonDelete", null);

__decorate([autobind], TableQueryBar.prototype, "handleButtonRemove", null);

__decorate([autobind], TableQueryBar.prototype, "handleButtonReset", null);

__decorate([autobind], TableQueryBar.prototype, "handleQueryReset", null);

__decorate([autobind], TableQueryBar.prototype, "handleExpandAll", null);

__decorate([autobind], TableQueryBar.prototype, "handleCollapseAll", null);

__decorate([autobind], TableQueryBar.prototype, "handleChangeExportStrategy", null);

__decorate([autobind], TableQueryBar.prototype, "handleButtonExport", null);

__decorate([autobind], TableQueryBar.prototype, "handleQuery", null);

__decorate([autobind], TableQueryBar.prototype, "handleExport", null);

__decorate([autobind, action], TableQueryBar.prototype, "handleExportButton", null);

__decorate([action], TableQueryBar.prototype, "openMore", void 0);

__decorate([autobind], TableQueryBar.prototype, "expandTree", null);

__decorate([autobind], TableQueryBar.prototype, "collapseTree", null);

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