<template>
  <div class="school-tree">
    <el-table
      v-loading="loading"
      :data="treeData"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      border
      stripe
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      default-expand-all
    >
      <el-table-column prop="name" label="名称" min-width="250" show-overflow-tooltip />
      
      <el-table-column prop="code" label="编码" width="150" show-overflow-tooltip />
      
      <el-table-column prop="type" label="类型" width="100" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.type === 'school'" type="primary">学校</el-tag>
          <el-tag v-else-if="row.type === 'grade'" type="success">年级</el-tag>
          <el-tag v-else type="info">班级</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="status" label="状态" width="80" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.type === 'school'" :type="row.status === '0' ? 'success' : 'danger'">
            {{ row.status === '0' ? '正常' : '停用' }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="regionPath" label="区域路径" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">
          <span v-if="row.type === 'school'">{{ row.regionPath }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="300" fixed="right" align="center">
        <template #default="{ row }">
          <!-- 学校操作 -->
          <template v-if="row.type === 'school'">
            <el-button type="primary" link :icon="Edit" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" link :icon="Collection" size="small" @click="handleBindGrade(row)">挂载年级</el-button>
            <el-button type="danger" link :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
          
          <!-- 年级操作 -->
          <template v-else-if="row.type === 'grade'">
            <el-button type="primary" link :icon="Files" size="small" @click="handleBindClass(row)">挂载班级</el-button>
            <el-button type="danger" link :icon="Delete" size="small" @click="handleDeleteGrade(row)">删除</el-button>
          </template>
          
          <!-- 班级操作 -->
          <template v-else>
            <el-button type="danger" link :icon="Delete" size="small" @click="handleDeleteClass(row)">删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
/**
 * 学校树形组件
 * @author pangu
 */
import { getSchoolTree, deleteSchool, deleteSchoolGrade, deleteSchoolClass } from '@/api/school'
import { Collection, Delete, Edit, Files } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, watch } from 'vue'

const props = defineProps({
  regionId: {
    type: Number,
    default: null
  }
})

const emit = defineEmits(['edit', 'bind-grade', 'bind-class'])

const loading = ref(false)
const treeData = ref([])

// 加载学校树
const loadSchoolTree = async () => {
  loading.value = true
  try {
    const res = await getSchoolTree(props.regionId)
    if (res.code === 200) {
      treeData.value = res.data || []
    }
  } catch (error) {
    console.error('加载学校树失败:', error)
    ElMessage.error('加载学校树失败')
  } finally {
    loading.value = false
  }
}

// 监听区域ID变化
watch(() => props.regionId, () => {
  loadSchoolTree()
}, { immediate: true })

// 编辑学校
const handleEdit = (row) => {
  emit('edit', row)
}

// 挂载年级
const handleBindGrade = (row) => {
  emit('bind-grade', row)
}

// 挂载班级
const handleBindClass = (row) => {
  emit('bind-class', row)
}

// 删除学校
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除学校"${row.name}"吗？删除后不可恢复！`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await deleteSchool(row.schoolId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadSchoolTree()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除学校失败:', error)
    }
  }
}

// 删除年级
const handleDeleteGrade = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除年级"${row.name}"吗？删除后不可恢复！`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await deleteSchoolGrade(row.schoolGradeId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadSchoolTree()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除年级失败:', error)
    }
  }
}

// 删除班级
const handleDeleteClass = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除班级"${row.name}"吗？删除后不可恢复！`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await deleteSchoolClass(row.schoolClassId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadSchoolTree()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除班级失败:', error)
    }
  }
}

// 暴露方法给父组件
defineExpose({ loadSchoolTree })
</script>

<style scoped>
.school-tree {
  width: 100%;
}
</style>
