import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
var _excluded = ["afterClick"],
    _excluded2 = ["afterClick"];
import _regeneratorRuntime from "@babel/runtime/regenerator";
import React, { isValidElement, useCallback, useContext, useEffect, useState, cloneElement, useMemo } from 'react';
import classnames from 'classnames';
import { observer } from 'mobx-react-lite';
import { DragDropContext } from 'react-beautiful-dnd';
import { isArrayLike } from 'mobx';
import isString from 'lodash/isString';
import noop from 'lodash/noop';
import isObject from 'lodash/isObject';
import isFunction from 'lodash/isFunction';
import uniqWith from 'lodash/uniqWith';
import isEqual from 'lodash/isEqual';
import Icon from '../../../es/icon';
import { Row } from '../../../es/grid';
import DataSet from '../data-set';
import KanbanColumn from './KanbanColumn';
import BoardContext from './BoardContext';
import TableDynamicFilterBar from '../table/query-bar/TableDynamicFilterBar';
import { getEditorByField, getPlaceholderByField } from '../table/utils';
import Button from '../button/Button';
import { ButtonColor, ButtonType, FuncType } from '../button/enum';
import { useModal } from '../modal-provider/ModalProvider';
import { $l } from '../locale-context';
import KanbanCustomizationSettings from './kanban-customization-settings';
import { ViewField, ViewMode } from './enum';
import { TableButtonType } from '../table/interface';
import { DataSetStatus } from '../data-set/interface';
import Dropdown from '../dropdown/Dropdown';
import Menu from '../menu';

