"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 _getRequireWildcardCache(nodeInterop) { if (typeof _WeakMap !== "function") return null; var cacheBabelInterop = new _WeakMap(); var cacheNodeInterop = new _WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && _Object$getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? _Object$getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof _Symbol !== "undefined" && _getIteratorMethod(o) || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { var _context4; if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = _sliceInstanceProperty2(_context4 = Object.prototype.toString.call(o)).call(_context4, 8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return _Array$from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

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;

    if (process.env.NODE_ENV !== 'production') {
      if (!hasAnySortableColumns(columns)) {
        console.warn('[ali-react-table] commonTransform.sort 缺少可排序的列，请通过 column.features.sortable 来指定哪些列可排序', 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));
}