<!--
  学校树组件
  @author pangu
-->
<template>
  <el-card shadow="never" class="school-tree-card">
    <template #header>
      <span>学校列表</span>
    </template>

    <!-- 搜索框 -->
    <el-input
      v-model="filterText"
      placeholder="搜索学校"
      clearable
      :prefix-icon="Search"
      style="margin-bottom: 12px;"
    />

    <!-- 树形组件 -->
    <el-scrollbar height="calc(100vh - 280px)">
      <el-tree
        ref="treeRef"
        :data="treeData"
        :props="{ label: 'label', children: 'children' }"
        :filter-node-method="filterNode"
        node-key="id"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <el-icon v-if="data.type === 'school'" style="margin-right: 4px;"><School /></el-icon>
            <el-icon v-else-if="data.type === 'grade'" style="margin-right: 4px;"><Reading /></el-icon>
            <el-icon v-else style="margin-right: 4px;"><User /></el-icon>
            <span>{{ node.label }}</span>
          </span>
        </template>
      </el-tree>
    </el-scrollbar>
  </el-card>
</template>

<script setup>
import { ref, watch } from 'vue'
import { Search, School, Reading, User } from '@element-plus/icons-vue'
import { getSchoolTree } from '@/api/school'

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

// 树数据
const treeData = ref([])
const treeRef = ref(null)
const filterText = ref('')

// 加载树数据
async function loadTree() {
  try {
    const res = await getSchoolTree()
    if (res.code === 200) {
      treeData.value = res.data || []
    }
  } catch (error) {
    console.error('加载学校树失败', error)
  }
}

// 过滤节点
function filterNode(value, data) {
  if (!value) return true
  return data.label.includes(value)
}

// 节点点击
function handleNodeClick(data) {
  emit('node-click', {
    nodeType: data.type,
    nodeId: data.id,
    nodeData: data
  })
}

// 监听搜索文本
watch(filterText, (val) => {
  treeRef.value?.filter(val)
})

// 初始化
loadTree()
</script>

<style scoped>
.custom-tree-node {
  display: flex;
  align-items: center;
}
</style>
