<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
              :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="tableData" border stripe :header-cell-style="{ background: '#f5f7fa', color: '#606266' }" style="width: 100%">
            <el-table-column prop="schoolName" label="学校名称" min-width="150" show-overflow-tooltip />
            <el-table-column prop="schoolType" label="学校类型" width="100" align="center" />
            <el-table-column prop="regionName" label="所属区域" min-width="180" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="80" align="center">
              <template #default="{ row }">
                <el-tag :type="row.status === '0' ? 'success' : 'danger'">
                  {{ row.status === '0' ? '正常' : '停用' }}
                </el-tag>
              </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="280" fixed="right" align="center">
              <template #default="{ row }">
                <el-button type="primary" link :icon="Edit" @click="handleEdit(row)">编辑</el-button>
                <el-button type="primary" link :icon="Collection" @click="handleAddGrade(row)">新增年级</el-button>
                <el-button type="primary" link :icon="Files" @click="handleAddClass(row)">新增班级</el-button>
                <el-button type="danger" link :icon="Delete" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            style="margin-top: 16px; justify-content: flex-end"
            @size-change="handleQuery"
            @current-change="handleQuery"
          />
        </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 { Collection, Delete, Edit, Files, 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 treeRef = ref()
const treeFilterText = ref('')
const regionTree = ref([])
const selectedRegionId = ref(null)

// 表格相关
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  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('/api/region/tree')
  if (res.code === 200) {
    regionTree.value = res.data
  }
}

// 获取学校列表
const getList = async () => {
  loading.value = true
  try {
    const res = await request.get('/api/school/list', { params: queryParams.value })
    if (res.code === 200) {
      tableData.value = res.rows
      total.value = res.total
    }
  } finally {
    loading.value = false
  }
}

// 树节点点击
const handleNodeClick = (data) => {
  selectedRegionId.value = data.regionId
  queryParams.value.regionId = data.regionId
  queryParams.value.pageNum = 1
  getList()
}

// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

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

// 新增
const handleAdd = () => {
  schoolDialogRef.value?.open()
}

// 编辑
const handleEdit = (row) => {
  schoolDialogRef.value?.open(row)
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除学校"${row.schoolName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await request.delete(`/api/school/${row.id}`)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getList()
    }
  }).catch(() => {})
}

// 新增年级
const handleAddGrade = (row) => {
  gradeDialogRef.value?.open(row)
}

// 新增班级
const handleAddClass = (row) => {
  classDialogRef.value?.open(row)
}

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

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