<template>
  <div class="app-container">
    <el-row :gutter="16">
      <!-- 左侧区域树 -->
      <el-col :span="5">
        <el-card shadow="never">
          <template #header>
            <span>区域筛选</span>
          </template>
          <el-input v-model="treeFilterText" placeholder="输入关键字过滤" clearable style="margin-bottom: 12px" />
          <el-scrollbar height="calc(100vh - 260px)">
            <el-tree
              ref="treeRef"
              :data="regionTree"
              :props="{ label: 'regionName', children: 'children' }"
              node-key="regionId"
              highlight-current
              default-expand-all
              :filter-node-method="filterNode"
              @node-click="handleNodeClick"
            />
          </el-scrollbar>
        </el-card>
      </el-col>

      <!-- 右侧列表 -->
      <el-col :span="19">
        <!-- 搜索区域 -->
        <el-card shadow="never" class="search-wrapper">
          <el-form :model="queryParams" :inline="true">
            <el-form-item label="学校名称">
              <el-input v-model="queryParams.schoolName" placeholder="请输入学校名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
                <el-option label="正常" value="0" />
                <el-option label="停用" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
              <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 表格区域 -->
        <el-card shadow="never" style="margin-top: 12px">
          <el-row :gutter="10" style="margin-bottom: 12px">
            <el-col :span="1.5">
              <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
            </el-col>
          </el-row>

          <!-- 树形表格展示学校/年级/班级 -->
          <el-table
            v-loading="loading"
            :data="treeData"
            row-key="id"
            border
            default-expand-all
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            style="width: 100%"
          >
            <el-table-column prop="name" label="学校名称" min-width="200" show-overflow-tooltip />
            <el-table-column prop="schoolCode" label="学校编码" width="130" />
            <el-table-column prop="schoolType" label="学校类型" width="100" align="center">
              <template #default="{ row }">
                <span v-if="row.type === 'school'">{{ schoolTypeMap[row.schoolType] || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="regionName" label="所属区域" min-width="120" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="80" align="center">
              <template #default="{ row }">
                <template v-if="row.type === 'school'">
                  <el-tag :type="row.status === '0' ? 'success' : 'danger'" size="small">
                    {{ row.status === '0' ? '正常' : '停用' }}
                  </el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="160" />
            <el-table-column prop="createBy" label="创建人" width="100" />
            <el-table-column label="操作" width="220" fixed="right" align="center">
              <template #default="{ row }">
                <!-- 学校操作：编辑、新增年级、删除 -->
                <template v-if="row.type === 'school'">
                  <el-button type="primary" link size="small" @click="handleEdit(row)">编辑</el-button>
                  <el-button type="primary" link size="small" @click="handleAddGrade(row)">新增年级</el-button>
                  <el-button type="danger" link size="small" @click="handleDelete(row, 'school')">删除</el-button>
                </template>
                <!-- 年级操作：新增班级、删除 -->
                <template v-else-if="row.type === 'grade'">
                  <el-button type="primary" link size="small" @click="handleAddClass(row)">新增班级</el-button>
                  <el-button type="danger" link size="small" @click="handleDelete(row, 'grade')">删除</el-button>
                </template>
                <!-- 班级操作：删除 -->
                <template v-else>
                  <el-button type="danger" link size="small" @click="handleDelete(row, 'class')">删除</el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑学校弹窗 -->
    <SchoolDialog ref="schoolDialogRef" :region-tree="regionTree" @success="handleQuery" />

    <!-- 新增年级弹窗 -->
    <GradeDialog ref="gradeDialogRef" @success="handleQuery" />

    <!-- 新增班级弹窗 -->
    <ClassDialog ref="classDialogRef" @success="handleQuery" />
  </div>
</template>

<script setup>
/**
 * 学校管理页面
 * 按区域树形展示学校、年级、班级结构
 * @author pangu
 */
import { Plus, Refresh, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, ref, watch } from 'vue'
import request from '@/utils/request'
import ClassDialog from './components/ClassDialog.vue'
import GradeDialog from './components/GradeDialog.vue'
import SchoolDialog from './components/SchoolDialog.vue'

// 学校类型映射
const schoolTypeMap = {
  '1': '小学',
  '2': '初中',
  '3': '高中',
  '4': '九年一贯制',
  '5': '完全中学'
}

// 区域树相关
const treeRef = ref()
const treeFilterText = ref('')
const regionTree = ref([])
const selectedRegionId = ref(null)

// 表格相关
const loading = ref(false)
const treeData = ref([])

// 查询参数
const queryParams = ref({
  schoolName: '',
  status: '',
  regionId: ''
})

// 弹窗引用
const schoolDialogRef = ref()
const gradeDialogRef = ref()
const classDialogRef = ref()

// 监听树过滤
watch(treeFilterText, (val) => {
  treeRef.value?.filter(val)
})

// 树节点过滤
const filterNode = (value, data) => {
  if (!value) return true
  return data.regionName.includes(value)
}

// 获取区域树
const getRegionTree = async () => {
  const res = await request.get('/business/region/tree')
  if (res.code === 200) {
    regionTree.value = res.data
  }
}

// 获取学校树形数据（包含年级和班级）
const getSchoolTree = async () => {
  loading.value = true
  try {
    const res = await request.get('/business/school/tree', { params: queryParams.value })
    if (res.code === 200) {
      treeData.value = res.data
    }
  } finally {
    loading.value = false
  }
}

// 区域树节点点击 - 基于选择的区域筛选学校
const handleNodeClick = (data) => {
  selectedRegionId.value = data.regionId
  queryParams.value.regionId = data.regionId
  getSchoolTree()
}

// 搜索
const handleQuery = () => {
  getSchoolTree()
}

// 重置
const resetQuery = () => {
  queryParams.value = {
    schoolName: '',
    status: '',
    regionId: ''
  }
  selectedRegionId.value = null
  treeRef.value?.setCurrentKey(null)
  getSchoolTree()
}

// 新增学校 - 基于选择的区域新增学校信息
const handleAdd = () => {
  schoolDialogRef.value?.open(null, selectedRegionId.value)
}

// 编辑学校
const handleEdit = (row) => {
  const schoolData = {
    schoolId: row.id,
    schoolCode: row.schoolCode,
    schoolName: row.name,
    schoolType: row.schoolType,
    regionId: row.regionId,
    regionName: row.regionName,
    status: row.status
  }
  schoolDialogRef.value?.open(schoolData)
}

// 新增年级 - 学校下新增年级，选择对应的年级挂载
const handleAddGrade = (row) => {
  const schoolData = {
    schoolId: row.id,
    schoolName: row.name
  }
  gradeDialogRef.value?.open(schoolData)
}

// 新增班级 - 年级下新增班级，选择对应的班级挂载
const handleAddClass = (row) => {
  // 从 treeData 中查找学校名称
  const school = treeData.value.find(s => s.id === row.schoolId)
  const schoolData = {
    schoolId: row.schoolId,
    schoolName: school ? school.name : '',
    schoolGradeId: row.id,
    gradeName: row.name
  }
  classDialogRef.value?.open(schoolData)
}

// 删除操作 - 删除时提示是否有子级
const handleDelete = (row, type) => {
  let message = ''
  let url = ''
  
  if (type === 'school') {
    // 检查是否有子级
    if (row.children && row.children.length > 0) {
      message = `学校"${row.name}"下有年级/班级，确定要删除吗？删除后其下的年级和班级也将被删除。`
    } else {
      message = `确定要删除学校"${row.name}"吗？`
    }
    url = `/business/school/${row.id}`
  } else if (type === 'grade') {
    if (row.children && row.children.length > 0) {
      message = `年级"${row.name}"下有班级，确定要删除吗？其下的班级也将被删除。`
    } else {
      message = `确定要删除年级"${row.name}"吗？`
    }
    url = `/business/school/grade/${row.id}`
  } else {
    message = `确定要删除班级"${row.name}"吗？`
    url = `/business/school/class/${row.id}`
  }

  ElMessageBox.confirm(message, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await request.delete(url)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getSchoolTree()
    }
  }).catch(() => {})
}

onMounted(() => {
  getRegionTree()
  getSchoolTree()
})
</script>

<style scoped>
.app-container {
  padding: 16px;
}
.search-wrapper {
  margin-bottom: 0;
}
</style>
