<template>
  <div class="register-team-page">
    <a-card class="mb-4">
      <template #title>活动报名（团队参与）</template>
      <template #extra>
        <a-space>
          <a-button type="primary" @click="handleAddTeam">
            <template #icon><PlusOutlined /></template>
            添加参赛队伍
          </a-button>
        </a-space>
      </template>
    </a-card>

    <!-- 数据表格 -->
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'index'">
          {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
        </template>
        <template v-else-if="column.key === 'teamName'">
          {{ record.teamName || "-" }}
        </template>
        <template v-else-if="column.key === 'leader'">
          {{ record.leader?.nickname || "-" }}
        </template>
        <template v-else-if="column.key === 'memberCount'">
          {{ record._count?.members || 0 }}
        </template>
        <template v-else-if="column.key === 'registrationState'">
          <a-tag :color="getStateColor(record.registrationState)">
            {{ getStateText(record.registrationState) }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button
              type="link"
              size="small"
              @click="handleViewMembers(record)"
            >
              查看成员
            </a-button>
            <a-popconfirm
              title="确定要取消该队伍的报名吗？"
              @confirm="handleCancel(record)"
            >
              <a-button type="link" size="small" danger>
                取消报名
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 底部操作按钮 -->
    <div class="footer-actions">
      <a-space>
        <a-button @click="handleBack">返回</a-button>
      </a-space>
    </div>

    <!-- 添加参赛队伍抽屉 -->
    <a-drawer
      v-model:open="teamDrawerVisible"
      title="队伍信息"
      placement="right"
      width="700"
      :footer-style="{ textAlign: 'right' }"
    >
      <a-form
        ref="teamFormRef"
        :model="teamForm"
        :rules="teamRules"
        layout="vertical"
      >
        <!-- 队伍名称 -->
        <a-form-item label="队伍名称" name="teamName" required>
          <a-input
            v-model:value="teamForm.teamName"
            placeholder="请输入队伍名称"
            :maxlength="100"
          />
        </a-form-item>

        <!-- 队长 -->
        <a-form-item label="队长" name="leaderId">
          <a-button type="dashed" block @click="handleSelectLeader">
            <PlusOutlined /> 添加队长
          </a-button>
          <a-table
            v-if="selectedLeader"
            :columns="memberTableColumns"
            :data-source="[selectedLeader]"
            :pagination="false"
            size="small"
            class="mt-3"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'nickname'">
                {{ record.user?.nickname || record.nickname || "-" }}
              </template>
              <template v-else-if="column.key === 'gender'">
                {{ record.user?.gender === 'male' ? '男' : record.user?.gender === 'female' ? '女' : '-' }}
              </template>
              <template v-else-if="column.key === 'username'">
                {{ record.user?.username || record.username || "-" }}
              </template>
              <template v-else-if="column.key === 'phone'">
                {{ record.user?.phone || record.phone || "-" }}
              </template>
              <template v-else-if="column.key === 'tenant'">
                {{ record.user?.tenant?.name || "-" }}
              </template>
              <template v-else-if="column.key === 'action'">
                <a-button type="link" size="small" @click="handleSelectLeader">
                  更换
                </a-button>
              </template>
            </template>
          </a-table>
        </a-form-item>

        <!-- 队员 -->
        <a-form-item label="队员">
          <a-button type="dashed" block @click="handleSelectMembers">
            <PlusOutlined /> 添加队员
          </a-button>
          <a-table
            v-if="selectedMembers.length > 0"
            :columns="memberTableColumnsWithRemove"
            :data-source="selectedMembers"
            :pagination="false"
            size="small"
            class="mt-3"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'nickname'">
                {{ record.user?.nickname || record.nickname || "-" }}
              </template>
              <template v-else-if="column.key === 'gender'">
                {{ record.user?.gender === 'male' ? '男' : record.user?.gender === 'female' ? '女' : '-' }}
              </template>
              <template v-else-if="column.key === 'username'">
                {{ record.user?.username || record.username || "-" }}
              </template>
              <template v-else-if="column.key === 'phone'">
                {{ record.user?.phone || record.phone || "-" }}
              </template>
              <template v-else-if="column.key === 'tenant'">
                {{ record.user?.tenant?.name || "-" }}
              </template>
              <template v-else-if="column.key === 'action'">
                <a-button type="link" size="small" danger @click="handleRemoveMember(record)">
                  移除
                </a-button>
              </template>
            </template>
          </a-table>
        </a-form-item>

        <!-- 指导老师 -->
        <a-form-item label="指导老师">
          <a-button type="dashed" block @click="handleSelectTeachers">
            <PlusOutlined /> 添加指导老师
          </a-button>
          <a-table
            v-if="selectedTeachers.length > 0"
            :columns="memberTableColumnsWithRemove"
            :data-source="selectedTeachers"
            :pagination="false"
            size="small"
            class="mt-3"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'nickname'">
                {{ record.user?.nickname || "-" }}
              </template>
              <template v-else-if="column.key === 'gender'">
                {{ record.gender === 1 ? '男' : record.gender === 2 ? '女' : '-' }}
              </template>
              <template v-else-if="column.key === 'username'">
                {{ record.user?.username || "-" }}
              </template>
              <template v-else-if="column.key === 'phone'">
                {{ record.phone || "-" }}
              </template>
              <template v-else-if="column.key === 'tenant'">
                {{ record.department?.name || "-" }}
              </template>
              <template v-else-if="column.key === 'action'">
                <a-button
                  v-if="!(currentTeacher && record.userId === currentTeacher.userId)"
                  type="link"
                  size="small"
                  danger
                  @click="handleRemoveTeacher(record)"
                >
                  移除
                </a-button>
                <span v-else class="text-gray">默认</span>
              </template>
            </template>
          </a-table>
        </a-form-item>
      </a-form>

      <template #footer>
        <a-space>
          <a-button @click="handleTeamCancel">取消</a-button>
          <a-button type="primary" :loading="teamSubmitLoading" @click="handleTeamSubmit">
            确定
          </a-button>
        </a-space>
      </template>
    </a-drawer>

    <!-- 选择学生弹框 -->
    <a-modal
      v-model:open="selectStudentModalVisible"
      :title="selectStudentTitle"
      width="900px"
      @ok="handleSelectStudentConfirm"
      @cancel="handleSelectStudentCancel"
    >
      <!-- 搜索 -->
      <a-form layout="inline" class="mb-3">
        <a-form-item label="姓名">
          <a-input
            v-model:value="studentSearchParams.nickname"
            placeholder="请输入姓名"
            allow-clear
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item label="账号">
          <a-input
            v-model:value="studentSearchParams.username"
            placeholder="请输入账号"
            allow-clear
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearchStudents">搜索</a-button>
          <a-button class="ml-2" @click="handleResetStudentSearch">重置</a-button>
        </a-form-item>
      </a-form>

      <!-- 学生列表 -->
      <a-table
        :columns="studentSelectColumns"
        :data-source="studentList"
        :loading="studentListLoading"
        :pagination="studentPagination"
        :row-selection="studentRowSelection"
        row-key="id"
        size="small"
        @change="handleStudentTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'nickname'">
            {{ record.user?.nickname || "-" }}
          </template>
          <template v-else-if="column.key === 'gender'">
            {{ record.user?.gender === 'male' ? '男' : record.user?.gender === 'female' ? '女' : '-' }}
          </template>
          <template v-else-if="column.key === 'username'">
            {{ record.user?.username || "-" }}
          </template>
          <template v-else-if="column.key === 'phone'">
            {{ record.user?.phone || "-" }}
          </template>
          <template v-else-if="column.key === 'tenant'">
            {{ record.user?.tenant?.name || "-" }}
          </template>
        </template>
      </a-table>
    </a-modal>

    <!-- 选择老师弹框 -->
    <a-modal
      v-model:open="selectTeacherModalVisible"
      title="选择指导老师"
      width="900px"
      @ok="handleSelectTeacherConfirm"
      @cancel="handleSelectTeacherCancel"
    >
      <!-- 搜索 -->
      <a-form layout="inline" class="mb-3">
        <a-form-item label="姓名">
          <a-input
            v-model:value="teacherSearchParams.nickname"
            placeholder="请输入姓名"
            allow-clear
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item label="账号">
          <a-input
            v-model:value="teacherSearchParams.username"
            placeholder="请输入账号"
            allow-clear
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearchTeachers">搜索</a-button>
          <a-button class="ml-2" @click="handleResetTeacherSearch">重置</a-button>
        </a-form-item>
      </a-form>

      <!-- 老师列表 -->
      <a-table
        :columns="teacherSelectColumns"
        :data-source="teacherList"
        :loading="teacherListLoading"
        :pagination="teacherPagination"
        :row-selection="teacherRowSelection"
        row-key="id"
        size="small"
        @change="handleTeacherTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'nickname'">
            {{ record.user?.nickname || "-" }}
          </template>
          <template v-else-if="column.key === 'gender'">
            {{ record.gender === 1 ? '男' : record.gender === 2 ? '女' : '-' }}
          </template>
          <template v-else-if="column.key === 'username'">
            {{ record.user?.username || "-" }}
          </template>
          <template v-else-if="column.key === 'phone'">
            {{ record.phone || "-" }}
          </template>
          <template v-else-if="column.key === 'tenant'">
            {{ record.department?.name || "-" }}
          </template>
        </template>
      </a-table>
    </a-modal>

    <!-- 查看成员弹框 -->
    <a-modal
      v-model:open="viewMembersModalVisible"
      :title="`团队成员 - ${currentViewTeam?.teamName || ''}`"
      :footer="null"
      width="700px"
    >
      <a-table
        :columns="viewMemberColumns"
        :data-source="currentTeamMembers"
        :loading="viewMembersLoading"
        :pagination="false"
        size="small"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'role'">
            <a-tag :color="record.role === 'leader' ? 'gold' : record.role === 'mentor' ? 'purple' : 'blue'">
              {{ record.role === 'leader' ? '队长' : record.role === 'mentor' ? '指导老师' : '队员' }}
            </a-tag>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue"
import { useRoute, useRouter } from "vue-router"
import { message } from "ant-design-vue"
import { PlusOutlined } from "@ant-design/icons-vue"
import type { FormInstance, TableProps } from "ant-design-vue"
import { teamsApi, type ContestTeam, type ContestTeamMember } from "@/api/contests"
import { studentsApi, type Student } from "@/api/students"
import { teachersApi, type Teacher } from "@/api/teachers"
import { useAuthStore } from "@/stores/auth"

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const tenantCode = route.params.tenantCode as string
const contestId = Number(route.params.id)

// 当前登录老师信息
const currentTeacher = ref<Teacher | null>(null)

// 列表状态
const loading = ref(false)
const dataSource = ref<ContestTeam[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})

// 添加队伍抽屉
const teamDrawerVisible = ref(false)
const teamSubmitLoading = ref(false)
const teamFormRef = ref<FormInstance>()

const teamForm = reactive({
  teamName: "",
  leaderId: undefined as number | undefined,
})

const teamRules = {
  teamName: [{ required: true, message: "请输入队伍名称", trigger: "blur" }],
}

// 选中的成员
const selectedLeader = ref<Student | null>(null)
const selectedMembers = ref<Student[]>([])
const selectedTeachers = ref<Teacher[]>([])

// 选择学生弹框
const selectStudentModalVisible = ref(false)
const selectStudentTitle = ref("选择学生")
const selectStudentType = ref<"leader" | "member" | "teacher">("member")
const studentList = ref<Student[]>([])
const studentListLoading = ref(false)
const studentPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})
const studentSearchParams = reactive({
  nickname: "",
  username: "",
})
const selectedStudentKeys = ref<number[]>([])
const selectedStudentRows = ref<Student[]>([])

