"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const util = require("../util.js");
const vue = require("vue");
function useExpand(watcherData) {
  const instance = vue.getCurrentInstance();
  const defaultExpandAll = vue.ref(false);
  const expandRows = vue.ref([]);
  const canRowExpand = (row, index) => {
    const expandableFn = instance.store.states.rowExpandable.value;
    return (expandableFn == null ? void 0 : expandableFn(row, index)) ?? true;
  };
  const updateExpandRows = () => {
    const data = watcherData.data.value || [];
    const rowKey = watcherData.rowKey.value;
    if (defaultExpandAll.value) expandRows.value = instance.store.states.rowExpandable.value ? data.filter(canRowExpand) : data.slice();
    else if (rowKey) {
      const expandRowsMap = util.getKeysMap(expandRows.value, rowKey);
      expandRows.value = data.filter((row, index) => {
        return !!expandRowsMap[util.getRowIdentity(row, rowKey)] && canRowExpand(row, index);
      });
    } else expandRows.value = [];
  };
  const toggleRowExpansion = (row, expanded) => {
    const rowIndex = (watcherData.data.value || []).indexOf(row);
    if (rowIndex > -1 && !canRowExpand(row, rowIndex)) return;
    if (util.toggleRowStatus(expandRows.value, row, expanded, void 0, void 0, void 0, watcherData.rowKey.value)) instance.emit("expand-change", row, expandRows.value.slice());
  };
  const setExpandRowKeys = (rowKeys) => {
    instance.store.assertRowKey();
    const data = watcherData.data.value || [];
    const rowKey = watcherData.rowKey.value;
    const keysMap = util.getKeysMap(data, rowKey);
    expandRows.value = rowKeys.reduce((prev, cur) => {
      const info = keysMap[cur];
      if (info && canRowExpand(info.row, info.index)) prev.push(info.row);
      return prev;
    }, []);
  };
  const isRowExpanded = (row) => {
    const rowKey = watcherData.rowKey.value;
    if (rowKey) return !!util.getKeysMap(expandRows.value, rowKey)[util.getRowIdentity(row, rowKey)];
    return expandRows.value.includes(row);
  };
  return {
    updateExpandRows,
    toggleRowExpansion,
    setExpandRowKeys,
    isRowExpanded,
    states: {
      expandRows,
      defaultExpandAll
    }
  };
}
exports.default = useExpand;
