<template>
  <div class="school-admin-workbench">
    <section class="admin-hero">
      <div class="admin-badge">Platform Admin / Teachers</div>
      <h1 class="admin-title">教师管理</h1>
      <p class="admin-subtitle">统一维护教师账号，超管可指定管理型老师，普通教师账号默认不具备管理权限。</p>
    </section>

    <section class="admin-panel">
      <div class="toolbar">
        <el-select v-model="query.schoolId" clearable filterable placeholder="所属学校" class="filter-input">
          <el-option v-for="school in schools" :key="school.schoolId" :label="school.schoolName" :value="school.schoolId" />
        </el-select>
        <el-input v-model="query.name" clearable placeholder="姓名" class="filter-input" @keyup.enter="load" />
        <el-input v-model="query.username" clearable placeholder="账号" class="filter-input" @keyup.enter="load" />
        <el-input v-model="query.phone" clearable placeholder="手机号" class="filter-input" @keyup.enter="load" />
        <el-button type="primary" @click="load">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="success" @click="openCreate">新增</el-button>
      </div>

      <el-table v-loading="loading" :data="rows" border>
        <el-table-column label="姓名" prop="name" min-width="120" />
        <el-table-column label="账号" prop="username" min-width="140" />
        <el-table-column label="所属学校" min-width="180">
          <template #default="{ row }">{{ schoolName(row.schoolId) }}</template>
        </el-table-column>
        <el-table-column label="性别" width="90">
          <template #default="{ row }">{{ sexText(row.sex) }}</template>
        </el-table-column>
        <el-table-column label="管理型老师" width="120">
          <template #default="{ row }">
            <el-tag :type="row.teacherAdmin ? 'success' : 'info'" effect="dark">
              {{ row.teacherAdmin ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="手机号" prop="phone" min-width="140" />
        <el-table-column label="邮箱" prop="email" min-width="180" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="openEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="remove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pager"
        layout="total, prev, pager, next, sizes"
        :total="total"
        v-model:current-page="query.index"
        v-model:page-size="query.size"
        @current-change="load"
        @size-change="handleSizeChange"
      />

      <el-dialog
        v-model="dialogVisible"
        :title="form.userId ? '编辑教师' : '新增教师'"
        width="560px"
        align-center
        append-to-body
        custom-class="admin-edit-dialog platform-admin-dialog"
      >
        <el-form :model="form" label-width="112px">
          <el-form-item label="所属学校">
            <el-select v-model="form.schoolId" filterable placeholder="请选择学校" style="width: 100%">
              <el-option v-for="school in schools" :key="school.schoolId" :label="school.schoolName" :value="school.schoolId" />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="账号">
            <el-input v-model="form.username" :disabled="Boolean(form.userId)" />
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="form.sex" placeholder="请选择性别" style="width: 100%">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="管理型老师">
            <el-switch v-model="form.teacherAdmin" active-text="是" inactive-text="否" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="form.phone" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="form.email" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit">保存</el-button>
        </template>
      </el-dialog>
    </section>
  </div>
</template>

<script setup>
import "@/views/schoolAdmin/admin-theme.scss";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  addPlatformTeacher,
  deletePlatformTeacher,
  getPlatformSchools,
  getPlatformTeachers,
  updatePlatformTeacher,
} from "@/api/platformAdmin";

const query = reactive({ index: 1, size: 10, schoolId: "", name: "", username: "", phone: "" });
const rows = ref([]);
const total = ref(0);
const loading = ref(false);
const dialogVisible = ref(false);
const form = ref({});
const schools = ref([]);

const schoolName = (schoolId) => {
  return schools.value.find((school) => school.schoolId === schoolId)?.schoolName || schoolId || "-";
};

const sexText = (sex) => {
  if (sex === "1") return "男";
  if (sex === "2") return "女";
  return sex || "-";
};

const loadSchools = async () => {
  const res = await getPlatformSchools({ index: 1, size: 1000 });
  schools.value = res.data?.list || [];
};

const load = async () => {
  loading.value = true;
  try {
    const res = await getPlatformTeachers(query);
    rows.value = res.data?.list || [];
    total.value = res.data?.total || 0;
  } finally {
    loading.value = false;
  }
};

const reset = () => {
  query.index = 1;
  query.schoolId = "";
  query.name = "";
  query.username = "";
  query.phone = "";
  load();
};

const handleSizeChange = () => {
  query.index = 1;
  load();
};

const openCreate = () => {
  form.value = { teacherAdmin: false };
  dialogVisible.value = true;
};

const openEdit = (row) => {
  form.value = { ...row, teacherAdmin: Boolean(row.teacherAdmin) };
  dialogVisible.value = true;
};

const submit = async () => {
  if (form.value.userId) {
    await updatePlatformTeacher(form.value.userId, form.value);
  } else {
    await addPlatformTeacher(form.value);
  }
  ElMessage.success("保存成功");
  dialogVisible.value = false;
  load();
};

const remove = async (row) => {
  await ElMessageBox.confirm("确认删除该教师？如果教师已创建班级，将不能删除。", "提示", { type: "warning" });
  await deletePlatformTeacher(row.userId);
  ElMessage.success("删除成功");
  load();
};

onMounted(async () => {
  await loadSchools();
  await load();
});
</script>
