import _Array$from from "@babel/runtime-corejs3/core-js-stable/array/from";
import _Symbol from "@babel/runtime-corejs3/core-js-stable/symbol";
import _getIteratorMethod from "@babel/runtime-corejs3/core-js/get-iterator-method";
import _extends from "@babel/runtime-corejs3/helpers/extends";
import _taggedTemplateLiteral from "@babel/runtime-corejs3/helpers/taggedTemplateLiteral";
import _defineProperty from "@babel/runtime-corejs3/helpers/defineProperty";

var _templateObject;

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 = _sliceInstanceProperty(_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; }

import _filterInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/filter";
import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice";
import _Map from "@babel/runtime-corejs3/core-js-stable/map";
import _mapInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/map";
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat";
import _findIndexInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/find-index";
import React from 'react';
import styled from 'styled-components';
import cx from 'classnames';
import { internals } from '../../internals';
import { collectNodes, isLeafNode, layeredSort, mergeCellProps, smartCompare, console } from '../../utils';
import { Classes } from '../../base/styles';

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.createElement("svg", {
    style: style,
    className: className,
    focusable: "false",
    preserveAspectRatio: "xMidYMid meet",
    width: size,
    height: size,
    viewBox: "0 0 32 32",
    "aria-hidden": "true",
    fill: "currentColor"
  }, /*#__PURE__*/React.createElement("path", {
    fill: order === 'asc' ? 'currentColor' : '#bfbfbf',
    transform: "translate(0, 4)",
    d: "M8 8L16 0 24 8z"
  }), /*#__PURE__*/React.createElement("path", {
    fill: order === 'desc' ? 'currentColor' : '#bfbfbf',
    transform: "translate(0, -4)",
    d: "M24 24L16 32 8 24z "
  }));
}

function DefaultSortHeaderCell(_ref2) {
  var _cx;

  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.createElement(TableHeaderCell, {
    onClick: onToggle,
    style: {
      justifyContent: justifyContent
    }
  }, children, /*#__PURE__*/React.createElement(SortIcon, {
    style: {
      userSelect: 'none',
      marginLeft: 2,
      flexShrink: 0
    },
    className: cx((_cx = {}, _defineProperty(_cx, Classes.tableSortIcon, true), _defineProperty(_cx, "active", sortOrder === 'desc' || sortOrder === 'asc'), _cx)),
    size: 16,
    order: sortOrder
  }), sortOptions.mode === 'multiple' && sortIndex !== -1 && /*#__PURE__*/React.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) || !isLeafNode(col) && hasAnySortableColumns(col.children);
  });
}

