/**
 * ldesign v0.2.14
 * (c) 2022/11/2 16:16 built by swimly
 * @license MIT
 */

'use strict';

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

var helper = require('../../../chunks/helper.js');
var VueCompositionAPI = require('@vue/composition-api');
var isFunction = require('lodash/isFunction');
var components_table_core_sorterButton = require('../core/sorter-button.js');
var hooks_useDefaultValue = require('../../../hooks/use-default-value.js');
require('@ldesign/icons-vue');
require('../../tooltip/index.js');
require('../../../utils/map-props.js');
require('vue');
require('../../../utils/with-install.js');
require('lodash');
require('../../../config.js');
require('../../tooltip/tooltip.js');
require('../../popup/props.js');
require('../../popup/popup.js');
require('@popperjs/core');
require('../../../chunks/set-style.js');
require('../../../utils/dom.js');
require('raf');
require('lodash/isString');
require('../../../chunks/log.js');
require('../../../chunks/_commonjsHelpers-2e6815bd.js');
require('../../../utils/easing.js');
require('../../../utils/render-node.js');
require('../../../utils/helper.js');
require('lodash/camelCase');
require('../../config-provider/config-receiver.js');
require('lodash/mergeWith');
require('../../config-provider/context.js');
require('../../../chunks/zh_CN.js');
require('../../../utils/mixins.js');
require('../../popup/container.js');
require('../../tooltip/props.js');
require('../../config-provider/useConfig.js');
require('../../../hooks/lnode.js');
require('lodash/isEmpty');
require('lodash/kebabCase');
require('../../../hooks/render-lnode.js');
require('../../../hooks/use-global-icon.js');
require('./useClassName.js');

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

var isFunction__default = /*#__PURE__*/_interopDefaultLegacy(isFunction);

function useSorter(props, _ref) {
  let {
    emit,
    slots
  } = _ref;
  const {
    sort,
    data
  } = VueCompositionAPI.toRefs(props);
  const originalData = VueCompositionAPI.ref();
  const [tSortInfo, setTSortInfo] = hooks_useDefaultValue["default"](sort, props.defaultSort, props.onSortChange, "sort", "sort-change");
  const [tData, setTData] = hooks_useDefaultValue["default"](data, [], props.onDataChange, "data", "data-change");
  const sorterFuncMap = VueCompositionAPI.computed(() => getSorterFuncMap(props.columns));
  const sortArray = VueCompositionAPI.computed(() => {
    const sort2 = tSortInfo.value;
    if (!sort2) return [];
    return Array.isArray(sort2) ? sort2 : [sort2];
  });
  const sortMap = VueCompositionAPI.computed(() => {
    const sortMap2 = {};
    sortArray.value.forEach((info, index) => {
      const {
        sortBy
      } = info;
      sortMap2[sortBy] = {
        index,
        ...info
      };
    });
    return sortMap2;
  });
  function getSorterFuncMap(columns) {
    let map = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    for (let i = 0, len = columns.length; i < len; i++) {
      var _col$children;
      const 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) {
    const sort2 = sortInfo;
    if (!Object.keys(sorterFuncMap.value).length) return;
    if (!originalData.value) originalData.value = tData.value;
    const isEmptyArraySort = !sort2 || Array.isArray(sort2) && !sort2.length;
    const isEmptyObjectSort = !Array.isArray(sort2) && !(sort2 !== null && sort2 !== void 0 && sort2.sortBy);
    if (isEmptyArraySort || isEmptyObjectSort) {
      setTData(originalData.value, {
        trigger: "sort"
      });
      return originalData.value;
    }
    const formattedSort = Array.isArray(sort2) ? sort2 : [sort2];
    const newData = tData.value.slice().sort((a, b) => {
      let sortResult = 0;
      for (let i = 0, len = formattedSort.length; i < len; i++) {
        const item = formattedSort[i];
        const 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;
    let sortInfo;
    if (props.multipleSort) {
      sortInfo = getMultipleNextSort(col, p);
    } else {
      const sort2 = Array.isArray(tSortInfo.value) ? tSortInfo.value[0] : tSortInfo.value;
      sortInfo = getSingleNextSort(col, sort2, p);
    }
    const newData = handleDataSort(sortInfo);
    const currentData = newData || tData.value;
    const currentDataSource = currentData;
    setTSortInfo(sortInfo, {
      currentDataSource,
      col
    });
    (_props$onChange = props.onChange) === null || _props$onChange === void 0 ? void 0 : _props$onChange.call(props, {
      sorter: sortInfo
    }, {
      currentData,
      trigger: "sorter"
    });
    emit("change", {
      sorter: sortInfo
    }, {
      currentData,
      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) {
    const sort2 = tSortInfo.value;
    if (!Array.isArray(sort2)) return;
    const {
      colKey
    } = col;
    const result = [...sort2];
    for (let i = 0, len = sort2.length; i < len; i++) {
      if (sort2[i].sortBy === colKey) {
        const 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;
    let {
      col
    } = _ref2;
    if (!col.sorter) return null;
    const 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 h(components_table_core_sorterButton["default"], helper.helper([{
      "scopedSlots": {
        sortIcon: slots.sortIcon
      }
    }, {
      "props": sorterButtonsProps
    }, {}, {
      "on": {
        "sort-icon-click": (_, p) => handleSortHeaderClick(col, p)
      }
    }]));
  }
  return {
    renderSortIcon
  };
}

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