"use strict";

var _typeof = require("@babel/runtime-corejs3/helpers/typeof");
var _sliceInstanceProperty2 = require("@babel/runtime-corejs3/core-js-stable/instance/slice");
var _Array$from = require("@babel/runtime-corejs3/core-js-stable/array/from");
var _Symbol = require("@babel/runtime-corejs3/core-js-stable/symbol");
var _getIteratorMethod = require("@babel/runtime-corejs3/core-js/get-iterator-method");
var _WeakMap = require("@babel/runtime-corejs3/core-js-stable/weak-map");
var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");
var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.makeSortTransform = makeSortTransform;
exports.useSortTransform = useSortTransform;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/slicedToArray"));
var _extends2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/extends"));
var _taggedTemplateLiteral2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/taggedTemplateLiteral"));
var _getOwnPropertySymbols = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols"));
var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/filter"));
var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));
var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/map"));
var _map2 = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map"));
var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));
var _findIndex = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/find-index"));
var _react = _interopRequireWildcard(require("react"));
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _internals = require("../internals");
var _utils = require("../utils");
var _warnTransformsDeprecated = require("./warnTransformsDeprecated");
var _templateObject;
function _interopRequireWildcard(e, t) { if ("function" == typeof _WeakMap) var r = new _WeakMap(), n = new _WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && _Object$getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof _Symbol && _getIteratorMethod(r) || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { var _context4; if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = _sliceInstanceProperty2(_context4 = {}.toString.call(r)).call(_context4, 8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? _Array$from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
var __rest = void 0 && (void 0).__rest || function (s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  if (s != null && typeof _getOwnPropertySymbols.default === "function") for (var i = 0, p = (0, _getOwnPropertySymbols.default)(s); i < p.length; i++) {
    if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  }
  return t;
};
function SortIcon(_ref) {
  var _ref$size = _ref.size,
    size = _ref$size === void 0 ? 32 : _ref$size,
    style = _ref.style,
    className = _ref.className,
    order = _ref.order;
  return /*#__PURE__*/_react.default.createElement("svg", {
    style: style,
    className: className,
    focusable: "false",
    preserveAspectRatio: "xMidYMid meet",
    width: size,
    height: size,
    viewBox: "0 0 32 32",
    "aria-hidden": "true"
  }, /*#__PURE__*/_react.default.createElement("path", {
    fill: order === 'asc' ? '#23A3FF' : '#bfbfbf',
    transform: "translate(0, 4)",
    d: "M8 8L16 0 24 8z"
  }), /*#__PURE__*/_react.default.createElement("path", {
    fill: order === 'desc' ? '#23A3FF' : '#bfbfbf',
    transform: "translate(0, -4)",
    d: "M24 24L16 32 8 24z "
  }));
}
function DefaultSortHeaderCell(_ref2) {
  var children = _ref2.children,
    column = _ref2.column,
    onToggle = _ref2.onToggle,
    sortOrder = _ref2.sortOrder,
    sortIndex = _ref2.sortIndex,
    sortOptions = _ref2.sortOptions;
  // 通过 justify-content 来与 col.align 保持对齐方向一致
  var justifyContent = column.align === 'right' ? 'flex-end' : column.align === 'center' ? 'center' : 'flex-start';
  return /*#__PURE__*/_react.default.createElement(TableHeaderCell, {
    onClick: onToggle,
    style: {
      justifyContent: justifyContent
    }
  }, children, /*#__PURE__*/_react.default.createElement(SortIcon, {
    style: {
      userSelect: 'none',
      marginLeft: 2,
      flexShrink: 0
    },
    size: 16,
    order: sortOrder
  }), sortOptions.mode === 'multiple' && sortIndex != -1 && (/*#__PURE__*/_react.default.createElement("div", {
    style: {
      userSelect: 'none',
      marginLeft: 2,
      color: '#666',
      flex: '0 0 auto',
      fontSize: 10,
      fontFamily: 'monospace'
    }
  }, sortIndex + 1)));
}
function hasAnySortableColumns(cols) {
  return cols.some(function (col) {
    var _a;
    return Boolean((_a = col.features) === null || _a === void 0 ? void 0 : _a.sortable) || !(0, _utils.isLeafNode)(col) && hasAnySortableColumns(col.children);
  });
}
var TableHeaderCell = _styledComponents.default.div(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2.default)(["\n  cursor: pointer;\n  display: flex;\n  align-items: center;\n"])));
/** @deprecated transform 用法已经过时，请使用 pipeline 来对表格进行拓展 */
function makeSortTransform(_ref3) {
  var inputSorts = _ref3.sorts,
    inputOnChangeSorts = _ref3.onChangeSorts,
    _ref3$orders = _ref3.orders,
    orders = _ref3$orders === void 0 ? ['desc', 'asc', 'none'] : _ref3$orders,
    _ref3$mode = _ref3.mode,
    mode = _ref3$mode === void 0 ? 'multiple' : _ref3$mode,
    _ref3$SortHeaderCell = _ref3.SortHeaderCell,
    SortHeaderCell = _ref3$SortHeaderCell === void 0 ? DefaultSortHeaderCell : _ref3$SortHeaderCell,
    keepDataSource = _ref3.keepDataSource,
    highlightColumnWhenActive = _ref3.highlightColumnWhenActive,
    stopClickEventPropagation = _ref3.stopClickEventPropagation;
  (0, _warnTransformsDeprecated.warnTransformsDeprecated)('makeSortTransform');
  var filteredInputSorts = (0, _filter.default)(inputSorts).call(inputSorts, function (s) {
    return s.order !== 'none';
  });
  // 单字段排序的情况下 sorts 中只有第一个排序字段才会生效
  var sorts = mode === 'multiple' ? filteredInputSorts : (0, _slice.default)(filteredInputSorts).call(filteredInputSorts, 0, 1);
  var onChangeSorts = mode === 'multiple' ? inputOnChangeSorts : function (nextSorts) {
    // 单字段排序的情况下，nextSorts 中只有最后一个排序字段才会生效
    var len = nextSorts.length;
    inputOnChangeSorts((0, _slice.default)(nextSorts).call(nextSorts, len - 1));
  };
  var sortOptions = {
    sorts: sorts,
    onChangeSorts: onChangeSorts,
    orders: orders,
    mode: mode,
    keepDataSource: keepDataSource,
    highlightColumnWhenActive: highlightColumnWhenActive,
    stopClickEventPropagation: stopClickEventPropagation
  };
  var sortMap = new _map.default((0, _map2.default)(sorts).call(sorts, function (sort, index) {
    return [sort.code, (0, _extends2.default)({
      index: index
    }, sort)];
  }));
  return function (_ref4) {
    var dataSource = _ref4.dataSource,
      columns = _ref4.columns;
    return {
      columns: processColumns(columns),
      dataSource: processDataSource(dataSource)
    };
    function processDataSource(dataSource) {
      var _context, _context2;
      if (keepDataSource) {
        return dataSource;
      }
      var sortColumnsMap = new _map.default((0, _map2.default)(_context = (0, _filter.default)(_context2 = (0, _utils.collectNodes)(columns, 'leaf-only')).call(_context2, function (col) {
        var _a;
        return ((_a = col.features) === null || _a === void 0 ? void 0 : _a.sortable) != null;
      })).call(_context, function (col) {
        return [col.code, col];
      }));
      return (0, _utils.layeredSort)(dataSource, function (x, y) {
        var _iterator = _createForOfIteratorHelper(sorts),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var _step$value = _step.value,
              code = _step$value.code,
              order = _step$value.order;
            var column = sortColumnsMap.get(code);
            // 如果 code 对应的 column 不可排序，我们跳过该 code
            if (column == null) {
              continue;
            }
            var sortable = column.features.sortable;
            var compareFn = typeof sortable === 'function' ? sortable : _utils.smartCompare;
            var xValue = _internals.internals.safeGetValue(column, x, -1);
            var yValue = _internals.internals.safeGetValue(column, y, -1);
            var cmp = compareFn(xValue, yValue);
            if (cmp !== 0) {
              return cmp * (order === 'asc' ? 1 : -1);
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
        return 0;
      });
    }
    // 在「升序 - 降序 - 不排序」之间不断切换
    function toggle(code) {
      var sort = sortMap.get(code);
      if (sort == null) {
        onChangeSorts((0, _concat.default)(sorts).call(sorts, [{
          code: code,
          order: orders[0]
        }]));
      } else {
        var index = (0, _findIndex.default)(sorts).call(sorts, function (s) {
          return s.code === code;
        });
        var nextSorts = (0, _slice.default)(sorts).call(sorts, 0, index + 1);
        var nextOrder = getNextOrder(sort.order);
        if (nextOrder === 'none') {
          nextSorts.pop();
        } else {
          nextSorts[index] = (0, _extends2.default)((0, _extends2.default)({}, nextSorts[index]), {
            order: nextOrder
          });
        }
        onChangeSorts(nextSorts);
      }
    }
    function processColumns(columns) {
      return (0, _map2.default)(columns).call(columns, dfs);
      function dfs(col) {
        var _a;
        var result = (0, _extends2.default)({}, col);
        var sortable = col.code && (((_a = col.features) === null || _a === void 0 ? void 0 : _a.sortable) || sortMap.has(col.code));
        var active = sortable && sortMap.has(col.code);
        if (sortable) {
          var sortIndex = -1;
          var sortOrder = 'none';
          if (active) {
            var _sortMap$get = sortMap.get(col.code),
              order = _sortMap$get.order,
              index = _sortMap$get.index;
            sortOrder = order;
            sortIndex = index;
            if (highlightColumnWhenActive) {
              result.headerCellProps = (0, _utils.mergeCellProps)(col.headerCellProps, {
                style: {
                  background: 'var(--header-highlight-bgcolor)'
                }
              });
              result.getCellProps = function (value, row, rowIndex) {
                var prevCellProps = _internals.internals.safeGetCellProps(col, row, rowIndex);
                return (0, _utils.mergeCellProps)(prevCellProps, {
                  style: {
                    background: 'var(--highlight-bgcolor)'
                  }
                });
              };
            }
          }
          result.title = /*#__PURE__*/_react.default.createElement(SortHeaderCell, {
            onToggle: function onToggle(e) {
              if (stopClickEventPropagation) {
                e.stopPropagation();
              }
              toggle(col.code);
            },
            sortOrder: sortOrder,
            column: col,
            sortIndex: sortIndex,
            sortOptions: sortOptions
          }, _internals.internals.safeRenderHeader(col));
        }
        if (!(0, _utils.isLeafNode)(col)) {
          var _context3;
          result.children = (0, _map2.default)(_context3 = col.children).call(_context3, dfs);
        }
        return result;
      }
    }
  };
  function getNextOrder(order) {
    var idx = orders.indexOf(order);
    return orders[idx === orders.length - 1 ? 0 : idx + 1];
  }
}
/** @deprecated transform 用法已经过时，请使用 pipeline 来对表格进行拓展 */
function useSortTransform() {
  var _a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var _a$defaultSorts = _a.defaultSorts,
    defaultSorts = _a$defaultSorts === void 0 ? [] : _a$defaultSorts,
    others = __rest(_a, ["defaultSorts"]);
  var _useState = (0, _react.useState)(defaultSorts),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    sorts = _useState2[0],
    onChangeSorts = _useState2[1];
  return makeSortTransform((0, _extends2.default)({
    sorts: sorts,
    onChangeSorts: onChangeSorts
  }, others));
}