<template>
  <a-tree
    :tree-data="treeData" :checkable="isShowCheck" :expanded-keys="expandedKeys"
    :checked-keys="checkedKeys" :selected-keys="selectedKeys"
    :field-names="{ children: 'childrenDatas', key: 'id', title: 'text' }" @expand="handleExpand"
    @check="handleCheck"
  />
  <!-- @select="handleSelect" -->
</template>

<script>
export default {
  name: 'TreeViewNode',
  props: {
    node: {
      type: Object,
      default: () => ({}),
    },
    isShowCheck: {
      type: Boolean,
      default: false,
    },
    isRoot: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['nodeExpand', 'nodeSelect'],
  data() {
    return {
      expandedKeys: [],
      checkedKeys: [],
      selectedKeys: [],
    };
  },
  computed: {
    treeData() {
      return this.isRoot ? [this.node] : this.node.childrenDatas || [];
    },
  },
  watch: {
    node: {
      handler(newVal) {
        if (newVal.selected) {
          this.checkedKeys = [newVal.id];
        } else {
          this.checkedKeys = this.collectSelectedIds(newVal.childrenDatas || []);
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    handleExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      const node = this.findNode(expandedKeys[expandedKeys.length - 1]);
      this.$emit('nodeExpand', node);
    },
    handleCheck(checkedKeys, { node }) {
    //   this.checkedKeys = checkedKeys;
      this.$emit('nodeSelect', node.dataRef);
    },
    handleSelect(selectedKeys, { node }) {
    //   this.selectedKeys = selectedKeys;
      this.$emit('nodeSelect', node.dataRef);
    },
    findNode(key) {
      const find = nodes => {
        for (const node of nodes) {
          if (node.id === key) return node;
          if (node.childrenDatas) {
            const found = find(node.childrenDatas);
            if (found) return found;
          }
        }
      };
      return find(this.treeData);
    },

    // 获取所有子节点中selected为true的ID
    collectSelectedIds(nodes, result = []) {
      const _self = this;
      if (!nodes || nodes.length === 0) return result;

      nodes.forEach(node => {
        if (node.selected) {
          result.push(node.id);
        } else {
          if (node.childrenDatas && node.childrenDatas.length > 0) {
            _self.collectSelectedIds(node.childrenDatas, result);
          }
        }
      });
      return result;
    },
  },
};
</script>