/**
 * ldesign v0.4.2
 * (c) 2023 ldesign
 * @license MIT
 */

'use strict';

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

var _typeof = require('@babel/runtime/helpers/typeof');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var vue = require('vue');
var isFunction = require('lodash/isFunction');
var table_sorterButton = require('../sorter-button.js');
var hooks_useDefaultValue = require('../../hooks/useDefaultValue.js');
require('@ldesign/icons-vue-next');
require('../../tooltip/index.js');
require('../../utils/withInstall.js');
require('../../tooltip/tooltip.js');
require('lodash/omit');
require('../../popup/props.js');
require('../../popup/index.js');
require('../../popup/popup.js');
require('@popperjs/core');
require('lodash/isObject');
require('lodash/isString');
require('../../hooks/useConfig.js');
require('../../config-provider/useConfig.js');
require('lodash/cloneDeep');
require('../../config-provider/context.js');
require('lodash/mergeWith');
require('lodash/merge');
require('lodash/isArray');
require('../../_common/js/global-config/default-config.js');
require('../../_common/js/global-config/locale/zh_CN.js');
require('../../_chunks/dep-7f0559c3.js');
require('dayjs');
require('../../hooks/useVModel.js');
require('lodash/kebabCase');
require('../../utils/dom.js');
require('../../utils/easing.js');
require('../../_common/js/utils/set-style.js');
require('../../popup/container.js');
require('../../hooks/useResizeObserver.js');
require('../../hooks/tnode.js');
require('lodash/camelCase');
require('../../utils/render-tnode.js');
require('lodash/isEmpty');
require('../../tooltip/util.js');
require('../../tooltip/props.js');
require('../../hooks/useGlobalIcon.js');
require('./useClassName.js');

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

var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof);
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 slots = _ref.slots;
  var _toRefs = vue.toRefs(props),
    sort = _toRefs.sort,
    data = _toRefs.data;
  var originalData = vue.ref();
  var _useDefaultValue = hooks_useDefaultValue["default"](sort, props.defaultSort, props.onSortChange, "sort"),
    _useDefaultValue2 = _slicedToArray__default["default"](_useDefaultValue, 2),
    tSortInfo = _useDefaultValue2[0],
    setTSortInfo = _useDefaultValue2[1];
  var _useDefaultValue3 = hooks_useDefaultValue["default"](data, [], props.onDataChange, "data"),
    _useDefaultValue4 = _slicedToArray__default["default"](_useDefaultValue3, 2),
    tData = _useDefaultValue4[0],
    setTData = _useDefaultValue4[1];
  var sorterFuncMap = vue.computed(function () {
    return getSorterFuncMap(props.columns);
  });
  var innerSort = vue.ref();
  var sortArray = vue.computed(function () {
    var sort2 = tSortInfo.value;
    if (!sort2) return [];
    return Array.isArray(sort2) ? sort2 : [sort2];
  });
  var sortMap = vue.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 || Array.isArray(sort2) && !sort2.length;
    var isEmptyObjectSort = !Array.isArray(sort2) && !(sort2 !== null && sort2 !== void 0 && sort2.sortBy);
    if (isEmptyArraySort || isEmptyObjectSort) {
      setTData(originalData.value, {
        trigger: "sort"
      });
      return originalData.value;
    }
    var formatedSort = Array.isArray(sort2) ? 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 = Array.isArray(tSortInfo.value) ? 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"
    });
    innerSort.value = sortInfo;
  }
  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 (!Array.isArray(sort2)) 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(_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,
      hideSortTips: props.hideSortTips
    };
    return vue.createVNode(table_sorterButton["default"], vue.mergeProps(sorterButtonsProps, {
      "onSortIconClick": function onSortIconClick(_, p) {
        return handleSortHeaderClick(col, p);
      }
    }), {
      sortIcon: slots.sortIcon
    });
  }
  var isSortInfoSame = function isSortInfoSame(a, b) {
    var tmpSortInfo = Array.isArray(a) ? a : [a];
    var tmpInnerSortInfo = Array.isArray(b) ? b : [b];
    if (tmpSortInfo.length && !b) return false;
    var _loop = function _loop() {
      var item = tmpSortInfo[i];
      var result = tmpInnerSortInfo.find(function (t) {
        return t.sortBy === item.sortBy;
      });
      if (!result) return {
        v: false
      };
      return {
        v: item.descending === result.descending
      };
    };
    for (var i = 0, len = tmpSortInfo.length; i < len; i++) {
      var _ret = _loop();
      if (_typeof__default["default"](_ret) === "object") return _ret.v;
    }
  };
  vue.watch(tSortInfo, function () {
    if (!tSortInfo.value) return;
    if (!isSortInfoSame(tSortInfo.value, innerSort.value)) handleDataSort(tSortInfo.value);
  }, {
    immediate: true
  });
  return {
    renderSortIcon: renderSortIcon
  };
}

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