/**
 * tdesign v0.39.1-alpha.1
 * (c) 2022 tdesign
 * @license MIT
 */

'use strict';

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

var helper = require('../../_chunks/dep-33ee4bce.js');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var VueCompositionAPI = require('@vue/composition-api');
var isFunction = require('lodash/isFunction');
var table_sorterButton = require('../sorter-button.js');
var hooks_useDefaultValue = require('../../hooks/useDefaultValue.js');
require('tdesign-icons-vue');
require('./useClassName.js');
require('../../config-provider/useConfig.js');
require('lodash/cloneDeep');
require('lodash/mergeWith');
require('../../config-provider/context.js');
require('lodash/merge');
require('../../_common/js/global-config/default-config.js');
require('../../_common/js/global-config/locale/zh_CN.js');
require('../../tooltip/index.js');
require('../../tooltip/tooltip.js');
require('vue');
require('../../config.js');
require('../../tooltip/props.js');
require('../../popup/props.js');
require('../../popup/popup.js');
require('@babel/runtime/helpers/typeof');
require('@popperjs/core');
require('../../utils/classnames.js');
require('../../utils/dom.js');
require('raf');
require('lodash/isString');
require('../../utils/easing.js');
require('../../utils/render-tnode.js');
require('lodash/isObject');
require('../../utils/helper.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('lodash/camelCase');
require('../../_common/js/utils/set-style.js');
require('../../popup/container.js');
require('../../utils/map-props.js');
require('../../utils/withInstall.js');
require('lodash/capitalize');
require('../../hooks/tnode.js');
require('lodash/isEmpty');
require('lodash/kebabCase');
require('../../hooks/render-tnode.js');
require('../../_common/js/log/log.js');

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 _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
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; }
function useSorter(props, _ref) {
  var emit = _ref.emit,
      slots = _ref.slots;

  var _toRefs = VueCompositionAPI.toRefs(props),
      sort = _toRefs.sort,
      data = _toRefs.data;

  var originalData = VueCompositionAPI.ref();

  var _useDefaultValue = hooks_useDefaultValue["default"](sort, props.defaultSort, props.onSortChange, "sort", "sort-change"),
      _useDefaultValue2 = _slicedToArray__default["default"](_useDefaultValue, 2),
      tSortInfo = _useDefaultValue2[0],
      setTSortInfo = _useDefaultValue2[1];

  var _useDefaultValue3 = hooks_useDefaultValue["default"](data, [], props.onDataChange, "data", "data-change"),
      _useDefaultValue4 = _slicedToArray__default["default"](_useDefaultValue3, 2),
      tData = _useDefaultValue4[0],
      setTData = _useDefaultValue4[1];

  var sorterFuncMap = VueCompositionAPI.computed(function () {
    return getSorterFuncMap(props.columns);
  });
  var sortArray = VueCompositionAPI.computed(function () {
    var sort2 = tSortInfo.value;
    if (!sort2) return [];
    return Array.isArray(sort2) ? sort2 : [sort2];
  });
  var sortMap = VueCompositionAPI.computed(function () {
    var sortMap2 = {};
    sortArray.value.forEach(function (info, index) {
      var sortBy = info.sortBy;
      sortMap2[sortBy] = _objectSpread({
        index: index
      }, info);
    });
    return sortMap2;
  });

  function getSorterFuncMap(columns) {
    var map = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    for (var i = 0, len = columns.length; i < len; i++) {
      var _col$children;

      var col = columns[i];

      if (isFunction__default["default"](col.sorter)) {
        map[col.colKey] = col.sorter;
      }

      if ((_col$children = col.children) !== null && _col$children !== void 0 && _col$children.length) {
        getSorterFuncMap(col.children, map);
      }
    }

    return map;
  }

  function handleDataSort(sortInfo) {
    var sort2 = sortInfo;
    if (!Object.keys(sorterFuncMap.value).length) return;

    if (!originalData.value) {
      originalData.value = tData.value;
    }

    var isEmptyArraySort = !sort2 || sort2 instanceof Array && !sort2.length;
    var isEmptyObjectSort = !(sort2 instanceof Array) && !(sort2 !== null && sort2 !== void 0 && sort2.sortBy);

    if (isEmptyArraySort || isEmptyObjectSort) {
      setTData(originalData.value, {
        trigger: "sort"
      });
      return originalData.value;
    }

    var formatedSort = sort2 instanceof Array ? sort2 : [sort2];
    var newData = tData.value.slice().sort(function (a, b) {
      var sortResult = 0;

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

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

      return sortResult;
    });
    if (JSON.stringify(newData) === JSON.stringify(tData.value)) return;
    setTData(newData, {
      trigger: "sort"
    });
    return newData;
  }

  function handleSortHeaderClick(col, p) {
    var _props$onChange;

    var sortInfo;

    if (props.multipleSort) {
      sortInfo = getMultipleNextSort(col, p);
    } else {
      var sort2 = tSortInfo.value instanceof Array ? tSortInfo.value[0] : tSortInfo.value;
      sortInfo = getSingleNextSort(col, sort2, p);
    }

    var newData = handleDataSort(sortInfo);
    var currentData = newData || tData.value;
    var currentDataSource = currentData;
    setTSortInfo(sortInfo, {
      currentDataSource: currentDataSource,
      col: col
    });
    (_props$onChange = props.onChange) === null || _props$onChange === void 0 ? void 0 : _props$onChange.call(props, {
      sorter: sortInfo
    }, {
      currentData: currentData,
      trigger: "sorter"
    });
    emit("change", {
      sorter: sortInfo
    }, {
      currentData: currentData,
      col: col,
      trigger: "sorter"
    });
  }

  function getSortOrder(descending) {
    if (descending === void 0) return;
    return descending ? "desc" : "asc";
  }

  function getSingleNextSort(col, sortInfo, p) {
    if (sortInfo && sortInfo.sortBy === col.colKey && sortInfo.descending === p.descending) {
      return void 0;
    }

    return {
      sortBy: col.colKey,
      descending: p.descending
    };
  }

  function getMultipleNextSort(col, p) {
    var sort2 = tSortInfo.value;
    if (!(sort2 instanceof Array)) return;
    var colKey = col.colKey;

    var result = _toConsumableArray__default["default"](sort2);

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

    result.push({
      sortBy: colKey,
      descending: p.descending
    });
    return result;
  }

  function renderSortIcon(h, _ref2) {
    var _sortMap$value$col$co;

    var col = _ref2.col;
    if (!col.sorter) return null;
    var sorterButtonsProps = {
      sortType: col.sortType,
      sortOrder: getSortOrder((_sortMap$value$col$co = sortMap.value[col.colKey]) === null || _sortMap$value$col$co === void 0 ? void 0 : _sortMap$value$col$co.descending),
      sortIcon: props.sortIcon
    };
    return h(table_sorterButton["default"], helper.helper([{
      "scopedSlots": {
        sortIcon: slots.sortIcon
      }
    }, {
      "props": sorterButtonsProps
    }, {}, {
      "on": {
        "sort-icon-click": function sortIconClick(_, p) {
          return handleSortHeaderClick(col, p);
        }
      }
    }]));
  }

  return {
    renderSortIcon: renderSortIcon
  };
}

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