// 选择老师弹框
const selectTeacherModalVisible = ref(false)
const teacherList = ref<Teacher[]>([])
const teacherListLoading = ref(false)
const teacherPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})
const teacherSearchParams = reactive({
  nickname: "",
  username: "",
})
const selectedTeacherKeys = ref<number[]>([])
const selectedTeacherRows = ref<Teacher[]>([])

// 查看成员弹框
const viewMembersModalVisible = ref(false)
const viewMembersLoading = ref(false)
const currentViewTeam = ref<ContestTeam | null>(null)
const currentTeamMembers = ref<ContestTeamMember[]>([])

// 表格列定义
const columns = [
  { title: "序号", key: "index", width: 70 },
  { title: "队伍名称", key: "teamName", width: 150 },
  { title: "队长", key: "leader", width: 120 },
  { title: "成员数", key: "memberCount", width: 100 },
  { title: "审核状态", key: "registrationState", width: 100 },
  { title: "操作", key: "action", width: 180, fixed: "right" as const },
]

// 成员表格列（更换操作）
const memberTableColumns = [
  { title: "姓名", key: "nickname", width: 100 },
  { title: "性别", key: "gender", width: 60 },
  { title: "账号", key: "username", width: 120 },
  { title: "联系方式", key: "phone", width: 120 },
  { title: "机构信息", key: "tenant", width: 150 },
  { title: "操作", key: "action", width: 80 },
]