var TableHeaderCell = styled.div(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n  cursor: pointer;\n  display: flex;\n  align-items: center;\n  // flex: auto;\n"])));
var stateKey = 'sort';
export function sort() {
  var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return function sortStep(pipeline) {
    var _a, _b, _c;

    var _opts$orders = opts.orders,
        orders = _opts$orders === void 0 ? ['desc', 'asc', 'none'] : _opts$orders,
        _opts$mode = opts.mode,
        mode = _opts$mode === void 0 ? 'multiple' : _opts$mode,
        _opts$SortHeaderCell = opts.SortHeaderCell,
        SortHeaderCell = _opts$SortHeaderCell === void 0 ? DefaultSortHeaderCell : _opts$SortHeaderCell,
        keepDataSource = opts.keepDataSource,
        highlightColumnWhenActive = opts.highlightColumnWhenActive,
        stopClickEventPropagation = opts.stopClickEventPropagation,
        sortIconHoverShow = opts.sortIconHoverShow;
    var inputSorts = (_c = (_b = (_a = opts.sorts) !== null && _a !== void 0 ? _a : pipeline.getStateAtKey(stateKey)) !== null && _b !== void 0 ? _b : opts.defaultSorts) !== null && _c !== void 0 ? _c : [];

    var activeSorts = _filterInstanceProperty(inputSorts).call(inputSorts, function (s) {
      return s.order !== 'none';
    }); // 单字段排序的情况下 sorts 中只有第一个排序字段才会生效


    var sorts = mode === 'multiple' ? activeSorts : _sliceInstanceProperty(activeSorts).call(activeSorts, 0, 1);

    var onChangeSortsInMultipleMode = function onChangeSortsInMultipleMode(nextSorts, currentSort) {
      var _a;

      (_a = opts.onChangeSorts) === null || _a === void 0 ? void 0 : _a.call(opts, nextSorts, currentSort);
      pipeline.setStateAtKey(stateKey, nextSorts);
    };

    var onChangeSorts = mode === 'multiple' ? onChangeSortsInMultipleMode : function (nextSorts, currentSort) {
      // 单字段排序的情况下，nextSorts 中只有最后一个排序字段才会生效
      var len = nextSorts.length;
      onChangeSortsInMultipleMode(_sliceInstanceProperty(nextSorts).call(nextSorts, len - 1), currentSort);
    };
    var sortOptions = {
      sorts: sorts,
      onChangeSorts: onChangeSorts,
      orders: orders,
      mode: mode,
      keepDataSource: keepDataSource,
      highlightColumnWhenActive: highlightColumnWhenActive,
      stopClickEventPropagation: stopClickEventPropagation,
      sortIconHoverShow: sortIconHoverShow
    };
    var sortMap = new _Map(_mapInstanceProperty(sorts).call(sorts, function (sort, index) {
      return [sort.code, _extends({
        index: index
      }, sort)];
    }));
    var dataSource = pipeline.getDataSource();
    var columns = pipeline.getColumns();

    if (process.env.NODE_ENV !== 'production') {
      if (!hasAnySortableColumns(columns)) {
        console.warn('commonTransform.sort 缺少可排序的列，请通过 column.features.sortable 来指定哪些列可排序', columns);
      }
    }

    pipeline.dataSource(processDataSource(dataSource));
    pipeline.columns(processColumns(columns));
    return pipeline;

    function processDataSource(dataSource) {
      var _context, _context2;

      if (keepDataSource) {
        return dataSource;
      }

      var sortColumnsMap = new _Map(_mapInstanceProperty(_context = _filterInstanceProperty(_context2 = collectNodes(columns, 'leaf-only')).call(_context2, function (col) {
        var _a, _b;

        return ((_a = col.features) === null || _a === void 0 ? void 0 : _a.sortable) !== false && ((_b = col.features) === null || _b === void 0 ? void 0 : _b.sortable) != null;
      })).call(_context, function (col) {
        return [col.code, col];
      }));
      return 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 : smartCompare;
            var xValue = internals.safeGetValue(column, x, -1);
            var yValue = internals.safeGetValue(column, y, -1);
            var cmp = compareFn(xValue, yValue, x, y);

            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);
      var currentSort;

      if (sort == null) {
        currentSort = {
          code: code,
          order: orders[0]
        };
        onChangeSorts(_concatInstanceProperty(sorts).call(sorts, [currentSort]), currentSort);
      } else {
        var index = _findIndexInstanceProperty(sorts).call(sorts, function (s) {
          return s.code === code;
        });

        var nextSorts = _sliceInstanceProperty(sorts).call(sorts, 0, index + 1);

        var nextOrder = getNextOrder(sort.order);
        currentSort = {
          code: code,
          order: nextOrder
        };

        if (nextOrder === 'none') {
          nextSorts.pop();
        } else {
          nextSorts[index] = _extends(_extends({}, nextSorts[index]), {
            order: nextOrder
          });
        }

        onChangeSorts(nextSorts, currentSort);
      }
    }

    function processColumns(columns) {
      return _mapInstanceProperty(columns).call(columns, dfs);

      function dfs(col) {
        var _a;

        var result = _extends({}, 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 = mergeCellProps(col.headerCellProps, {
                style: {
                  background: 'var(--header-highlight-bgcolor)'
                }
              });

              result.getCellProps = function (value, row, rowIndex) {
                var prevCellProps = internals.safeGetCellProps(col, row, rowIndex);
                return mergeCellProps(prevCellProps, {
                  style: {
                    background: 'var(--highlight-bgcolor)'
                  }
                });
              };
            }
          }

          var sortNode = /*#__PURE__*/React.createElement(SortHeaderCell, {
            onToggle: function onToggle(e) {
              if (stopClickEventPropagation) {
                e.stopPropagation();
              }

              toggle(col.code);
            },
            sortOrder: sortOrder,
            column: col,
            sortIndex: sortIndex,
            sortOptions: sortOptions
          }, internals.safeRenderHeader(_extends(_extends({}, col), {
            title: col.title && col.title[0] ? col.title[0] : col.title
          })));

          if (result.title && result.title[0]) {
            result.title[0] = sortNode;
          } else {
            result.title = sortNode;
          }
        }

        if (!isLeafNode(col)) {
          var _context3;

          result.children = _mapInstanceProperty(_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];
    }
  };
}