import { defineComponent, useSlots, useAttrs, computed, ref, resolveComponent, createElementBlock, openBlock, mergeProps, unref, renderSlot, createVNode, createSlots, withCtx, normalizeProps, guardReactiveProps, createCommentVNode, createElementVNode, normalizeClass, normalizeStyle, createTextVNode, toDisplayString, createBlock, Fragment, renderList } from 'vue';
import '../../../utils/index.mjs';
import { omit } from 'lodash-es';
import { treeEmits, treeProps } from './tree.mjs';
import { createNamespace } from '../../../utils/create-namespace.mjs';

"use strict";
const _hoisted_1 = ["onClick"];
var _sfc_main = /* @__PURE__ */ defineComponent({
  ...{ name: "LlTree", inheritAttrs: false },
  __name: "tree",
  props: treeProps,
  emits: treeEmits,
  setup(__props, { expose: __expose, emit: __emit }) {
    const slots = useSlots();
    const attrs = useAttrs();
    const props = __props;
    const emits = __emit;
    const bem = createNamespace("tree");
    const containerAttrs = computed(() => ({
      class: attrs.class,
      style: attrs.style
    }));
    const componentAttrs = computed(() => omit(attrs, ["class", "style"]));
    const filterSlots = computed(() => {
      return Object.keys(slots).filter(
        (name) => name !== "switcherIcon" && name !== "title" && name !== "header"
      );
    });
    const fieldKey = computed(() => props.fieldNames?.["key"] || "key");
    const fieldTitle = computed(() => props.fieldNames?.["title"] || "title");
    const fieldChildren = computed(
      () => props.fieldNames?.["children"] || "children"
    );
    const initSelectedKeys = ref([]);
    const initExpandedKeys = ref([]);
    const initCheckedKeys = ref([]);
    const newSelectedKeys = computed({
      get: () => props.selectedKeys || initSelectedKeys.value,
      set(val) {
        initSelectedKeys.value = val;
        emits("update:selectedKeys", val);
      }
    });
    const newExpandedKeys = computed({
      get: () => props.expandedKeys || initExpandedKeys.value,
      set(val) {
        initExpandedKeys.value = val;
        emits("update:expandedKeys", val);
      }
    });
    const newCheckedKeys = computed({
      get: () => props.checkedKeys || initCheckedKeys.value,
      set: (val) => {
        initCheckedKeys.value = val;
        emits("update:checkedKeys", val);
      }
    });
    const onExpand = (keys, e) => {
      emits("expand", keys, e);
    };
    const onSelect = (keys, e) => {
      emits("select", keys, e);
    };
    const onCheck = (keys, e) => {
      emits("check", keys, e);
    };
    const nodeClick = (data) => {
      if (!props.clickRowExpand) return;
      const state = newExpandedKeys.value.includes(data[fieldKey.value]);
      const keys = state ? newExpandedKeys.value.filter((k) => k !== data[fieldKey.value]) : [...newExpandedKeys.value, data[fieldKey.value]];
      newExpandedKeys.value = keys;
      onExpand(keys, { expanded: !state, node: data });
      emits("nodeClick", data);
    };
    const expandAll = () => {
      newExpandedKeys.value = getAllNodeKeys();
      onExpand(newExpandedKeys.value);
    };
    const collapseAll = () => {
      newExpandedKeys.value = [];
      onExpand(newExpandedKeys.value);
    };
    const expandRoot = (key) => {
      if (!props.treeData?.length) return;
      const rootNode = props.treeData?.find((item) => item[fieldKey.value] === key);
      if (rootNode && !newExpandedKeys.value.includes(key)) {
        newExpandedKeys.value = [...newExpandedKeys.value, key];
      }
      onExpand(newExpandedKeys.value);
    };
    const collapseRoot = (key) => {
      if (newExpandedKeys.value.includes(key)) {
        newExpandedKeys.value = newExpandedKeys.value.filter((k) => k !== key);
      }
      onExpand(newExpandedKeys.value);
    };
    const expandAllRoots = () => {
      if (!props.treeData?.length) return;
      const rootKeys = props.treeData.map((item) => item[fieldKey.value]).filter(Boolean);
      const mergedKeys = [.../* @__PURE__ */ new Set([...newExpandedKeys.value, ...rootKeys])];
      newExpandedKeys.value = mergedKeys;
      onExpand(newExpandedKeys.value);
    };
    const collapseAllRoots = () => {
      if (!props.treeData?.length) {
        newExpandedKeys.value = [];
        return;
      }
      const rootKeys = props.treeData.map((item) => item[fieldKey.value]).filter(Boolean);
      newExpandedKeys.value = newExpandedKeys.value.filter(
        (key) => !rootKeys.includes(key)
      );
      onExpand(newExpandedKeys.value);
    };
    const selection = (key) => {
      if (props.multiple) {
        if (!newSelectedKeys.value.includes(key)) {
          newSelectedKeys.value = [...newSelectedKeys.value, key];
        }
      } else {
        newSelectedKeys.value = [key];
      }
      onSelect(newSelectedKeys.value);
    };
    const clearSelection = (key) => {
      if (newSelectedKeys.value.includes(key)) {
        newSelectedKeys.value = newSelectedKeys.value.filter((k) => k !== key);
      }
      onSelect(newSelectedKeys.value);
    };
    const checkedAll = () => {
      if (!props.treeData?.length) return;
      if (props.checkStrictly) {
        newCheckedKeys.value = {
          checked: getAllNodeKeys(),
          halfChecked: []
        };
      } else {
        newCheckedKeys.value = getAllNodeKeys();
      }
      onCheck(newCheckedKeys.value);
    };
    const deselectAll = () => {
      if (props.checkStrictly) {
        newCheckedKeys.value = {
          checked: [],
          halfChecked: []
        };
      } else {
        newCheckedKeys.value = [];
      }
      onCheck(newCheckedKeys.value);
    };
    const getAllNodeKeys = () => {
      if (!props.treeData?.length) return [];
      const allKeys = [];
      const collectKeys = (nodes) => {
        nodes.forEach((node) => {
          if (node[fieldKey.value] != null) {
            allKeys.push(node[fieldKey.value]);
          }
          if (node[fieldChildren.value]?.length) {
            collectKeys(node[fieldChildren.value]);
          }
        });
      };
      collectKeys(props.treeData);
      return [...new Set(allKeys)];
    };
    const findNode = (key) => {
      const find = (nodes) => {
        for (const node of nodes) {
          if (node[fieldKey.value] === key) return node;
          if (node[fieldChildren.value]?.length) {
            const found = find(node[fieldChildren.value]);
            if (found) return found;
          }
        }
        return null;
      };
      return find(props.treeData || []);
    };
    __expose({
      expandAll,
      // 展开所有
      collapseAll,
      // 收起所有
      expandRoot,
      // 展开指定根目录
      collapseRoot,
      // 收起指定根目录
      expandAllRoots,
      // 展开所有根目录
      collapseAllRoots,
      // 收起所有根目录
      selection,
      // 选中指定节点
      clearSelection,
      // 取消选中指定节点
      checkedAll,
      // 全选
      deselectAll,
      // 取消全选
      getAllNodeKeys,
      //获取所有节点的key
      findNode
      // 查找指定节点（辅助函数）
    });
    return (_ctx, _cache) => {
      const _component_ll_icon = resolveComponent("ll-icon");
      const _component_a_tree = resolveComponent("a-tree");
      return openBlock(), createElementBlock(
        "div",
        mergeProps({
          class: unref(bem).b("wrapper")
        }, containerAttrs.value),
        [
          renderSlot(_ctx.$slots, "header"),
          createVNode(_component_a_tree, mergeProps(componentAttrs.value, {
            "selected-keys": newSelectedKeys.value,
            "onUpdate:selectedKeys": _cache[0] || (_cache[0] = ($event) => newSelectedKeys.value = $event),
            "checked-keys": newCheckedKeys.value,
            "onUpdate:checkedKeys": _cache[1] || (_cache[1] = ($event) => newCheckedKeys.value = $event),
            "expanded-keys": !_ctx.expandedKeys && _ctx.defaultExpandAll ? void 0 : newExpandedKeys.value,
            "tree-data": _ctx.treeData,
            class: [unref(bem).b(), unref(bem).is(_ctx.height && _ctx.virtual ? "virtual" : "")],
            "default-expand-all": _ctx.defaultExpandAll,
            multiple: _ctx.multiple,
            "field-names": _ctx.fieldNames,
            virtual: _ctx.virtual,
            height: _ctx.height,
            "check-strictly": _ctx.checkStrictly,
            "load-data": _ctx.enableLazyLoad ? _ctx.loadData : void 0,
            "loaded-keys": _ctx.cacheLoadedData ? _ctx.loadedKeys : [],
            "show-line": _ctx.showLine && { showLeafIcon: _ctx.showLeafIcon },
            "onUpdate:expandedKeys": _cache[2] || (_cache[2] = (v) => newExpandedKeys.value = v),
            onExpand,
            onSelect,
            onCheck
          }), createSlots({
            switcherIcon: withCtx((data) => [
              renderSlot(_ctx.$slots, "switcherIcon", normalizeProps(guardReactiveProps(data)), () => [
                createCommentVNode(" \u5C55\u5F00\u72B6\u6001\u56FE\u6807 "),
                data.expanded ? (openBlock(), createBlock(_component_ll_icon, {
                  key: 0,
                  "icon-name": _ctx.expandIcon?.iconName || "icon-solid-arrow-down",
                  size: _ctx.expandIcon?.size || 12,
                  color: _ctx.expandIcon?.color
                }, null, 8, ["icon-name", "size", "color"])) : (openBlock(), createElementBlock(
                  Fragment,
                  { key: 1 },
                  [
                    createCommentVNode(" \u6536\u8D77\u72B6\u6001\u56FE\u6807 "),
                    createVNode(_component_ll_icon, {
                      "icon-name": _ctx.collapseIcon?.iconName || "icon-solid-arrow-right",
                      size: _ctx.collapseIcon?.size || 12,
                      color: _ctx.collapseIcon?.color
                    }, null, 8, ["icon-name", "size", "color"])
                  ],
                  2112
                  /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */
                ))
              ])
            ]),
            title: withCtx((data) => [
              renderSlot(_ctx.$slots, "title", normalizeProps(guardReactiveProps(data)), () => [
                createCommentVNode(" \u8282\u70B9\u5185\u5BB9 "),
                createElementVNode("div", {
                  class: normalizeClass(unref(bem).e("node-content")),
                  onClick: ($event) => nodeClick(data)
                }, [
                  createCommentVNode(" \u56FE\u6807 "),
                  _ctx.showIcon && data.dataRef.icon ? (openBlock(), createElementBlock(
                    "div",
                    {
                      key: 0,
                      class: normalizeClass(unref(bem).e("title-icon"))
                    },
                    [
                      renderSlot(_ctx.$slots, "title-icon", normalizeProps(guardReactiveProps(data)), () => [
                        createVNode(_component_ll_icon, {
                          "icon-name": data.dataRef.icon,
                          size: _ctx.iconSize,
                          color: _ctx.iconColor
                        }, null, 8, ["icon-name", "size", "color"])
                      ])
                    ],
                    2
                    /* CLASS */
                  )) : createCommentVNode("v-if", true),
                  createCommentVNode(" \u663E\u793A\u6587\u672C "),
                  createElementVNode(
                    "div",
                    {
                      class: normalizeClass(unref(bem).e("title-text")),
                      style: normalizeStyle({
                        color: _ctx.textColor,
                        fontSize: `${_ctx.textSize}px`
                      })
                    },
                    [
                      renderSlot(_ctx.$slots, "title-text", normalizeProps(guardReactiveProps(data)), () => [
                        createTextVNode(
                          toDisplayString(data.dataRef[fieldTitle.value]),
                          1
                          /* TEXT */
                        )
                      ])
                    ],
                    6
                    /* CLASS, STYLE */
                  ),
                  createCommentVNode(" \u64CD\u4F5C\u533A "),
                  _ctx.enableOperate ? (openBlock(), createElementBlock(
                    "div",
                    {
                      key: 1,
                      class: normalizeClass(unref(bem).e("operate"))
                    },
                    [
                      renderSlot(_ctx.$slots, "operate", normalizeProps(guardReactiveProps(data)))
                    ],
                    2
                    /* CLASS */
                  )) : createCommentVNode("v-if", true)
                ], 10, _hoisted_1)
              ])
            ]),
            _: 2
            /* DYNAMIC */
          }, [
            renderList(Object.keys(filterSlots.value), (item) => {
              return {
                name: item,
                fn: withCtx((data) => [
                  renderSlot(_ctx.$slots, item, normalizeProps(guardReactiveProps(data || {})))
                ])
              };
            })
          ]), 1040, ["selected-keys", "checked-keys", "expanded-keys", "tree-data", "class", "default-expand-all", "multiple", "field-names", "virtual", "height", "check-strictly", "load-data", "loaded-keys", "show-line"])
        ],
        16
        /* FULL_PROPS */
      );
    };
  }
});

export { _sfc_main as default };
//# sourceMappingURL=tree.vue2.mjs.map