// 成员表格列（移除操作）
const memberTableColumnsWithRemove = [
  { title: "姓名", key: "nickname", width: 100 },
  { title: "性别", key: "gender", width: 60 },
  { title: "账号", key: "username", width: 120 },
  { title: "联系方式", key: "phone", width: 120 },
  { title: "机构信息", key: "tenant", width: 150 },
  { title: "操作", key: "action", width: 80 },
]

// 学生选择表格列
const studentSelectColumns = [
  { title: "姓名", key: "nickname", width: 100 },
  { title: "性别", key: "gender", width: 60 },
  { title: "账号", key: "username", width: 120 },
  { title: "联系方式", key: "phone", width: 120 },
  { title: "机构信息", key: "tenant", width: 150 },
]

// 查看成员表格列
const viewMemberColumns = [
  { title: "姓名", dataIndex: ["user", "nickname"], width: 100 },
  { title: "账号", dataIndex: ["user", "username"], width: 120 },
  { title: "角色", key: "role", width: 100 },
]

// 学生选择行配置
const studentRowSelection = computed<TableProps["rowSelection"]>(() => ({
  type: selectStudentType.value === "leader" ? "radio" : "checkbox",
  selectedRowKeys: selectedStudentKeys.value,
  onChange: (keys: any, rows: Student[]) => {
    selectedStudentKeys.value = keys
    selectedStudentRows.value = rows
  },
}))

