<template>
  <div class="tree-container" :style="containerStyle">
    <!-- 搜索框 -->
    <div class="tree-header" v-if="showSearch">
      <el-input
        v-model="searchText"
        :placeholder="searchPlaceholder"
        clearable
        size="small"
        prefix-icon="el-icon-search"
        @input="handleSearch"
        style="width: 100%; margin-bottom: 10px;"
      />
    </div>
    
    <!-- 树组件 -->
    <div class="tree-body" :style="treeBodyStyle">
      <el-tree
        v-if="treeData && treeData.length > 0"
        ref="treeRef"
        :data="filteredTreeData"
        :props="treeProps"
        :node-key="nodeKey"
        :default-expand-all="defaultExpandAll"
        :expand-on-click-node="expandOnClickNode"
        :highlight-current="highlightCurrent"
        :filter-node-method="filterNodeMethod"
        :empty-text="emptyText"
        :style="treeStyle"
        @node-click="handleNodeClick"
        @node-expand="handleNodeExpand"
        @node-collapse="handleNodeCollapse"
        @current-change="handleCurrentChange"
      >
        <!-- 自定义节点内容插槽 -->
        <template #default="{ node, data }">
          <slot name="node-content" :node="node" :data="data">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
            </span>
          </slot>
        </template>
      </el-tree>
      
      <!-- 空状态 -->
      <div v-else class="tree-empty">
        <slot name="empty">
          <div style="padding: 20px; text-align: center; color: #999;">
            {{ loading ? '加载中...' : '暂无数据' }}
          </div>
        </slot>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TreeComponent',
  props: {
    // 树数据
    treeData: {
      type: Array,
      default: () => []
    },
    
    // 树配置
    treeProps: {
      type: Object,
      default: () => ({
        children: 'children',
        label: 'label',
        value: 'sid'
      })
    },
    
    // 节点key
    nodeKey: {
      type: String,
      default: 'sid'
    },
    
    // 是否显示搜索框
    showSearch: {
      type: Boolean,
      default: true
    },
    
    // 搜索框占位符
    searchPlaceholder: {
      type: String,
      default: '请输入搜索内容'
    },
    
    // 是否默认展开所有节点
    defaultExpandAll: {
      type: Boolean,
      default: true
    },
    
    // 是否点击节点时展开
    expandOnClickNode: {
      type: Boolean,
      default: false
    },
    
    // 是否高亮当前选中节点
    highlightCurrent: {
      type: Boolean,
      default: true
    },
    
    // 容器样式
    containerStyle: {
      type: Object,
      default: () => ({
        height: '100%',
        padding: '10px'
      })
    },
    
    // 树容器样式
    treeBodyStyle: {
      type: Object,
      default: () => ({
        height: 'calc(100% - 50px)',
        overflow: 'auto'
      })
    },
    
    // 树样式
    treeStyle: {
      type: Object,
      default: () => ({})
    },
    
    // 空状态文本
    emptyText: {
      type: String,
      default: '暂无数据'
    },
    
    // 加载状态
    loading: {
      type: Boolean,
      default: false
    },
    
    // 初始选中的节点key
    defaultSelectedKey: {
      type: [String, Number],
      default: null
    }
  },
  
  data() {
    return {
      searchText: '',
      filteredTreeData: [],
      selectedNode: null
    }
  },
  
  watch: {
    treeData: {
      immediate: true,
      handler(newData) {
        this.filteredTreeData = newData
        this.$nextTick(() => {
          if (this.defaultSelectedKey && this.$refs.treeRef) {
            this.$refs.treeRef.setCurrentKey(this.defaultSelectedKey)
          }
        })
      }
    },
    
    defaultSelectedKey: {
      immediate: true,
      handler(newKey) {
        if (newKey && this.$refs.treeRef) {
          this.$refs.treeRef.setCurrentKey(newKey)
        }
      }
    }
  },
  
  methods: {
    /**
     * 过滤节点方法
     */
    filterNodeMethod(value, data, node) {
      if (!value) return true
      const label = data[this.treeProps.label] || ''
      return label.toLowerCase().includes(value.toLowerCase())
    },
    
    /**
     * 处理搜索
     */
    handleSearch(value) {
      this.$refs.treeRef.filter(value)
    },
    
    /**
     * 节点点击事件
     */
    handleNodeClick(data, node, component) {
      this.selectedNode = { data, node, component }
      this.$emit('node-click', data, node, component)
    },
    
    /**
     * 节点展开事件
     */
    handleNodeExpand(data, node, component) {
      this.$emit('node-expand', data, node, component)
    },
    
    /**
     * 节点折叠事件
     */
    handleNodeCollapse(data, node, component) {
      this.$emit('node-collapse', data, node, component)
    },
    
    /**
     * 当前节点变化事件
     */
    handleCurrentChange(data, node) {
      this.$emit('current-change', data, node)
    },
    /**
     * 重置树结构
     */
      resetTree() {
      // 修复：使用正确的 ref 名称 treeRef
      if (this.$refs.treeRef) {
        this.$refs.treeRef.setCurrentKey(null);
        this.searchText = '';
        this.$refs.treeRef.filter(''); // 清空搜索
      }
    },
    /**
     * 设置当前选中的节点
     */
    setCurrentNode(node) {
      this.$refs.treeRef.setCurrentNode(node)
    },
    
    /**
     * 设置当前选中的节点key
     */
    setCurrentKey(key) {
      this.$refs.treeRef.setCurrentKey(key)
    },
    
    /**
     * 获取当前选中的节点
     */
    getCurrentNode() {
      return this.$refs.treeRef.getCurrentNode()
    },
    
    /**
     * 获取当前选中的节点key
     */
    getCurrentKey() {
      return this.$refs.treeRef.getCurrentKey()
    },
    
    /**
     * 展开指定节点
     */
    expandNode(node) {
      this.$refs.treeRef.expandNode(node)
    },
    
    /**
     * 折叠指定节点
     */
    collapseNode(node) {
      this.$refs.treeRef.collapseNode(node)
    },
    
    /**
     * 展开所有节点
     */
    expandAll() {
      this.$refs.treeRef.expandAll()
    },
    
    /**
     * 折叠所有节点
     */
    collapseAll() {
      this.$refs.treeRef.collapseAll()
    },
    
    /**
     * 更新节点数据
     */
    updateKeyChildren(key, data) {
      this.$refs.treeRef.updateKeyChildren(key, data)
    },
    
    /**
     * 获取节点信息
     */
    getNode(key) {
      return this.$refs.treeRef.getNode(key)
    },
    
    /**
     * 移除节点
     */
    remove(key) {
      this.$refs.treeRef.remove(key)
    },
    
    /**
     * 追加节点数据
     */
    append(data, parentNode) {
      this.$refs.treeRef.append(data, parentNode)
    },
    
    /**
     * 插入节点数据
     */
    insertBefore(data, refNode) {
      this.$refs.treeRef.insertBefore(data, refNode)
    },
    
    /**
     * 插入节点数据后
     */
    insertAfter(data, refNode) {
      this.$refs.treeRef.insertAfter(data, refNode)
    }
  }
}
</script>

<style scoped>
.tree-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tree-header {
  flex-shrink: 0;
}

.tree-body {
  flex: 1;
  overflow: auto;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.tree-empty {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}
</style>