import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import React, { useCallback, useContext, useEffect, useState, useMemo, useRef, isValidElement, cloneElement, Children } from 'react';
import { runInAction } from 'mobx';
import { observer } from 'mobx-react-lite';
import classnames from 'classnames';
import isString from 'lodash/isString';
import isObject from 'lodash/isObject';
import isNil from 'lodash/isNil';
import isFunction from 'lodash/isFunction';
import isBoolean from 'lodash/isBoolean';
import sortBy from 'lodash/sortBy';
import ConfigContext from '../../../es/config-provider/ConfigContext';
import warning from '../../../es/_util/warning';
import confirm from '../modal/confirm';
import { ViewField, ViewMode, ViewModeIcon } from './enum';
import DataSet from '../data-set';
import Table from '../table';
import Button from '../button';
import { ButtonColor, FuncType } from '../button/enum';
import Icon from '../icon';
import Dropdown from '../dropdown';
import Form from '../form';
import Select from '../select';
import TextField from '../text-field';
import ModalProvider from '../modal-provider';
import { useModal } from '../modal-provider/ModalProvider';
import KanbanContent from './KanbanContent';
import BoardContext from './BoardContext';
import { getColumnKey, getEditorByField, getPlaceholderByField } from '../table/utils';
import { $l } from '../locale-context';
import { FieldType, RecordStatus } from '../data-set/enum';
import CardContent from './CardContent';
import { ColumnLock } from '../table/interface';
import isFragment from '../_util/isFragment';
export var GROUPFIELD = '__GROUPFIELD__';

function normalizeColumns(elements, tableAggregation, customizedColumns) {
  var parent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  var defaultKey = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [0];
  var columnSort = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {
    left: 0,
    center: 0,
    right: 0
  };
  var columns = [];
  var leftColumns = [];
  var rightColumns = [];
  var hasAggregationColumn = false;
  var isHideDisabled = false;

  var normalizeColumn = function normalizeColumn(element) {
    if ( /*#__PURE__*/isValidElement(element)) {
      var props = element.props,
          key = element.key,
          type = element.type;

      if (isFragment(element)) {
        var children = props.children;

        if (children) {
          Children.forEach(children, normalizeColumn);
        }
      } else if (type.__PRO_TABLE_COLUMN) {
        var column = _objectSpread({}, props);

        if (key) {
          column.key = key;
        } else if (isNil(getColumnKey(column))) {
          column.key = "anonymous-".concat(defaultKey[0]++);
        }

        var _children = column.children,
            aggregation = column.aggregation;

        if (!hasAggregationColumn && aggregation) {
          hasAggregationColumn = true;
        }

        if (tableAggregation || !aggregation) {
          if (!isHideDisabled && column.hideable === false) {
            isHideDisabled = true;
          }

          if (parent || !column.lock) {
            if (column.sort === undefined) {
              column.sort = columnSort.center;
            }

            columnSort.center++;
            columns.push(column);
          } else if (column.lock === true || column.lock === ColumnLock.left) {
            if (column.sort === undefined) {
              column.sort = columnSort.left;
            }

            columnSort.left++;
            leftColumns.push(column);
          } else {
            if (column.sort === undefined) {
              column.sort = columnSort.right;
            }

            columnSort.right++;
            rightColumns.push(column);
          }
        } else {
          var _normalizeColumns = normalizeColumns(_children, tableAggregation, customizedColumns, parent, defaultKey, parent ? undefined : columnSort),
              _normalizeColumns2 = _slicedToArray(_normalizeColumns, 4),
              leftNodes = _normalizeColumns2[0],
              nodes = _normalizeColumns2[1],
              rightNodes = _normalizeColumns2[2],
              _normalizeColumns2$ = _normalizeColumns2[3],
              childrenHasAggregationColumn = _normalizeColumns2$.hasAggregationColumn,
              childrenIsHideDisabled = _normalizeColumns2$.isHideDisabled;

          if (!hasAggregationColumn && childrenHasAggregationColumn) {
            hasAggregationColumn = childrenHasAggregationColumn;
          }

          if (!isHideDisabled && childrenIsHideDisabled) {
            column.hideable = false;
            isHideDisabled = true;
          }

          if (parent) {
            parent.children = [].concat(_toConsumableArray(leftNodes), _toConsumableArray(nodes), _toConsumableArray(rightNodes));
          } else {
            leftColumns.push.apply(leftColumns, _toConsumableArray(leftNodes));
            columns.push.apply(columns, _toConsumableArray(nodes));
            rightColumns.push.apply(rightColumns, _toConsumableArray(rightNodes));
          }
        }
      }
    }
  };

  Children.forEach(elements, normalizeColumn);

  if (parent) {
    return [[], sortBy(columns, function (_ref) {
      var sort = _ref.sort;
      return sort;
    }), [], {
      hasAggregationColumn: hasAggregationColumn,
      isHideDisabled: isHideDisabled
    }];
  }

  return [sortBy(leftColumns, function (_ref2) {
    var sort = _ref2.sort;
    return sort;
  }), sortBy(columns, function (_ref3) {
    var sort = _ref3.sort;
    return sort;
  }), sortBy(rightColumns, function (_ref4) {
    var sort = _ref4.sort;
    return sort;
  }), {
    hasAggregationColumn: hasAggregationColumn,
    isHideDisabled: isHideDisabled
  }];
}
/**
 * 处理分组字段下拉数据,仅单选快码
 * @param dataSet
 */