var KanbanContent = function KanbanContent(props) {
  var dataSet = props.dataSet,
      buttons = props.buttons,
      _props$kanbanProps = props.kanbanProps,
      kanbanProps = _props$kanbanProps === void 0 ? {} : _props$kanbanProps,
      tableBtns = props.tableBtns,
      buttonsLimit = props.buttonsLimit,
      queryBarProps = props.queryBarProps;

  var _useContext = useContext(BoardContext),
      onChange = _useContext.onChange,
      getConfig = _useContext.getConfig,
      getProPrefixCls = _useContext.getProPrefixCls,
      _useContext$prefixCls = _useContext.prefixCls,
      prefixCls = _useContext$prefixCls === void 0 ? '' : _useContext$prefixCls,
      customizedDS = _useContext.customizedDS,
      queryFields = _useContext.queryFields,
      autoQuery = _useContext.autoQuery,
      _useContext$renderBut = _useContext.renderButtons,
      renderButtons = _useContext$renderBut === void 0 ? noop : _useContext$renderBut;

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      loaded = _useState2[0],
      setLoaded = _useState2[1];

  var _useState3 = useState(),
      _useState4 = _slicedToArray(_useState3, 2),
      columnData = _useState4[0],
      setColumnData = _useState4[1];

  var groupField = customizedDS.current.get(ViewField.groupField);
  var viewProps = customizedDS.current.get(ViewField.viewProps);
  var dataKey = kanbanProps.columnDsProps ? kanbanProps.columnDsProps.dataKey || getConfig('dataKey') : getConfig('dataKey');
  var totalKey = kanbanProps.columnDsProps ? kanbanProps.columnDsProps.totalKey || getConfig('totalKey') : getConfig('dataKey');
  var dsField = useMemo(function () {
    return dataSet.fields.get(groupField);
  }, [dataSet, groupField]);
  var modal = useModal();
  var openCustomizationModal = useCallback(function () {
    var modalProps = {
      drawer: true,
      title: '看板视图配置',
      children: /*#__PURE__*/React.createElement(KanbanCustomizationSettings, {
        viewMode: ViewMode.kanban
      }),
      bodyStyle: {
        overflow: 'hidden auto',
        padding: 0
      }
    };
    modalProps.okText = $l('Tabs', 'save');
    modal.open(modalProps);
  }, [modal]);
  var kanbanDS = useMemo(function () {
    var defaultSortParams = dataSet.combineSort && viewProps ? viewProps[ViewField.combineSort] || [] : [];
    var orgFields = dataSet.props.fields ? dataSet.props.fields : [];
    var orderFields = orgFields.map(function (field) {
      var orderField = defaultSortParams.find(function (of) {
        return of.sortName === field.name;
      });

      var newField = _objectSpread({}, field);

      if (orderField) {
        newField.order = orderField.order;
      }

      return newField;
    });
    return new DataSet(_objectSpread(_objectSpread(_objectSpread({}, dataSet.props), {}, {
      dataKey: 'null',
      fields: orderFields
    }, kanbanProps.allDsProps), {}, {
      autoQuery: false
    }));
  }, []);
  var loadColumnData = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var res, changed, _res, _changed;

    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            setLoaded(false);

            if (!(dsField && dsField.getOptions() && dsField.getOptions().toData().length)) {
              _context.next = 15;
              break;
            }

            res = _toConsumableArray(dsField.getOptions().toData());
            res.unshift({});
            setColumnData(uniqWith(res, isEqual));
            kanbanDS.setQueryParameter('groupingBy', dsField.name);
            dataSet.setState('__CURRENTVIEWDS__', kanbanDS);
            changed = customizedDS && customizedDS.getState('__ISCHANGE__');

            if (isFunction(onChange) && changed) {
              onChange({
                dataSet: dataSet,
                currentViewDS: kanbanDS,
                record: customizedDS.current
              });
            }

            if (!autoQuery) {
              _context.next = 12;
              break;
            }

            _context.next = 12;
            return kanbanDS.query();

          case 12:
            setLoaded(true);
            _context.next = 34;
            break;

          case 15:
            if (!dsField) {
              _context.next = 34;
              break;
            }

            _context.prev = 16;
            _context.next = 19;
            return dsField.fetchLookup(true);

          case 19:
            _res = _context.sent;

            if (!(_res && _res.length)) {
              _context.next = 31;
              break;
            }

            _res.unshift({});

            setColumnData(uniqWith(_res, isEqual));
            kanbanDS.setQueryParameter('groupingBy', dsField.name);
            dataSet.setState('__CURRENTVIEWDS__', kanbanDS);
            _changed = customizedDS && customizedDS.getState('__ISCHANGE__');

            if (isFunction(onChange) && _changed) {
              onChange({
                dataSet: dataSet,
                currentViewDS: kanbanDS,
                record: customizedDS.current
              });
            }

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

            _context.next = 30;
            return kanbanDS.query();

          case 30:
            setLoaded(true);

          case 31:
            _context.prev = 31;
            setLoaded(true);
            return _context.finish(31);

          case 34:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[16,, 31, 34]]);
  })), [dsField, dataSet]);
  useEffect(function () {
    loadColumnData();
  }, [dataSet, customizedDS.current, groupField, kanbanProps]);
  /**
   * 根据列数据渲染列组件
   * @returns 看板列组件
   */

  var getBoardColumns = useCallback(function () {
    if (dsField && columnData && loaded) {
      var groupFieldName = dsField.get('name');
      var groupValueField = dsField.get('valueField');
      var groupTextField = dsField.get('textField');
      return columnData.map(function (groupRecord) {
        var groupValue = groupRecord[groupValueField];
        var groupText = groupRecord[groupTextField];
        var kanbanQuote = kanbanDS.find(function (record) {
          return record.get(groupFieldName) === groupValue;
        });
        kanbanDS.setState("".concat(groupValue === undefined ? '_empty' : groupValue, "_totalCount"), kanbanQuote ? kanbanQuote.get(totalKey) : undefined);
        return /*#__PURE__*/React.createElement(KanbanColumn, {
          key: groupValue === undefined ? '_empty' : groupValue,
          kanbanProps: kanbanProps,
          prefixCls: prefixCls,
          quotes: kanbanQuote ? kanbanQuote.get(dataKey) : [],
          kanbanDS: kanbanDS,
          columnId: groupValue === undefined ? '_empty' : groupValue,
          header: groupText || '未分组',
          groupingBy: groupFieldName
        });
      });
    }

    return null;
  }, [columnData, loaded]);
  var cls = classnames("".concat(prefixCls, "-wrapper"), {});
  /**
  * buttons 大于 buttonsLimits 放入下拉
  * @param buttonsLimits
  */

  var getMoreButton = function getMoreButton(buttonsLimits) {
    var tableButtonProps = getConfig('tableButtonProps');
    var children = [];

    if (tableBtns && tableBtns.length && buttonsLimits) {
      tableBtns.slice(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 = getButtonProps(button);

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

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

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

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

                return function (_x) {
                  return _ref2.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
          }, /*#__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
          }, /*#__PURE__*/React.createElement(Button, _extends({}, tableButtonProps, button, {
            funcType: FuncType.link
          }))));
        }
      });
    }

    var menu = /*#__PURE__*/React.createElement(Menu, {
      prefixCls: "".concat(getProPrefixCls('table'), "-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'
    })));
  };

  var getButtonProps = useCallback(function (type) {
    var disabled = kanbanDS.status !== DataSetStatus.ready;

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

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

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

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

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

      case TableButtonType.query:
        return {
          icon: 'search',
          onClick: function () {
            var _onClick = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
              return _regeneratorRuntime.wrap(function _callee3$(_context3) {
                while (1) {
                  switch (_context3.prev = _context3.next) {
                    case 0:
                      _context3.next = 2;
                      return kanbanDS.modifiedCheck(undefined, dataSet, 'query');

                    case 2:
                      _context3.t2 = _context3.sent;

                      if (!_context3.t2) {
                        _context3.next = 5;
                        break;
                      }

                      _context3.t2 = kanbanDS.queryDataSet;

                    case 5:
                      _context3.t1 = _context3.t2;

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

                      _context3.t1 = kanbanDS.queryDataSet.current;

                    case 8:
                      _context3.t0 = _context3.t1;

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

                      _context3.next = 12;
                      return kanbanDS.queryDataSet.current.validate();

                    case 12:
                      _context3.t0 = _context3.sent;

                    case 13:
                      if (!_context3.t0) {
                        _context3.next = 15;
                        break;
                      }

                      return _context3.abrupt("return", kanbanDS.query());

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

            function onClick() {
              return _onClick.apply(this, arguments);
            }

            return onClick;
          }(),
          children: $l('Table', 'query_button')
        };

      case TableButtonType["export"]:
        return undefined;

      case TableButtonType.expandAll:
        return undefined;

      case TableButtonType.collapseAll:
        return undefined;

      default:
    }
  }, []);
  var getButtons = useCallback(function (buttonsArr) {
    var children = [];
    var buttons = buttonsArr || tableBtns;

    if (buttons) {
      var tableButtonProps = getConfig('tableButtonProps');

      var _buttonsArr = buttons.slice(0, buttonsLimit);

      _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 = getButtonProps(button);

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

              defaultButtonProps.onClick = /*#__PURE__*/function () {
                var _ref3 = _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 _ref3.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 (buttonsLimit && buttons.length > buttonsLimit) {
        var moreButton = getMoreButton(buttonsLimit);
        children.push(moreButton);
      }
    }

    return children;
  }, [tableBtns, kanbanDS]);

  var getCustomizationIcon = function getCustomizationIcon() {
    // 是否存在切换面板按钮
    var hasButtons = buttons && buttons.length; // 是否存在视图按钮控制

    var shouldRenderTableBtns = !isFunction(renderButtons);
    var tableButtons = getButtons();
    var mergeButtons = buttons && buttons.length ? _toConsumableArray(buttons) : [];

    if (hasButtons) {
      if (shouldRenderTableBtns) {
        mergeButtons.push(tableButtons);
      } else {
        var getBtns = getButtons(renderButtons({
          viewMode: ViewMode.card,
          dataSet: kanbanDS,
          buttons: tableButtons
        }));
        mergeButtons.push(getBtns);
      }

      mergeButtons.unshift( /*#__PURE__*/React.createElement(Button, {
        key: "settings",
        className: "".concat(prefixCls, "-hover-button"),
        funcType: FuncType.flat,
        color: ButtonColor.primary,
        icon: "settings-o",
        onClick: openCustomizationModal
      }));
      return mergeButtons;
    }

    var buttonRenderer = [/*#__PURE__*/React.createElement(Button, {
      key: "settings",
      className: "".concat(prefixCls, "-hover-button"),
      funcType: FuncType.flat,
      color: ButtonColor.primary,
      icon: "settings-o",
      onClick: openCustomizationModal
    })];

    if (shouldRenderTableBtns) {
      buttonRenderer.unshift(tableBtns);
    } else {
      buttonRenderer.unshift(renderButtons({
        viewMode: ViewMode.card,
        dataSet: kanbanDS,
        buttons: tableBtns
      }));
    }

    return buttonRenderer;
  };
  /**
  * 渲染查询条字段组件
  */


  var getQueryFields = useCallback(function () {
    var queryDataSet = kanbanDS.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;
      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 = {};
          var inValidElement = getEditorByField(field, current, true);
          var placeholder = /*#__PURE__*/isValidElement(element) && element.props.placeholder ? element.props.placeholder : getPlaceholderByField(field, current);
          filterBarProps = {
            placeholder: placeholder,
            border: false,
            clearButton: true
          };
          var elementType = inValidElement.type;

          if ((! /*#__PURE__*/isValidElement(element) || element.props.suffix === undefined) && ['Currency', 'ObserverNumberField', 'EmailField', 'UrlField', 'ObserverTextField'].indexOf(elementType.name) !== -1) {
            _extends(filterBarProps, {
              suffix: /*#__PURE__*/React.createElement(Icon, {
                type: "search"
              })
            });
          }

          var _props3 = _objectSpread({
            key: name,
            name: name,
            dataSet: queryDataSet,
            isFlat: true
          }, filterBarProps);

          result.push( /*#__PURE__*/isValidElement(element) ? /*#__PURE__*/cloneElement(element, _props3) : /*#__PURE__*/cloneElement(inValidElement, _objectSpread(_objectSpread({}, _props3), isObject(element) ? element : {})));
        }
      };

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

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

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

    return result;
  }, []);
  var restDragDropContext = useCallback(function () {
    var dragDropContext = kanbanProps.dragDropContext;

    if (isFunction(dragDropContext)) {
      return dragDropContext({
        kanbanDS: kanbanDS,
        dataSet: dataSet
      });
    }

    return dragDropContext;
  }, [kanbanDS, dataSet]);
  return /*#__PURE__*/React.createElement("div", {
    style: {
      height: '100%'
    }
  }, kanbanDS && kanbanDS.queryDataSet ? /*#__PURE__*/React.createElement(TableDynamicFilterBar, _extends({}, queryBarProps, {
    dataSet: kanbanDS,
    queryDataSet: kanbanDS.queryDataSet,
    queryFields: getQueryFields(),
    buttons: getCustomizationIcon()
  })) : getCustomizationIcon(), /*#__PURE__*/React.createElement(DragDropContext, _extends({}, restDragDropContext()), /*#__PURE__*/React.createElement(Row, {
    gutter: 16,
    className: cls
  }, getBoardColumns())));
};

KanbanContent.defaultProps = {
  animated: true
};
KanbanContent.displayName = 'KanbanContent';
export default observer(KanbanContent);
//# sourceMappingURL=KanbanContent.js.map