// 老师选择表格列
const teacherSelectColumns = [
  { title: "姓名", key: "nickname", width: 100 },
  { title: "性别", key: "gender", width: 60 },
  { title: "账号", key: "username", width: 120 },
  { title: "联系方式", key: "phone", width: 120 },
  { title: "机构信息", key: "tenant", width: 150 },
]

// 老师选择行配置（多选）
const teacherRowSelection = computed<TableProps["rowSelection"]>(() => ({
  type: "checkbox",
  selectedRowKeys: selectedTeacherKeys.value,
  onChange: (keys: any, rows: Teacher[]) => {
    selectedTeacherKeys.value = keys
    selectedTeacherRows.value = rows
  },
  getCheckboxProps: (record: Teacher) => ({
    // 当前登录老师不能取消选择
    disabled: currentTeacher.value && record.userId === currentTeacher.value.userId,
  }),
}))

// 获取状态颜色
const getStateColor = (state?: string) => {
  switch (state) {
    case "passed": return "success"
    case "rejected": return "error"
    default: return "processing"
  }
}

// 获取状态文本
const getStateText = (state?: string) => {
  switch (state) {
    case "passed": return "已通过"
    case "rejected": return "已拒绝"
    default: return "待审核"
  }
}

// 获取团队列表
const fetchTeamList = async () => {
  loading.value = true
  try {
    const teams = await teamsApi.getList(contestId)
    dataSource.value = teams
    pagination.total = teams.length
  } catch (error) {
    message.error("获取团队列表失败")
  } finally {
    loading.value = false
  }
}

