<template>
  <div class="org-tree-container">
    <el-input v-model="filterText" placeholder="请输入组织名称" clearable prefix-icon="Search" class="mb10" />
    <el-tree
      ref="treeRef"
      :data="treeData"
      :props="treeProps"
      :filter-node-method="filterNode"
      :expand-on-click-node="false"
      :default-expand-all="defaultExpandAll"
      node-key="id"
      highlight-current
      @node-click="handleNodeClick"
    >
      <template #default="{ node, data }">
        <div class="tree-node">
          <span class="node-label">{{ node.label }}</span>
          <span class="node-level" v-if="data.level">[{{ data.level }}]</span>
        </div>
      </template>
    </el-tree>
  </div>
</template>

<script setup name="OrgTree">
import { ref, watch, onMounted } from 'vue'

const props = defineProps({
  defaultExpandAll: {
    type: Boolean,
    default: true
  },
  showLevel: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['node-click'])

const treeRef = ref(null)
const filterText = ref('')
const treeData = ref([])

const treeProps = {
  children: 'children',
  label: 'label'
}

watch(filterText, (val) => {
  treeRef.value.filter(val)
})

/** 过滤节点 */
function filterNode(value, data) {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

/** 节点点击 */
function handleNodeClick(data) {
  emit('node-click', data)
}

/** 获取选中节点 */
function getCheckedKeys() {
  return treeRef.value.getCheckedKeys()
}

/** 设置选中节点 */
function setCheckedKeys(keys) {
  treeRef.value.setCheckedKeys(keys)
}

/** 获取当前选中节点 */
function getCurrentKey() {
  return treeRef.value.getCurrentKey()
}

/** 设置当前选中节点 */
function setCurrentKey(key) {
  treeRef.value.setCurrentKey(key)
}

/** 查询组织树 */
function getTreeData() {
  // 这里需要调用后端接口获取组织树数据
  // 暂时使用模拟数据
  treeData.value = [
    {
      id: '1',
      label: '水利部',
      level: '部级',
      children: [
        {
          id: '1-1',
          label: '黄河水利委员会',
          level: '流域',
          children: [
            { id: '1-1-1', label: '河南黄河河务局', level: '省级' },
            { id: '1-1-2', label: '山东黄河河务局', level: '省级' }
          ]
        },
        {
          id: '1-2',
          label: '长江水利委员会',
          level: '流域',
          children: [
            { id: '1-2-1', label: '湖北水利厅', level: '省级' },
            { id: '1-2-2', label: '湖南水利厅', level: '省级' }
          ]
        }
      ]
    }
  ]
}

onMounted(() => {
  getTreeData()
})

defineExpose({
  getCheckedKeys,
  setCheckedKeys,
  getCurrentKey,
  setCurrentKey
})
</script>

<style scoped>
.org-tree-container {
  padding: 10px;
  background: #fff;
  border-radius: 4px;
}
.mb10 {
  margin-bottom: 10px;
}
.tree-node {
  display: flex;
  align-items: center;
  flex: 1;
  font-size: 14px;
  padding-right: 8px;
}
.node-label {
  flex: 1;
}
.node-level {
  color: #909399;
  font-size: 12px;
  margin-left: 5px;
}
</style>