function processGroupData(dataSet) {
  var data = [];
  dataSet.fields.forEach(function (field) {
    var type = field.get('type');
    var multiple = field.get('multiple');

    if (!multiple && (field.get('lookupCode') || isString(field.get('lookupUrl')) || type !== FieldType.object && (field.get('lovCode') || field.getLookup() || field.get('options')))) {
      data.push({
        value: field.get('name'),
        meaning: field.get('label')
      });
    }
  });
  return data;
}

var ModalContent = function ModalContent(_ref5) {
  var modal = _ref5.modal,
      prefixCls = _ref5.prefixCls,
      groupDataSet = _ref5.groupDataSet;
  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-board-modal-content")
  }, /*#__PURE__*/React.createElement("div", null, "\u9009\u62E9\u4E00\u4E2A\u5B57\u6BB5\uFF0C\u6570\u636E\u5C06\u6309\u7167\u6B64\u5B57\u6BB5\u4E2D\u7684\u5B57\u6BB5\u503C\u5206\u7EC4\u663E\u793A\u5728\u770B\u677F\u4E2D\uFF0C\u652F\u6301\u5B57\u6BB5\u7C7B\u578B\uFF1A\u5355\u9009\u3001\u4E0B\u62C9\u5355\u9009"), /*#__PURE__*/React.createElement(Form, {
    dataSet: groupDataSet
  }, /*#__PURE__*/React.createElement(TextField, {
    label: "\u89C6\u56FE\u540D\u79F0",
    name: ViewField.viewName
  }), /*#__PURE__*/React.createElement(Select, {
    name: "groupField",
    label: "\u9009\u62E9\u5206\u7EC4\u5B57\u6BB5",
    onChange: function onChange(value) {
      if (value) {
        modal.update({
          okProps: {
            disabled: false
          }
        });
      }
    }
  })));
};

