/**
 * tdesign v0.32.0
 * (c) 2021 tdesign
 * @license MIT
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var helper = require('../../../_chunks/dep-44e6bdf6.js');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var Vue = require('vue');
var isFunction = require('lodash/isFunction');
var table_primaryTable_sorterButton = require('../sorter-button.js');
var config = require('../../../config.js');
var table_primaryTableProps = require('../../primary-table-props.js');
var table_baseTableProps = require('../../base-table-props.js');
var utils_event = require('../../../utils/event.js');
var table_util_common = require('../../util/common.js');
require('tdesign-icons-vue');
require('../../../utils/mixins.js');
require('../../../config-provider/config-receiver.js');
require('../../../config-provider/zh_CN_config.js');
require('../../../tooltip/index.js');
require('../../../tooltip/tooltip.js');
require('../../../tooltip/props.js');
require('../../../popup/props.js');
require('../../../popup/popup.js');
require('@babel/runtime/helpers/typeof');
require('@popperjs/core');
require('../../../_chunks/dep-939cdc39.js');
require('../../../utils/classnames.js');
require('../../../utils/dom.js');
require('raf');
require('lodash/isString');
require('../../../utils/easing.js');
require('../../../utils/render-tnode.js');
require('../../../utils/set-style.js');
require('../../../utils/map-props.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('../../../utils/withInstall.js');
require('lodash/capitalize');
require('../../../utils/helper.js');
require('@babel/runtime/helpers/slicedToArray');
require('lodash/camelCase');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var Vue__default = /*#__PURE__*/_interopDefaultLegacy(Vue);
var isFunction__default = /*#__PURE__*/_interopDefaultLegacy(isFunction);

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
var sort = Vue__default["default"].extend({
  name: "".concat(config.prefix, "-primary-table-sort"),
  props: {
    data: table_baseTableProps["default"].data,
    columns: table_primaryTableProps["default"].columns,
    sort: table_primaryTableProps["default"].sort,
    multipleSort: table_primaryTableProps["default"].multipleSort
  },
  data: function data() {
    return {
      sorterFuncMap: {}
    };
  },
  computed: {
    sortArray: function sortArray() {
      var sort = this.sort;
      if (!sort) return [];
      return Array.isArray(sort) ? sort : [sort];
    },
    sortMap: function sortMap() {
      var sortMap = {};
      this.sortArray.forEach(function (info, index) {
        var sortBy = info.sortBy;
        sortMap[sortBy] = _objectSpread({
          index: index
        }, info);
      });
      return sortMap;
    },
    localDataSort: function localDataSort() {
      return !!Object.keys(this.sorterFuncMap).length;
    }
  },
  methods: {
    handleDataSort: function handleDataSort() {
      var _this = this;

      var data = this.data,
          sort = this.sort;
      if (!sort || !this.localDataSort) return;
      var formatedSort = sort instanceof Array ? sort : [sort];
      var newData = data.slice().sort(function (a, b) {
        var sortResult = 0;

        for (var i = 0, len = formatedSort.length; i < len; i++) {
          var item = formatedSort[i];
          var sortFunc = _this.sorterFuncMap[item.sortBy];

          if (sortResult === 0 && sortFunc) {
            sortResult = item.descending ? sortFunc(b, a) : sortFunc(a, b);

            if (sortResult !== 0) {
              sortResult = sortResult > 0 ? 1 : -1;
            }
          } else {
            break;
          }
        }

        return sortResult;
      });
      if (JSON.stringify(newData) === JSON.stringify(this.data)) return;
      utils_event.emitEvent(this, "data-change", newData);
      return newData;
    },
    needSort: function needSort(column) {
      var sorter = column.sorter,
          sortType = column.sortType;
      return sorter && (!sortType || Array.isArray(sortType) && sortType.length > 0 || typeof sortType === "string");
    },
    getNextSortOrder: function getNextSortOrder(currentSortOrder, sortType) {
      var sorterTypes = !sortType || sortType === "all" ? ["desc", "asc"] : [sortType];
      var idx = (sorterTypes.indexOf(currentSortOrder) + 1) % (sorterTypes.length + 1);
      return sorterTypes[idx];
    },
    handleSortHeaderClick: function handleSortHeaderClick(col) {
      var newData = this.handleDataSort();
      var sortInfo;

      if (this.multipleSort) {
        sortInfo = this.getMultipleNextSort(col);
      } else {
        sortInfo = this.getSingleNextSort(col);
      }

      utils_event.emitEvent(this, "sort-change", sortInfo, {
        currentDataSource: newData || this.data,
        col: col
      });
      utils_event.emitEvent(this, "change", {
        sorter: sortInfo
      }, {
        trigger: "sorter",
        currentData: newData || this.data
      });
    },
    getSortColumn: function getSortColumn(colKey) {
      return this.columns.find(function (column) {
        return column.colKey === colKey;
      });
    },
    getSortOrder: function getSortOrder(descending) {
      if (descending === void 0) return;
      return descending ? "desc" : "asc";
    },
    getNextDescending: function getNextDescending(current, col) {
      var _ref = current || {},
          descending = _ref.descending;

      var _col$sortType = col.sortType,
          sortType = _col$sortType === void 0 ? "all" : _col$sortType;
      if (descending === true && ["asc", "all"].includes(sortType)) return false;
      if (descending === void 0 && ["desc", "all"].includes(sortType)) return true;
    },
    getSingleNextSort: function getSingleNextSort(col) {
      var colKey = col.colKey;
      var current = this.sortMap[colKey];
      var next = this.getNextDescending(current, col);
      if (next === void 0) return;
      return {
        sortBy: colKey,
        descending: next
      };
    },
    getMultipleNextSort: function getMultipleNextSort(col) {
      if (!(this.sort instanceof Array)) return;
      var colKey = col.colKey;

      var result = _toConsumableArray__default["default"](this.sort);

      for (var i = 0, len = this.sort.length; i < len; i++) {
        if (this.sort[i].sortBy === colKey) {
          var next = this.getSingleNextSort(col);
          next ? result[i] = next : result.splice(i, 1);
          return result;
        }
      }

      result.push({
        sortBy: colKey,
        descending: true
      });
      return result;
    },
    getSorterColumns: function getSorterColumns(columns) {
      var _this2 = this;

      var h = this.$createElement;
      var r = columns.map(function (item, index) {
        var _column$children;

        var column = _objectSpread({}, item);

        if ((_column$children = column.children) !== null && _column$children !== void 0 && _column$children.length) {
          column.children = _toConsumableArray__default["default"](_this2.getSorterColumns(column.children));
        } else {
          if (isFunction__default["default"](column.sorter)) {
            _this2.sorterFuncMap[column.colKey] = column.sorter;
          }

          var needSort = _this2.needSort(column);

          if (needSort) {
            var _this2$sortMap$colKey;

            var _column$sortType = column.sortType,
                sortType = _column$sortType === void 0 ? "all" : _column$sortType,
                colKey = column.colKey;

            var nextSort = _this2.getSingleNextSort(column);

            var sorterButtonsProps = {
              on: {
                click: function click() {
                  return _this2.handleSortHeaderClick(column);
                }
              },
              props: {
                sortType: sortType,
                sortOrder: _this2.getSortOrder((_this2$sortMap$colKey = _this2.sortMap[colKey]) === null || _this2$sortMap$colKey === void 0 ? void 0 : _this2$sortMap$colKey.descending),
                nextSortOrder: _this2.getSortOrder(nextSort === null || nextSort === void 0 ? void 0 : nextSort.descending)
              }
            };
            var title = table_util_common.getTitle(_this2, column, index);

            column.title = function () {
              return h("div", {
                "class": "".concat(config.prefix, "-table__cell--sortable")
              }, [h("div", {
                "class": "".concat(config.prefix, "-table__cell--title")
              }, [h("div", [title]), h(table_primaryTable_sorterButton["default"], helper.helper([{}, sorterButtonsProps]))])]);
            };
          }
        }

        return column;
      });
      this.handleDataSort();
      return r;
    }
  }
});

exports["default"] = sort;
//# sourceMappingURL=sort.js.map