// 获取学生列表
const fetchStudentList = async () => {
  studentListLoading.value = true
  try {
    const response = await studentsApi.getList({
      page: studentPagination.current,
      pageSize: studentPagination.pageSize,
      nickname: studentSearchParams.nickname || undefined,
      username: studentSearchParams.username || undefined,
    })
    studentList.value = response.list
    studentPagination.total = response.total
  } catch (error) {
    message.error("获取学生列表失败")
  } finally {
    studentListLoading.value = false
  }
}

// 获取老师列表
const fetchTeacherList = async () => {
  teacherListLoading.value = true
  try {
    const response = await teachersApi.getList({
      page: teacherPagination.current,
      pageSize: teacherPagination.pageSize,
      nickname: teacherSearchParams.nickname || undefined,
      username: teacherSearchParams.username || undefined,
    })
    teacherList.value = response.list
    teacherPagination.total = response.total
  } catch (error) {
    message.error("获取老师列表失败")
  } finally {
    teacherListLoading.value = false
  }
}

// 表格分页变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
}

// 学生表格分页变化
const handleStudentTableChange = (pag: any) => {
  studentPagination.current = pag.current
  studentPagination.pageSize = pag.pageSize
  fetchStudentList()
}

// 搜索学生
const handleSearchStudents = () => {
  studentPagination.current = 1
  fetchStudentList()
}

// 重置学生搜索
const handleResetStudentSearch = () => {
  studentSearchParams.nickname = ""
  studentSearchParams.username = ""
  studentPagination.current = 1
  fetchStudentList()
}

// 老师表格分页变化
const handleTeacherTableChange = (pag: any) => {
  teacherPagination.current = pag.current
  teacherPagination.pageSize = pag.pageSize
  fetchTeacherList()
}

// 搜索老师
const handleSearchTeachers = () => {
  teacherPagination.current = 1
  fetchTeacherList()
}

// 重置老师搜索
const handleResetTeacherSearch = () => {
  teacherSearchParams.nickname = ""
  teacherSearchParams.username = ""
  teacherPagination.current = 1
  fetchTeacherList()
}

// 添加参赛队伍
const handleAddTeam = () => {
  teamForm.teamName = ""
  teamForm.leaderId = undefined
  selectedLeader.value = null
  selectedMembers.value = []
  // 默认将当前登录老师设为指导老师
  if (currentTeacher.value) {
    selectedTeachers.value = [currentTeacher.value]
  } else {
    selectedTeachers.value = []
  }
  teamDrawerVisible.value = true
}

// 选择队长
const handleSelectLeader = () => {
  selectStudentType.value = "leader"
  selectStudentTitle.value = "选择队长"
  selectedStudentKeys.value = selectedLeader.value ? [selectedLeader.value.id] : []
  selectedStudentRows.value = selectedLeader.value ? [selectedLeader.value] : []
  selectStudentModalVisible.value = true
  fetchStudentList()
}

// 选择队员
const handleSelectMembers = () => {
  selectStudentType.value = "member"
  selectStudentTitle.value = "选择队员"
  selectedStudentKeys.value = selectedMembers.value.map(m => m.id)
  selectedStudentRows.value = [...selectedMembers.value]
  selectStudentModalVisible.value = true
  fetchStudentList()
}

// 选择指导老师（使用老师弹框）
const handleSelectTeachers = () => {
  // 设置已选中的老师
  selectedTeacherKeys.value = selectedTeachers.value.map(t => t.id)
  selectedTeacherRows.value = [...selectedTeachers.value]
  selectTeacherModalVisible.value = true
  fetchTeacherList()
}

// 确认选择学生
const handleSelectStudentConfirm = () => {
  if (selectStudentType.value === "leader") {
    if (selectedStudentRows.value.length > 0) {
      selectedLeader.value = selectedStudentRows.value[0]
      teamForm.leaderId = selectedLeader.value.userId
    }
  } else if (selectStudentType.value === "member") {
    selectedMembers.value = [...selectedStudentRows.value]
  }
  selectStudentModalVisible.value = false
}