var BoardWithContext = function Board(props) {
  var _useContext = useContext(ConfigContext),
      getConfig = _useContext.getConfig,
      getProPrefixCls = _useContext.getProPrefixCls;

  var _useState = useState(true),
      _useState2 = _slicedToArray(_useState, 2),
      hidden = _useState2[0],
      setHidden = _useState2[1];

  var onChange = props.onChange,
      onConfigChange = props.onConfigChange,
      renderButtons = props.renderButtons,
      viewVisible = props.viewVisible,
      autoQuery = props.autoQuery,
      kanbanProps = props.kanbanProps,
      cardProps = props.cardProps,
      renderCommand = props.renderCommand,
      customizedDS = props.customizedDS,
      queryFields = props.queryFields,
      dataSet = props.dataSet,
      tableProps = props.tableProps,
      customizable = props.customizable,
      customizedCode = props.customizedCode;
  var prefixCls = getProPrefixCls('board');
  var saveCustomized = useCallback( /*#__PURE__*/function () {
    var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(newCustomized) {
      var customizedSave, res;
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!(customizable && customizedCode)) {
                _context.next = 6;
                break;
              }

              customizedSave = getConfig('customizedSave');
              _context.next = 4;
              return customizedSave(customizedCode, newCustomized, 'Board');

            case 4:
              res = _context.sent;
              return _context.abrupt("return", res);

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

    return function (_x) {
      return _ref6.apply(this, arguments);
    };
  }(), [customizable, customizedCode]);
  var customizedLoad = getConfig('customizedLoad');
  var viewTypeVisible = useMemo(function () {
    if (isBoolean(viewVisible)) {
      return {
        card: viewVisible,
        kanban: viewVisible,
        table: viewVisible
      };
    }

    if (isObject(viewVisible)) {
      return {
        card: isBoolean(viewVisible.card) ? viewVisible.card : true,
        kanban: isBoolean(viewVisible.kanban) ? viewVisible.kanban : true,
        table: isBoolean(viewVisible.table) ? viewVisible.table : true
      };
    }

    return {
      card: true,
      kanban: true,
      table: true
    };
  }, [viewVisible]);
  var viewHeight = useMemo(function () {
    return customizedDS && customizedDS.current ? customizedDS.current.get(ViewField.viewHeight) : undefined;
  }, [customizedDS.current]);
  var currentDisplayFields = useMemo(function () {
    return customizedDS && customizedDS.current ? customizedDS.current.get(ViewField.displayFields) : undefined;
  }, [customizedDS.current]);

  var _useState3 = useState(''),
      _useState4 = _slicedToArray(_useState3, 2),
      searchText = _useState4[0],
      setSearchText = _useState4[1];

  var modal = useModal();
  var TableRef = useRef(null);
  var DropdownRef = useRef(null);
  var SwitchBtnRef = useRef(null);
  var optionDS = useMemo(function () {
    return new DataSet({
      data: processGroupData(dataSet),
      paging: false,
      primaryKey: 'value'
    });
  }, [dataSet]);
  var displayFields = useMemo(function () {
    if (tableProps && tableProps.columns) {
      return tableProps.columns;
    }

    if (tableProps && tableProps.children) {
      var children = tableProps.children,
          aggregation = tableProps.aggregation;
      var generatedColumns = normalizeColumns(children, aggregation);
      return generatedColumns[0].concat(generatedColumns[1], generatedColumns[2]);
    }

    return [];
  }, [tableProps]);
  var command = useMemo(function () {
    if (displayFields && displayFields.length) {
      var commandCol = displayFields.find(function (col) {
        return col.command;
      });
      return commandCol ? commandCol.command : [];
    }
  }, [displayFields]);
  var groupDataSet = useMemo(function () {
    return new DataSet({
      paging: false,
      primaryKey: 'groupField',
      autoCreate: true,
      fields: [{
        name: ViewField.groupField,
        required: true,
        type: FieldType.object,
        options: optionDS
      }, {
        name: ViewField.viewName,
        type: FieldType.string,
        defaultValue: '看板视图'
      }]
    });
  }, [dataSet]);
  /**
   * 处理面板显隐
   */

  var handleClickOut = useCallback(function (e) {
    if (DropdownRef.current && SwitchBtnRef.current // @ts-ignore
    && !(DropdownRef.current.contains(e.target) // @ts-ignore
    || SwitchBtnRef.current.element.contains(e.target))) {
      setHidden(true);
    }
  }, [DropdownRef]);
  useEffect(function () {
    document.addEventListener('click', handleClickOut);
    return function () {
      return document.removeEventListener('click', handleClickOut);
    };
  }, [DropdownRef]);
  /**
   * 新建视图 | 加载视图列表数据
   */

  var loadListData = useCallback( /*#__PURE__*/function () {
    var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(record) {
      var _defaultView, detailRes, res, mergeRes, defaultView;

      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.prev = 0;

              if (!(record.get(ViewField.id) || record.get('menuId') || record.get(ViewField.id) === '__DEFAULT__')) {
                _context2.next = 5;
                break;
              }

              detailRes = record.toData();
              _context2.next = 8;
              break;

            case 5:
              _context2.next = 7;
              return saveCustomized(record.toData());

            case 7:
              detailRes = _context2.sent;

            case 8:
              _context2.next = 10;
              return customizedLoad(customizedCode, 'Board', {
                type: 'list'
              });

            case 10:
              res = _context2.sent;
              mergeRes = res.map(function (r) {
                if (r.id === detailRes[ViewField.id]) {
                  return detailRes;
                }

                return r;
              });
              defaultView = (_defaultView = {
                code: customizedCode
              }, _defineProperty(_defaultView, ViewField.viewName, '初始列表视图'), _defineProperty(_defaultView, ViewField.viewMode, ViewMode.table), _defineProperty(_defaultView, ViewField.id, '__DEFAULT__'), _defaultView);
              customizedDS.loadData([].concat(_toConsumableArray(mergeRes), [defaultView]));
              _context2.next = 19;
              break;

            case 16:
              _context2.prev = 16;
              _context2.t0 = _context2["catch"](0);
              warning(false, _context2.t0.message);

            case 19:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[0, 16]]);
    }));

    return function (_x2) {
      return _ref7.apply(this, arguments);
    };
  }(), [customizedCode]);
  /**
   * 渲染查询条字段组件
   */

  var getQueryFields = useCallback(function () {
    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;
      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 _props = _objectSpread({
            key: name,
            name: name,
            dataSet: queryDataSet,
            isFlat: true
          }, filterBarProps);

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

      propFields.forEach(function (_ref8) {
        var name = _ref8.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 addBoardView = useCallback(function () {
    setHidden(true);
    var modalProps = {
      title: '看板视图',
      autoCenter: true,
      style: {
        width: 595
      },
      children: /*#__PURE__*/React.createElement(ModalContent, {
        groupDataSet: groupDataSet,
        prefixCls: prefixCls
      }),
      okProps: {
        disabled: true
      },
      onClose: function onClose() {
        groupDataSet.reset();
        return true;
      },
      onOk: function onOk() {
        var _ViewField$viewProps, _customizedDS$create;

        var groupField = groupDataSet.current.get('groupField').value;
        customizedDS.create((_customizedDS$create = {}, _defineProperty(_customizedDS$create, ViewField.viewMode, ViewMode.kanban), _defineProperty(_customizedDS$create, ViewField.viewName, groupDataSet.current.get(ViewField.viewName)), _defineProperty(_customizedDS$create, ViewField.viewProps, (_ViewField$viewProps = {}, _defineProperty(_ViewField$viewProps, ViewField.groupField, groupField), _defineProperty(_ViewField$viewProps, ViewField.cardWidth, 6), _defineProperty(_ViewField$viewProps, ViewField.displayFields, displayFields.map(function (field) {
          return field.name;
        }).filter(Boolean).slice(0, 3)), _defineProperty(_ViewField$viewProps, ViewField.showLabel, 1), _ViewField$viewProps)), _defineProperty(_customizedDS$create, ViewField.activeKey, 1), _customizedDS$create), 0);
        loadListData(customizedDS.current); // if (isFunction(onChange)) {
        //   onChange({ record: customizedDS.current, dataSet });
        // }

        return true;
      }
    };
    modal.open(modalProps);
  }, [modal, saveCustomized]);
  /**
   * 渲染视图切换面板
   */

  var renderSwitcherBoard = useCallback(function () {
    return /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-switch-board"),
      ref: DropdownRef
    }, /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-switch-board-search")
    }, /*#__PURE__*/React.createElement(TextField, {
      style: {
        width: '100%'
      },
      value: searchText,
      onClick: function onClick(e) {
        e.preventDefault();
        e.currentTarget.focus();
      },
      onChange: function onChange(v) {
        setSearchText(v);
      },
      onInput: function onInput(e) {
        setSearchText(e.target.value);
      },
      prefix: /*#__PURE__*/React.createElement(Icon, {
        type: "search"
      }),
      placeholder: $l('Table', 'enter_text_filter'),
      clearButton: true
    })), customizedDS && customizedDS.length ? customizedDS.map(function (record) {
      var viewMode = record.get(ViewField.viewMode);

      if (viewTypeVisible[viewMode] === false && !(record.get(ViewField.id) === '__DEFAULT__' || !record.get(ViewField.id))) {
        return null;
      }

      var itemCls = classnames("".concat(prefixCls, "-view-item"), _defineProperty({}, "".concat(prefixCls, "-view-item-active"), record.isCurrent));
      return /*#__PURE__*/React.createElement("div", {
        key: record.id,
        hidden: searchText ? !record.get(ViewField.viewName).includes(searchText) : false,
        className: itemCls,
        onClick: function () {
          var _onClick = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
            var res;
            return _regeneratorRuntime.wrap(function _callee3$(_context3) {
              while (1) {
                switch (_context3.prev = _context3.next) {
                  case 0:
                    if (!(record.get(ViewField.activeKey) === 1)) {
                      _context3.next = 4;
                      break;
                    }

                    setHidden(true);
                    _context3.next = 22;
                    break;

                  case 4:
                    customizedDS.current.set(ViewField.activeKey, 0);
                    record.set(ViewField.activeKey, 1);
                    customizedDS.current = record; // if (isFunction(onChange)) {
                    //   onChange({ record, dataSet });
                    // }

                    setHidden(true);
                    _context3.prev = 8;

                    if (!(record.get(ViewField.id) === '__DEFAULT__' || !record.get(ViewField.id))) {
                      _context3.next = 13;
                      break;
                    }

                    // 切换的为前端内置视图，frontFlag 标记前端配置，后端将其他视图 defaultFlag 置为 0
                    saveCustomized(_objectSpread(_objectSpread({}, record.toJSONData()), {}, {
                      id: undefined,
                      frontFlag: 1
                    }));
                    _context3.next = 17;
                    break;

                  case 13:
                    _context3.next = 15;
                    return customizedLoad(customizedCode, 'Board', _defineProperty({
                      type: 'detail'
                    }, ViewField.id, record.get(ViewField.id)));

                  case 15:
                    res = _context3.sent;
                    record.commit(res, customizedDS);

                  case 17:
                    _context3.next = 22;
                    break;

                  case 19:
                    _context3.prev = 19;
                    _context3.t0 = _context3["catch"](8);
                    record.status = RecordStatus.sync;

                  case 22:
                  case "end":
                    return _context3.stop();
                }
              }
            }, _callee3, null, [[8, 19]]);
          }));

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

          return onClick;
        }()
      }, /*#__PURE__*/React.createElement(Icon, {
        type: ViewModeIcon[record.get(ViewField.viewMode)]
      }), record.get(ViewField.viewName), record.get(ViewField.id) !== '__DEFAULT__' ? /*#__PURE__*/React.createElement(Icon, {
        className: "".concat(prefixCls, "-delete"),
        type: "delete_black-o",
        onClick: function () {
          var _onClick2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(e) {
            return _regeneratorRuntime.wrap(function _callee4$(_context4) {
              while (1) {
                switch (_context4.prev = _context4.next) {
                  case 0:
                    e.stopPropagation();
                    setHidden(true);
                    _context4.next = 4;
                    return confirm('确认删除');

                  case 4:
                    _context4.t0 = _context4.sent;

                    if (!(_context4.t0 !== 'cancel')) {
                      _context4.next = 7;
                      break;
                    }

                    runInAction(function () {
                      record.status = RecordStatus["delete"];

                      try {
                        saveCustomized(record.toJSONData());

                        if (record.isCurrent) {
                          customizedDS.current = customizedDS.find(function (record) {
                            return record.get(ViewField.id) === '__DEFAULT__';
                          });
                        }
                      } catch (e) {
                        record.status = RecordStatus.sync;
                      }
                    });

                  case 7:
                  case "end":
                    return _context4.stop();
                }
              }
            }, _callee4);
          }));

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

          return onClick;
        }()
      }) : null);
    }) : null, /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-switch-board-footer")
    }, /*#__PURE__*/React.createElement("div", null, "\u6DFB\u52A0\u89C6\u56FE"), /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-view-add")
    }, /*#__PURE__*/React.createElement("div", {
      hidden: !viewTypeVisible.table,
      onClick: function onClick() {
        var _customizedDS$create2;

        customizedDS.create((_customizedDS$create2 = {}, _defineProperty(_customizedDS$create2, ViewField.viewMode, ViewMode.table), _defineProperty(_customizedDS$create2, ViewField.viewName, '列表视图'), _defineProperty(_customizedDS$create2, ViewField.viewProps, {}), _defineProperty(_customizedDS$create2, ViewField.activeKey, 1), _customizedDS$create2), 0);

        try {
          // saveCustomized(customizedDS.current!.toData());
          loadListData(customizedDS.current); // if (isFunction(onChange)) {
          //   onChange({ record: customizedDS.current, dataSet });
          // }
        } catch (e) {// record.status = RecordStatus.sync;
        }

        setHidden(true);
      }
    }, /*#__PURE__*/React.createElement(Icon, {
      type: "biaoge-o"
    }), "\u5217\u8868"), /*#__PURE__*/React.createElement("div", {
      hidden: !viewTypeVisible.card,
      onClick: function onClick() {
        var _ViewField$viewProps2, _customizedDS$create3;

        customizedDS.create((_customizedDS$create3 = {}, _defineProperty(_customizedDS$create3, ViewField.viewMode, ViewMode.card), _defineProperty(_customizedDS$create3, ViewField.viewName, '卡片视图'), _defineProperty(_customizedDS$create3, ViewField.viewProps, (_ViewField$viewProps2 = {}, _defineProperty(_ViewField$viewProps2, ViewField.cardWidth, 6), _defineProperty(_ViewField$viewProps2, ViewField.displayFields, displayFields.map(function (field) {
          return field.name;
        }).filter(Boolean).slice(0, 3)), _defineProperty(_ViewField$viewProps2, ViewField.showLabel, 1), _ViewField$viewProps2)), _defineProperty(_customizedDS$create3, ViewField.activeKey, 1), _customizedDS$create3), 0);

        try {
          // saveCustomized(customizedDS.current!.toData());
          loadListData(customizedDS.current); // if (isFunction(onChange)) {
          //   onChange({ record: customizedDS.current, dataSet, currentViewDS:  });
          // }
        } catch (e) {// record.status = RecordStatus.sync;
        }

        setHidden(true);
      }
    }, /*#__PURE__*/React.createElement(Icon, {
      type: "kapian"
    }), "\u5361\u7247"), /*#__PURE__*/React.createElement("div", {
      hidden: !viewTypeVisible.kanban,
      onClick: addBoardView
    }, /*#__PURE__*/React.createElement(Icon, {
      type: "kanban"
    }), "\u770B\u677F"))));
  }, [customizedDS, searchText, viewTypeVisible]);
  var renderSwitcherIcon = useCallback(function () {
    var viewType = customizedDS.current && customizedDS.current.get(ViewField.viewMode);
    return /*#__PURE__*/React.createElement(Dropdown, {
      overlay: function overlay() {
        return renderSwitcherBoard();
      },
      hidden: hidden
    }, /*#__PURE__*/React.createElement(Button, {
      color: ButtonColor.primary,
      funcType: FuncType.flat,
      onClick: function () {
        var _onClick3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5() {
          return _regeneratorRuntime.wrap(function _callee5$(_context5) {
            while (1) {
              switch (_context5.prev = _context5.next) {
                case 0:
                  // 初次点击查询视图列表，=1 避免每次点击查询，保存具体配置或刷新重新查询 list 接口
                  if (hidden && customizedDS.length <= 2) {
                    loadListData(customizedDS.current);
                    customizedDS.setState('__ISCHANGE__', true);
                  }

                  setHidden(!hidden);

                case 2:
                case "end":
                  return _context5.stop();
              }
            }
          }, _callee5);
        }));

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

        return onClick;
      }(),
      ref: SwitchBtnRef
    }, /*#__PURE__*/React.createElement(Icon, {
      type: ViewModeIcon[viewType] || "biaoge-o"
    }), /*#__PURE__*/React.createElement(Icon, {
      type: hidden ? "baseline-arrow_drop_down" : "baseline-arrow_drop_up"
    })));
  }, [hidden, searchText, viewTypeVisible]);
  var tableDataSet = useMemo(function () {
    var isDefault = customizedDS.current ? customizedDS.current.get(ViewField.id) === '__DEFAULT__' : true;
    var defaultSortParams = dataSet.combineSort && customizedDS.current ? customizedDS.current.get(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 isDefault ? dataSet : new DataSet(_objectSpread(_objectSpread({}, dataSet.props), {}, {
      fields: orderFields,
      autoQuery: autoQuery
    }));
  }, [customizedDS.current]);
  var tableDataSetName = useMemo(function () {
    if (customizedDS.current && customizedDS.current.get(ViewField.viewMode) === ViewMode.table) {
      var changed = customizedDS.getState('__ISCHANGE__');

      if (isFunction(onChange) && tableDataSet && changed) {
        onChange({
          record: customizedDS.current,
          dataSet: dataSet,
          currentViewDS: tableDataSet
        });
      }
    }
  }, [tableDataSet]);
  var renderContent = useCallback(function () {
    var viewMode = customizedDS.current ? customizedDS.current.get(ViewField.viewMode) : ViewMode.table;
    var isDefault = customizedDS.current ? customizedDS.current.get(ViewField.id) === '__DEFAULT__' : true;
    var noSwitcher = !viewVisible || viewTypeVisible.card === false && viewTypeVisible.kanban === false && viewTypeVisible.table === false;
    var buttonsLimit = tableProps.buttonsLimit,
        buttons = tableProps.buttons,
        queryBarProps = tableProps.queryBarProps,
        queryFieldsLimit = tableProps.queryFieldsLimit,
        searchCode = tableProps.searchCode,
        dynamicFilterBar = tableProps.dynamicFilterBar;

    var tableQueryBarProps = _objectSpread(_objectSpread({}, getConfig('queryBarProps')), {}, {
      queryFieldsLimit: queryFieldsLimit,
      dynamicFilterBar: dynamicFilterBar,
      searchCode: searchCode
    }, queryBarProps);

    var displayedButtonsLimit = buttonsLimit && (noSwitcher ? buttonsLimit : buttonsLimit + 1);
    var tableBtns = buttons ? _toConsumableArray(buttons) : [];
    var btnRenderer = tableBtns;

    if (viewMode === ViewMode.table) {
      if (isFunction(renderButtons)) {
        btnRenderer = renderButtons({
          viewMode: viewMode,
          dataSet: isDefault ? dataSet : tableDataSet,
          buttons: tableBtns
        });
      }

      var btns = noSwitcher ? btnRenderer : [renderSwitcherIcon()].concat(_toConsumableArray(btnRenderer));
      dataSet.setState('__CURRENTVIEWDS__', tableDataSet); // handleChange tableDataSet

      if (tableDataSet) {
        dataSet.setState('__tempChange__', tableDataSetName);
      }

      return /*#__PURE__*/React.createElement(Table, _extends({}, tableProps, {
        customizable: isDefault ? false : customizable,
        customizedCode: customizedCode,
        boardCustomized: {
          customizedBtn: true,
          customizedDS: customizedDS
        },
        dataSet: isDefault ? dataSet : tableDataSet,
        buttons: btns,
        buttonsLimit: displayedButtonsLimit,
        ref: TableRef
      }));
    }

    if (viewMode === ViewMode.card) {
      return /*#__PURE__*/React.createElement(CardContent, {
        cardProps: cardProps,
        key: "cardContent",
        tableBtns: tableBtns,
        buttonsLimit: buttonsLimit,
        queryBarProps: tableQueryBarProps,
        buttons: noSwitcher ? [] : [renderSwitcherIcon()]
      });
    }

    return /*#__PURE__*/React.createElement(KanbanContent, {
      key: "kanbanContent",
      dataSet: dataSet,
      queryBarProps: tableQueryBarProps,
      tableBtns: tableBtns,
      buttonsLimit: buttonsLimit,
      buttons: noSwitcher ? [] : [renderSwitcherIcon()],
      kanbanProps: kanbanProps
    });
  }, [tableProps.buttonsLimit, customizedDS.current, viewHeight, currentDisplayFields, hidden, searchText, tableProps, viewTypeVisible]);
  var value = {
    // defaultActiveKey: propDefaultActiveKey,
    // actuallyDefaultActiveKey,
    // propActiveKey,
    prefixCls: prefixCls,
    getConfig: getConfig,
    getProPrefixCls: getProPrefixCls,
    customizedCode: customizedCode,
    // customizable,
    // customized,
    saveCustomized: saveCustomized,
    // activeKey,
    // changeActiveKey,
    autoQuery: autoQuery,
    command: command,
    renderCommand: renderCommand,
    renderButtons: renderButtons,
    customizedDS: customizedDS,
    displayFields: displayFields,
    optionDS: optionDS,
    dataSet: dataSet,
    queryFields: getQueryFields(),
    viewTypeVisible: viewTypeVisible,
    onConfigChange: onConfigChange,
    onChange: onChange
  };
  return /*#__PURE__*/React.createElement(BoardContext.Provider, {
    value: value
  }, customizable ? /*#__PURE__*/React.createElement(ModalProvider, null, renderContent()) : /*#__PURE__*/React.createElement(ModalProvider, null, renderContent()));
};

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