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

import { toRefs, ref, computed, watch, onUnmounted } from '@vue/composition-api';
import { AddRectangleIcon, MinusRectangleIcon } from '@ldesign/icons-vue';
import cloneDeep from 'lodash/cloneDeep';
import get from 'lodash/get';
import { _ as _defineProperty } from '../../../chunks/defineProperty-838e4192.js';
import { g as get_1 } from '../../../chunks/get-5e1abd10.js';
import { l as log } from '../../../chunks/log.js';
import { i as isRowSelectedDisabled } from '../../../chunks/utils3.js';
import '../../../chunks/isArray-cd7357b9.js';
import '../../../chunks/isSymbol-a38a5184.js';
import '../../../chunks/isObjectLike-c22c7e3b.js';
import '../../../chunks/_commonjsHelpers-2e6815bd.js';
import '../../../chunks/isFunction-91acade7.js';
import '../../../chunks/isNumber-c4eb560e.js';
import { renderCell } from '../core/tr.js';
import { useConfig } from '../../config-provider/useConfig.js';
import { useLNodeDefault } from '../../../hooks/lnode.js';
import { useGlobalIcon } from '../../../hooks/use-global-icon.js';
import useClassName from './useClassName.js';
import '../../../chunks/helper.js';
import '../../../chunks/_commonjsHelpers.js';
import 'lodash/isFunction';
import 'lodash/upperFirst';
import 'lodash/isString';
import 'lodash/pick';
import '../../../hooks/use-lazy-load.js';
import '../../../chunks/observe.js';
import '../utils.js';
import 'lodash/isObject';
import './useFixed.js';
import 'lodash/debounce';
import '../../../chunks/index.js';
import '../../../chunks/helper2.js';
import '../../../utils/dom.js';
import 'vue';
import 'raf';
import '../../../utils/easing.js';
import '../props.js';
import './useRowspanAndColspan.js';
import '../core/ellipsis.js';
import '../../../utils/render-node.js';
import 'lodash';
import '../../tooltip/index.js';
import '../../../utils/map-props.js';
import '../../../utils/with-install.js';
import '../../../config.js';
import '../../tooltip/tooltip.js';
import '../../popup/props.js';
import '../../popup/popup.js';
import '@popperjs/core';
import '../../../chunks/set-style.js';
import '../../../utils/helper.js';
import 'lodash/camelCase';
import '../../config-provider/config-receiver.js';
import 'lodash/mergeWith';
import '../../config-provider/context.js';
import '../../../chunks/zh_CN.js';
import '../../config-provider/type.js';
import '../../../utils/mixins.js';
import '../../popup/container.js';
import '../../tooltip/props.js';
import '../../tooltip/style/css.js';
import '../../tooltip/type.js';
import 'lodash/isEmpty';
import 'lodash/kebabCase';
import '../../../hooks/render-lnode.js';
import '../../../hooks/use-config.js';

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), true).forEach(function (key) {
      _defineProperty(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 TABLE_TREE_ERROR_CODE_NOT_SAME_LEVEL = {
  code: 1001,
  reason: "The same level of rows can not be swapped."
};
class TableTreeStore {
  constructor() {
    _defineProperty(this, "treeDataMap", /* @__PURE__ */new Map());
    _defineProperty(this, "expandAllRowIndex", void 0);
    this.treeDataMap = /* @__PURE__ */new Map();
  }
  initialTreeStore(dataSource, columns, keys) {
    var _this$treeDataMap;
    (_this$treeDataMap = this.treeDataMap) === null || _this$treeDataMap === void 0 ? void 0 : _this$treeDataMap.clear();
    this.initialTreeDataMap(this.treeDataMap, dataSource, columns[0], keys);
  }
  getAllUniqueKeys(data, keys) {
    var arr = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : [];
    for (var i = 0, len = data.length; i < len; i++) {
      var item = data[i];
      arr.push(get_1(item, keys.rowKey));
      var children = get_1(item, keys.childrenKey);
      if (children !== null && children !== void 0 && children.length) this.getAllUniqueKeys(children, keys, arr);
    }
    return arr;
  }
  toggleExpandData(p, dataSource, keys) {
    if (!p) {
      log.error("EnhancedTable", "the node you want to toggleExpand doest not exist in `data`");
      return dataSource;
    }
    var rowValue = get_1(p.row, keys.rowKey);
    if (rowValue === void 0) {
      log.error("EnhancedTable", "`rowKey` could be wrong, can not get rowValue from `data` by `rowKey`.");
      return [];
    }
    var childrenNodes = get_1(p.row, keys.childrenKey);
    if (childrenNodes === true) return dataSource;
    var r = this.treeDataMap.get(rowValue);
    r.rowIndex = p.rowIndex;
    r.expanded = !r.expanded;
    this.treeDataMap.set(rowValue, r);
    return this.updateExpandRow(r, dataSource, keys);
  }
  updateExpandRow(changeRow, dataSource, keys) {
    var {
      row,
      rowIndex,
      expanded
    } = changeRow;
    var {
      treeDataMap
    } = this;
    var childrenNodes = get_1(row, keys.childrenKey);
    if (!row || !childrenNodes) return dataSource;
    if (expanded) {
      updateChildrenRowState(treeDataMap, changeRow, expanded, keys);
      updateRowExpandLength(treeDataMap, row, childrenNodes.length, "expand", keys);
      dataSource.splice.apply(dataSource, [rowIndex + 1, 0].concat(childrenNodes));
    } else {
      updateChildrenRowState(treeDataMap, changeRow, expanded, keys);
      var len = changeRow.expandChildrenLength || childrenNodes.length;
      updateRowExpandLength(treeDataMap, row, -1 * len, "fold", keys);
      dataSource.splice(rowIndex + 1, len);
    }
    updateRowIndex(treeDataMap, dataSource, {
      rowKey: keys.rowKey,
      minRowIndex: rowIndex + 1
    });
    return dataSource;
  }
  getData(key) {
    return this.treeDataMap.get(key);
  }
  updateData(rowValue, newRowData, dataSource, keys) {
    var newRowValue = get_1(newRowData, keys.rowKey);
    var rowState = this.treeDataMap.get(rowValue);
    if (!rowState || rowState.rowIndex === -1) {
      updateRowData(dataSource, rowValue, newRowData, {
        rowKey: keys.rowKey,
        childrenKey: keys.childrenKey
      });
      return -1;
    }
    if (get_1(newRowData, keys.childrenKey) === true) {
      var oldChildren = get_1(rowState.row, keys.childrenKey);
      if (oldChildren !== null && oldChildren !== void 0 && oldChildren.length) {
        for (var i = 0, len = oldChildren.length; i < len; i++) {
          var rowValue2 = get_1(oldChildren[i], keys.rowKey);
          var state = this.treeDataMap.get(rowValue2);
          if (state) this.treeDataMap.delete(rowValue2);
        }
      }
    }
    var currentRowIndex = rowState.rowIndex;
    rowState.row = newRowData;
    rowState.id = newRowValue;
    if (rowState.parent) {
      var siblings = get_1(rowState.parent.row, keys.childrenKey);
      var index = siblings.findIndex(item => get_1(item, keys.rowKey) === rowValue);
      siblings[index] = newRowData;
    }
    this.treeDataMap.set(newRowValue, rowState);
    if (rowValue !== newRowValue) this.treeDataMap.delete(rowValue);
    return currentRowIndex;
  }
  remove(key, dataSource, keys) {
    var r = this.treeDataMap.get(key);
    if (r && r.rowIndex >= 0) {
      var removeNumber = (r.expandChildrenLength || 0) + 1;
      dataSource.splice(r.rowIndex, removeNumber);
      if (r.parent) {
        var siblings = get_1(r.parent.row, keys.childrenKey);
        var index = siblings.findIndex(item => get_1(item, keys.rowKey) === key);
        siblings.splice(index, 1);
        updateRowExpandLength(this.treeDataMap, r.parent.row, -1 * removeNumber, "delete", keys);
      }
      this.treeDataMap.delete(key);
      updateRowIndex(this.treeDataMap, dataSource, {
        minRowIndex: r.rowIndex,
        rowKey: keys.rowKey,
        type: "remove"
      });
    } else {
      log.warn("EnhancedTable", "Do not remove this node, which is not appeared.");
    }
    return dataSource;
  }
  appendTo(rowValue, newData, dataSource, keys) {
    var state = this.treeDataMap.get(rowValue);
    if (!this.validateDataExist(state, rowValue)) return dataSource;
    var children = get_1(state.row, keys.childrenKey);
    var isShowNewNode = state.expanded || !(children !== null && children !== void 0 && children.length);
    var tmpData = Array.isArray(newData) ? newData : [newData];
    var newChildrenData = [];
    var firstNewChildrenIndex = -1;
    for (var i = 0, len = tmpData.length; i < len; i++) {
      var oneData = tmpData[i];
      var newRowValue = get_1(oneData, keys.rowKey);
      var mapState = this.treeDataMap.get(newRowValue);
      if (!this.validateDataDoubleExist(mapState, newRowValue)) {
        log.warn("Table", "Duplicated Data `".concat(newRowValue, "` has been removed."));
      } else {
        var rowIndex = isShowNewNode ? state.rowIndex + (state.expandChildrenLength || 0) + (i + 1) : -1;
        if (i === 0) firstNewChildrenIndex = rowIndex;
        var newState = {
          id: newRowValue,
          row: oneData,
          rowIndex,
          level: state.level + 1,
          expanded: false,
          expandChildrenLength: 0,
          disabled: false,
          path: [...state.path],
          parent: state
        };
        newState.path = newState.path.concat(newState);
        newChildrenData.push(oneData);
        this.treeDataMap.set(newRowValue, newState);
      }
    }
    if (!newChildrenData.length) return dataSource;
    if (children !== null && children !== void 0 && children.length) {
      state.row[keys.childrenKey] = state.row[keys.childrenKey].concat(newChildrenData);
    } else {
      state.row[keys.childrenKey] = newChildrenData;
      state.expanded = true;
    }
    if (isShowNewNode) {
      dataSource.splice(firstNewChildrenIndex, 0, ...newChildrenData);
      var newChildrenCount = newChildrenData.length || 1;
      updateRowExpandLength(this.treeDataMap, state.row, newChildrenCount, "insert", {
        rowKey: keys.rowKey,
        childrenKey: keys.childrenKey
      });
      updateRowIndex(this.treeDataMap, dataSource, {
        minRowIndex: firstNewChildrenIndex + newChildrenData.length - 1,
        rowKey: keys.rowKey,
        type: "add",
        count: 1
      });
    }
    return dataSource;
  }
  appendToRoot(newData, dataSource, keys) {
    var newDataSource = dataSource.concat(newData);
    var tmpNewData = Array.isArray(newData) ? newData : [newData];
    var dataSourceLen = dataSource.length;
    for (var i = 0, len = tmpNewData.length; i < len; i++) {
      var rowValue = get_1(tmpNewData[i], keys.rowKey);
      if (!rowValue) {
        log.error("Table", "`rowKey` could be wrong, can not get rowValue from `data` by `rowKey`.");
        continue;
      }
      var state = {
        id: rowValue,
        row: tmpNewData[i],
        rowIndex: dataSourceLen + i,
        level: 0,
        expanded: false,
        expandChildrenLength: 0,
        disabled: false
      };
      state.path = [state];
      this.treeDataMap.set(rowValue, state);
    }
    return newDataSource;
  }
  insertAfter(rowValue, newData, dataSource, keys) {
    return this.insert(rowValue, newData, dataSource, keys, "after");
  }
  insertBefore(rowValue, newData, dataSource, keys) {
    return this.insert(rowValue, newData, dataSource, keys, "before");
  }
  insert(rowValue, newData, dataSource, keys, type) {
    var state = this.treeDataMap.get(rowValue);
    if (!this.validateDataExist(state, rowValue)) return dataSource;
    var newRowValue = get_1(newData, keys.rowKey);
    var mapState = this.treeDataMap.get(newRowValue);
    if (!this.validateDataDoubleExist(mapState, newRowValue)) return dataSource;
    var rowIndex = type === "after" ? state.rowIndex + 1 : state.rowIndex;
    var newState = {
      id: newRowValue,
      row: newData,
      rowIndex,
      level: state.level,
      expanded: false,
      expandChildrenLength: 0,
      disabled: false,
      path: state.path.slice(0, -1),
      parent: state.parent
    };
    newState.path = newState.path.concat(newState);
    var dataIndex = type === "after" ? state.rowIndex + (state.expandChildrenLength + 1) : state.rowIndex;
    dataSource.splice(dataIndex, 0, newData);
    var distance = type === "after" ? 1 : 0;
    if (state.parent) {
      var childrenIndex = state.parent.row[keys.childrenKey].findIndex(t => rowValue === get_1(t, keys.rowKey));
      state.parent.row[keys.childrenKey].splice(childrenIndex + distance, 0, newData);
      updateRowExpandLength(this.treeDataMap, state.parent.row, 1, "insert", keys);
    }
    this.treeDataMap.set(newRowValue, newState);
    updateRowIndex(this.treeDataMap, dataSource, {
      rowKey: keys.rowKey,
      minRowIndex: state.rowIndex + 1,
      type: "add"
    });
    return dataSource;
  }
  swapData(dataSource, params, keys) {
    var startIndex = params.currentIndex;
    var endIndex = params.targetIndex;
    if (startIndex === endIndex) return {
      dataSource,
      result: true
    };
    var startRowValue = get_1(params.current, keys.rowKey);
    var endRowValue = get_1(params.target, keys.rowKey);
    var startState = this.treeDataMap.get(startRowValue);
    var endState = this.treeDataMap.get(endRowValue);
    if (startState.level !== endState.level) {
      return {
        dataSource,
        result: false,
        code: TABLE_TREE_ERROR_CODE_NOT_SAME_LEVEL.code,
        reason: TABLE_TREE_ERROR_CODE_NOT_SAME_LEVEL.reason
      };
    }
    var startLastIndex = startIndex + startState.expandChildrenLength + 1;
    var endLastIndex = endIndex + endState.expandChildrenLength + 1;
    var startRowList = dataSource.slice(startIndex, startLastIndex);
    var endRowList = dataSource.slice(endIndex, endLastIndex);
    if (startIndex > endIndex) {
      var middleRowList = dataSource.slice(endLastIndex, startIndex);
      var allSwapList = startRowList.concat(endRowList, middleRowList);
      dataSource.splice(endIndex, allSwapList.length);
      dataSource.splice(endIndex, 0, ...allSwapList);
      updateRowIndex(this.treeDataMap, dataSource, {
        rowKey: keys.rowKey,
        minRowIndex: endIndex,
        maxRowIndex: startLastIndex
      });
    } else {
      var _middleRowList = dataSource.slice(startLastIndex, endIndex);
      var _allSwapList = _middleRowList.concat(endRowList, startRowList);
      dataSource.splice(startIndex, _allSwapList.length);
      dataSource.splice(startIndex, 0, ..._allSwapList);
      updateRowIndex(this.treeDataMap, dataSource, {
        rowKey: keys.rowKey,
        minRowIndex: startIndex,
        maxRowIndex: endLastIndex
      });
    }
    if (startState.parent) {
      var children = startState.parent.row[keys.childrenKey];
      var count = 0;
      var targetIndex = -1;
      var currentIndex = -1;
      for (var i = 0, len = children.length; i < len; i++) {
        if (get_1(children[i], keys.rowKey) === startRowValue) {
          targetIndex = i;
          count += 1;
        }
        if (get_1(children[i], keys.rowKey) === endRowValue) {
          currentIndex = i;
          count += 1;
        }
        if (count >= 2) break;
      }
      children[targetIndex] = params.target;
      children[currentIndex] = params.current;
    }
    return {
      dataSource,
      result: true
    };
  }
  expandAll(dataSource, keys) {
    var _this = this;
    this.expandAllRowIndex = 0;
    var expandLoop = function expandLoop2(dataSource2, keys2) {
      var newData = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : [];
      var parentExpanded = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false;
      var parent = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : null;
      for (var i = 0, len = dataSource2.length; i < len; i++) {
        var item = dataSource2[i];
        var rowValue = get_1(item, keys2.rowKey);
        var state = _this.treeDataMap.get(rowValue);
        var children = get_1(item, keys2.childrenKey);
        var originalExpanded = state.expanded;
        state.rowIndex = _this.expandAllRowIndex;
        if (children !== true && children !== null && children !== void 0 && children.length) state.expanded = true;
        state.expandChildrenLength = (children === null || children === void 0 ? void 0 : children.length) || 0;
        _this.expandAllRowIndex += 1;
        if (!parentExpanded) newData.push(item);
        _this.treeDataMap.set(rowValue, state);
        if (children !== null && children !== void 0 && children.length && !originalExpanded) {
          var tmpParent = parent;
          while ((_tmpParent = tmpParent) !== null && _tmpParent !== void 0 && _tmpParent.row) {
            var _tmpParent;
            tmpParent.expandChildrenLength += children.length;
            _this.treeDataMap.set(tmpParent.id, tmpParent);
            tmpParent = tmpParent.parent;
          }
          expandLoop2(children, keys2, newData, originalExpanded, state);
        }
      }
      return newData;
    };
    return expandLoop(dataSource, keys);
  }
  foldAll(dataSource, keys) {
    var newData = [];
    for (var i = 0, len = dataSource.length; i < len; i++) {
      var item = dataSource[i];
      var rowValue = get_1(item, keys.rowKey);
      var state = this.treeDataMap.get(rowValue);
      state.rowIndex = state.level === 0 ? i : -1;
      state.expanded = false;
      state.expandChildrenLength = 0;
      if (state.level === 0) newData.push(item);
      var children = get_1(item, keys.childrenKey);
      if (children !== null && children !== void 0 && children.length) this.foldAll(children, keys);
    }
    return newData;
  }
  getTreeNode(dataSource, keys) {
    var treeData = [];
    for (var i = 0, len = dataSource.length; i < len; i++) {
      var item = dataSource[i];
      var rowValue = get_1(item, keys.rowKey);
      var state = this.treeDataMap.get(rowValue);
      if (state.level === 0) treeData.push(item);
    }
    return treeData;
  }
  getTreeExpandedRow(dataSource, keys) {
    var type = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "data";
    var arr = [];
    dataSource.forEach(item => {
      var rowValue = get_1(item, keys.rowKey);
      var rowState = this.treeDataMap.get(rowValue);
      if (!rowState.expanded) return;
      if (type === "unique") arr.push(rowValue);else if (type === "data") arr.push(item);else arr.push(rowState);
    });
    return arr;
  }
  initialTreeDataMap(treeDataMap, dataSource, column, keys) {
    var level = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : 0;
    var parent = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : null;
    for (var i = 0, len = dataSource.length; i < len; i++) {
      var item = dataSource[i];
      var rowValue = get_1(item, keys.rowKey);
      if (rowValue === void 0) {
        log.error("EnhancedTable", "`rowKey` could be wrong, can not get rowValue from `data` by `rowKey`.");
        return;
      }
      var children = get_1(item, keys.childrenKey);
      var state = {
        id: rowValue,
        row: item,
        rowIndex: level === 0 ? i : -1,
        level,
        expanded: false,
        expandChildrenLength: 0,
        disabled: isRowSelectedDisabled(column, item, i),
        parent
      };
      state.path = parent ? parent.path.concat(state) : [state];
      treeDataMap.set(rowValue, state);
      if (children !== null && children !== void 0 && children.length) this.initialTreeDataMap(treeDataMap, children, column, keys, level + 1, state);
    }
  }
  updateDisabledState(dataSource, column, keys) {
    for (var i = 0, len = dataSource.length; i < len; i++) {
      var item = dataSource[i];
      var rowValue = get_1(item, keys.rowKey);
      if (rowValue === void 0) {
        log.error("EnhancedTable", "`rowKey` could be wrong, can not get rowValue from `data` by `rowKey`.");
        return;
      }
      var state = this.treeDataMap.get(rowValue);
      state.disabled = isRowSelectedDisabled(column, item, i);
      this.treeDataMap.set(rowValue, state);
      var children = get_1(item, keys.childrenKey);
      if (children !== null && children !== void 0 && children.length) this.updateDisabledState(children, column, keys);
    }
  }
  validateDataExist(state, rowValue) {
    if (!state) {
      log.warn("EnhancedTable", "".concat(rowValue, " does not exist."));
      return false;
    }
    return true;
  }
  validateDataDoubleExist(state, rowValue) {
    if (state) {
      log.warn("EnhancedTable", "Duplicated Key. ".concat(rowValue, " already exists."));
      return false;
    }
    return true;
  }
}
function updateRowExpandLength(treeDataMap, row, distance, type, keys) {
  var tmp = row;
  while (tmp) {
    var _state$parent;
    var state = treeDataMap.get(get_1(tmp, keys.rowKey));
    var expandLen = (state.expandChildrenLength || 0) + distance;
    state.expandChildrenLength = Math.max(0, expandLen);
    tmp = state === null || state === void 0 ? void 0 : (_state$parent = state.parent) === null || _state$parent === void 0 ? void 0 : _state$parent.row;
  }
  if (type === "fold") clearRowExpandLength(treeDataMap, row, keys);
}
function clearRowExpandLength(treeDataMap, row, keys) {
  var children = get_1(row, keys.childrenKey);
  if (children !== null && children !== void 0 && children.length) {
    children.forEach(item => {
      var state = treeDataMap.get(get_1(item, keys.rowKey));
      if (!state) return;
      state.expandChildrenLength = 0;
      clearRowExpandLength(treeDataMap, state.row, keys);
    });
  }
}
function updateChildrenRowState(treeDataMap, rowState, expanded, keys) {
  var {
    row,
    rowIndex
  } = rowState;
  var childrenNodes = get_1(row, keys.childrenKey);
  childrenNodes.forEach((item, kidRowIndex) => {
    var rowValue = get_1(item, keys.rowKey);
    var index = expanded ? rowIndex + 1 + kidRowIndex : -1;
    var curState = treeDataMap.get(rowValue);
    var newState = _objectSpread(_objectSpread({}, curState), {}, {
      row: item,
      rowIndex: index,
      expanded: false,
      parent: rowState
    });
    treeDataMap.set(rowValue, newState);
    if (!expanded) {
      var children = get_1(item, keys.childrenKey);
      if (children !== null && children !== void 0 && children.length) {
        updateChildrenRowState(treeDataMap, _objectSpread(_objectSpread({}, newState), {}, {
          rowIndex: -1,
          expanded: false
        }), expanded, keys);
      }
    }
  });
}
function updateRowData(data, key, newData, keys) {
  for (var i = 0, len = data.length; i < len; i++) {
    var item = data[i];
    if (get_1(item, keys.rowKey) === key) {
      data[i] = newData;
      return;
    }
    var children = get_1(item, keys.childrenKey) || [];
    if (children !== null && children !== void 0 && children.length) updateRowData(children, key, newData, keys);
  }
}
function updateRowIndex(treeDataMap, dataSource, extra) {
  var start = extra.minRowIndex || 0;
  var end = extra.maxRowIndex || dataSource.length;
  for (var rowIndex = start; rowIndex < end; rowIndex++) {
    var item = dataSource[rowIndex];
    var state = treeDataMap.get(get_1(item, extra.rowKey));
    if (!state) log.warn("Table", "tree map went wrong");
    state.rowIndex = rowIndex + ((extra === null || extra === void 0 ? void 0 : extra.count) || 1) - 1;
  }
}

function useTreeData(props, context) {
  const {
    data,
    columns
  } = toRefs(props);
  const {
    t,
    global
  } = useConfig("table");
  const {
    AddRectangleIcon: AddRectangleIcon$1,
    MinusRectangleIcon: MinusRectangleIcon$1
  } = useGlobalIcon({
    AddRectangleIcon: AddRectangleIcon,
    MinusRectangleIcon: MinusRectangleIcon
  });
  const store = ref(new TableTreeStore());
  const treeNodeCol = ref();
  const dataSource = ref([]);
  const {
    tableTreeClasses
  } = useClassName();
  const renderTNode = useLNodeDefault();
  const rowDataKeys = computed(() => {
    var _props$tree;
    return {
      rowKey: props.rowKey || "id",
      childrenKey: ((_props$tree = props.tree) === null || _props$tree === void 0 ? void 0 : _props$tree.childrenKey) || "children"
    };
  });
  const checkedColumn = computed(() => columns.value.find(col => col.colKey === "row-select"));
  watch(checkedColumn, column => {
    if (!store.value || !checkedColumn.value) return;
    store.value.updateDisabledState(dataSource.value, column, rowDataKeys.value);
  });
  function getFoldIcon(h, context2) {
    const params = {
      ...context2,
      type: "fold"
    };
    const defaultFoldIcon = t(global.value.treeExpandAndFoldIcon, h, params) || h(MinusRectangleIcon$1);
    return renderTNode("treeExpandAndFoldIcon", {
      defaultNode: defaultFoldIcon,
      params
    });
  }
  function getExpandIcon(h, context2) {
    const params = {
      ...context2,
      type: "expand"
    };
    const defaultExpandIcon = t(global.value.treeExpandAndFoldIcon, h, params) || h(AddRectangleIcon$1);
    return renderTNode("treeExpandAndFoldIcon", {
      defaultNode: defaultExpandIcon,
      params
    });
  }
  const uniqueKeys = computed(() => {
    var _store$value, _store$value$getAllUn;
    return ((_store$value = store.value) === null || _store$value === void 0 ? void 0 : (_store$value$getAllUn = _store$value.getAllUniqueKeys(data.value, rowDataKeys.value)) === null || _store$value$getAllUn === void 0 ? void 0 : _store$value$getAllUn.join()) || "";
  });
  watch([uniqueKeys], () => {
    if (!data.value) return [];
    if (!props.tree) {
      dataSource.value = data.value;
      return;
    }
    resetData(data.value);
  }, {
    immediate: true
  });
  onUnmounted(() => {
    var _store$value$treeData;
    if (!props.tree) return;
    (_store$value$treeData = store.value.treeDataMap) === null || _store$value$treeData === void 0 ? void 0 : _store$value$treeData.clear();
    store.value = null;
  });
  watch(() => {
    var _props$tree2;
    return [columns, (_props$tree2 = props.tree) === null || _props$tree2 === void 0 ? void 0 : _props$tree2.treeNodeColumnIndex];
  }, () => {
    treeNodeCol.value = getTreeNodeColumnCol();
  }, {
    immediate: true
  });
  function resetData(data2) {
    var _props$tree3;
    let newVal = cloneDeep(data2);
    store.value.initialTreeStore(newVal, props.columns, rowDataKeys.value);
    if ((_props$tree3 = props.tree) !== null && _props$tree3 !== void 0 && _props$tree3.defaultExpandAll) newVal = store.value.expandAll(newVal, rowDataKeys.value);
    dataSource.value = newVal;
  }
  function getTreeNodeStyle(level) {
    var _props$tree4, _props$tree5;
    if (level === void 0) return;
    const indent = ((_props$tree4 = props.tree) === null || _props$tree4 === void 0 ? void 0 : _props$tree4.indent) === void 0 ? 24 : (_props$tree5 = props.tree) === null || _props$tree5 === void 0 ? void 0 : _props$tree5.indent;
    return indent ? {
      paddingLeft: `${level * indent || 1}px`
    } : {};
  }
  function toggleExpandData(p, trigger) {
    var _store$value2, _store$value2$treeDat, _props$onTreeExpandCh;
    dataSource.value = store.value.toggleExpandData(p, dataSource.value, rowDataKeys.value);
    const rowValue = get(p.row, rowDataKeys.value.rowKey);
    const rowState = (_store$value2 = store.value) === null || _store$value2 === void 0 ? void 0 : (_store$value2$treeDat = _store$value2.treeDataMap) === null || _store$value2$treeDat === void 0 ? void 0 : _store$value2$treeDat.get(rowValue);
    const params = {
      row: p.row,
      rowIndex: p.rowIndex,
      rowState,
      trigger
    };
    (_props$onTreeExpandCh = props.onTreeExpandChange) === null || _props$onTreeExpandCh === void 0 ? void 0 : _props$onTreeExpandCh.call(props, params);
    context.emit("tree-expand-change", params);
  }
  function getTreeNodeColumnCol() {
    var _props$tree6;
    const {
      columns: columns2
    } = props;
    let treeNodeColumnIndex = ((_props$tree6 = props.tree) === null || _props$tree6 === void 0 ? void 0 : _props$tree6.treeNodeColumnIndex) || 0;
    while ((_columns2$treeNodeCol = columns2[treeNodeColumnIndex]) !== null && _columns2$treeNodeCol !== void 0 && _columns2$treeNodeCol.type || ((_columns2$treeNodeCol2 = columns2[treeNodeColumnIndex]) === null || _columns2$treeNodeCol2 === void 0 ? void 0 : _columns2$treeNodeCol2.colKey) === "__EXPAND_ROW_ICON_COLUMN__") {
      var _columns2$treeNodeCol, _columns2$treeNodeCol2;
      treeNodeColumnIndex += 1;
    }
    return columns2[treeNodeColumnIndex];
  }
  function formatTreeColumn(col) {
    if (!props.tree || col.colKey !== treeNodeCol.value.colKey) return col;
    const newCol = {
      ...treeNodeCol.value
    };
    newCol.cell = (h, p) => {
      const cellInfo = renderCell({
        ...p,
        col: {
          ...treeNodeCol.value
        }
      }, context.slots, {
        cellEmptyContent: props.cellEmptyContent
      });
      const currentState = store.value.treeDataMap.get(get(p.row, rowDataKeys.value.rowKey));
      const colStyle = getTreeNodeStyle(currentState === null || currentState === void 0 ? void 0 : currentState.level);
      const classes = {
        [tableTreeClasses.inlineCol]: !!col.ellipsis
      };
      const childrenNodes = get(p.row, rowDataKeys.value.childrenKey);
      if (childrenNodes && Array.isArray(childrenNodes) || childrenNodes === true) {
        var _store$value$treeData2;
        const iconNode = (_store$value$treeData2 = store.value.treeDataMap.get(get(p.row, rowDataKeys.value.rowKey))) !== null && _store$value$treeData2 !== void 0 && _store$value$treeData2.expanded ? getFoldIcon(h, p) : getExpandIcon(h, p);
        return h("div", {
          "class": [tableTreeClasses.col, classes],
          "style": colStyle
        }, [!!(childrenNodes.length || childrenNodes === true) && h("span", {
          "class": tableTreeClasses.icon,
          "on": {
            "click": () => toggleExpandData(p, "expand-fold-icon")
          }
        }, [iconNode]), cellInfo]);
      }
      return h("div", {
        "style": colStyle,
        "class": [classes, tableTreeClasses.leafNode]
      }, [h("span", {
        "class": tableTreeClasses.icon
      }), cellInfo]);
    };
    if (newCol.ellipsis === true) newCol.ellipsis = (h, p) => renderCell({
      ...p,
      col: {
        ...treeNodeCol.value
      }
    }, context.slots);
    return newCol;
  }
  function setData(key, newRowData) {
    const rowIndex = store.value.updateData(key, newRowData, dataSource.value, rowDataKeys.value);
    const newData = [...dataSource.value];
    newData[rowIndex] = newRowData;
    dataSource.value = newData;
  }
  function getData(key) {
    return store.value.getData(key);
  }
  function remove(key) {
    dataSource.value = [...store.value.remove(key, dataSource.value, rowDataKeys.value)];
  }
  function appendTo() {
    let key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
    let newData = arguments.length > 1 ? arguments[1] : undefined;
    if (!key) {
      dataSource.value = store.value.appendToRoot(newData, dataSource.value, rowDataKeys.value);
      return;
    }
    dataSource.value = [...store.value.appendTo(key, newData, dataSource.value, rowDataKeys.value)];
  }
  function insertAfter(rowValue, newData) {
    dataSource.value = [...store.value.insertAfter(rowValue, newData, dataSource.value, rowDataKeys.value)];
  }
  function insertBefore(rowValue, newData) {
    dataSource.value = [...store.value.insertBefore(rowValue, newData, dataSource.value, rowDataKeys.value)];
  }
  function expandAll() {
    dataSource.value = [...store.value.expandAll(dataSource.value, rowDataKeys.value)];
  }
  function foldAll() {
    dataSource.value = [...store.value.foldAll(dataSource.value, rowDataKeys.value)];
  }
  function swapData(params) {
    const r = store.value.swapData(dataSource.value, params, rowDataKeys.value);
    if (r.result) {
      dataSource.value = [...r.dataSource];
    } else {
      var _props$onAbnormalDrag;
      const params2 = {
        code: r.code,
        reason: r.reason
      };
      (_props$onAbnormalDrag = props.onAbnormalDragSort) === null || _props$onAbnormalDrag === void 0 ? void 0 : _props$onAbnormalDrag.call(props, params2);
      context.emit("abnormal-drag-sort", params2);
    }
  }
  function getTreeNode() {
    return store.value.getTreeNode(dataSource.value, rowDataKeys.value);
  }
  function getTreeExpandedRow() {
    let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "data";
    return store.value.getTreeExpandedRow(dataSource.value, rowDataKeys.value, type);
  }
  return {
    store,
    rowDataKeys,
    dataSource,
    swapData,
    setData,
    getData,
    remove,
    appendTo,
    insertAfter,
    insertBefore,
    formatTreeColumn,
    toggleExpandData,
    expandAll,
    foldAll,
    getTreeNode,
    resetData,
    getTreeExpandedRow
  };
}

export { useTreeData as default };
//# sourceMappingURL=useTreeData.js.map