// 取消选择学生
const handleSelectStudentCancel = () => {
  selectStudentModalVisible.value = false
}

// 确认选择老师
const handleSelectTeacherConfirm = () => {
  // 确保当前登录老师始终在列表中
  let teachers = [...selectedTeacherRows.value]
  if (currentTeacher.value) {
    const hasCurrentTeacher = teachers.some(t => t.userId === currentTeacher.value!.userId)
    if (!hasCurrentTeacher) {
      teachers = [currentTeacher.value, ...teachers]
    }
  }
  selectedTeachers.value = teachers
  selectTeacherModalVisible.value = false
}

// 取消选择老师
const handleSelectTeacherCancel = () => {
  selectTeacherModalVisible.value = false
}

// 移除队员
const handleRemoveMember = (record: Student) => {
  selectedMembers.value = selectedMembers.value.filter(m => m.id !== record.id)
}

// 移除指导老师
const handleRemoveTeacher = (record: Teacher) => {
  // 当前登录老师不能移除
  if (currentTeacher.value && record.userId === currentTeacher.value.userId) {
    message.warning("当前登录老师不能移除")
    return
  }
  selectedTeachers.value = selectedTeachers.value.filter(t => t.id !== record.id)
}

// 取消添加队伍
const handleTeamCancel = () => {
  teamDrawerVisible.value = false
}

// 提交添加队伍
const handleTeamSubmit = async () => {
  try {
    await teamFormRef.value?.validate()

    if (!selectedLeader.value) {
      message.warning("请选择队长")
      return
    }

    teamSubmitLoading.value = true

    const memberIds = [
      selectedLeader.value.userId,
      ...selectedMembers.value.map(m => m.userId),
    ]

    const teacherIds = selectedTeachers.value.map(t => t.userId)

    await teamsApi.create({
      contestId,
      teamName: teamForm.teamName,
      leaderId: selectedLeader.value.userId,
      memberIds,
      teacherIds: teacherIds.length > 0 ? teacherIds : undefined,
    })

    message.success("添加队伍成功")
    teamDrawerVisible.value = false
    fetchTeamList()
  } catch (error: any) {
    if (error?.errorFields) return
    message.error(error?.response?.data?.message || "添加队伍失败")
  } finally {
    teamSubmitLoading.value = false
  }
}

// 查看成员
const handleViewMembers = async (record: ContestTeam) => {
  currentViewTeam.value = record
  viewMembersModalVisible.value = true
  viewMembersLoading.value = true
  try {
    const teamDetail = await teamsApi.getDetail(record.id)
    currentTeamMembers.value = teamDetail.members || []
  } catch (error) {
    message.error("获取团队成员失败")
    currentTeamMembers.value = []
  } finally {
    viewMembersLoading.value = false
  }
}

// 取消报名
const handleCancel = async (record: ContestTeam) => {
  try {
    await teamsApi.delete(record.id)
    message.success("取消报名成功")
    fetchTeamList()
  } catch (error: any) {
    message.error(error?.response?.data?.message || "取消报名失败")
  }
}

// 返回
const handleBack = () => {
  router.back()
}

// 获取当前登录老师信息
const fetchCurrentTeacher = async () => {
  const userId = authStore.user?.id
  if (!userId) return

  // 检查当前用户是否是老师角色
  const roles = authStore.user?.roles || []
  if (!roles.includes("teacher")) return

  try {
    const teacher = await teachersApi.getByUserId(userId)
    currentTeacher.value = teacher
  } catch (error) {
    // 可能不是老师，忽略错误
    console.log("当前用户不是老师")
  }
}

onMounted(async () => {
  await fetchCurrentTeacher()
  fetchTeamList()
})
</script>

<style lang="scss" scoped>
.register-team-page {
  .footer-actions {
    margin-top: 24px;
    padding: 16px;
    background: #fff;
    border-radius: 8px;
    text-align: right;
  }

  .mt-3 {
    margin-top: 12px;
  }

  .mb-3 {
    margin-bottom: 12px;
  }

  .text-gray {
    color: #999;
  }

  .ml-2 {
    margin-left: 8px;
  }
}
</style>
