<template>
  <div class="register-individual-page">
    <a-card class="mb-4">
      <template #title>
        <div class="page-title">
          <span>活动报名（个人参与）</span>
          <span v-if="contest" class="contest-name">{{
            contest.contestName
          }}</span>
        </div>
      </template>
      <template #extra>
        <a-space>
          <a-button type="primary" @click="handleAddParticipant">
            <template #icon><PlusOutlined /></template>
            添加参赛人
          </a-button>
          <a-button @click="handleImport">
            <template #icon><UploadOutlined /></template>
            导入
          </a-button>
        </a-space>
      </template>
    </a-card>

    <!-- 数据表格 -->
    <a-table
      :columns="columns"
      :data-source="displayDataSource"
      :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 === 'name'">
          {{ record.user?.nickname || record.accountName || "-" }}
        </template>
        <template v-else-if="column.key === 'gender'">
          <a-tag v-if="record.user?.gender === 'male'" color="blue">男</a-tag>
          <a-tag v-else-if="record.user?.gender === 'female'" color="pink"
            >女</a-tag
          >
          <a-tag v-else-if="record.user?.student?.gender === 1" color="blue"
            >男</a-tag
          >
          <a-tag v-else-if="record.user?.student?.gender === 2" color="pink"
            >女</a-tag
          >
          <a-tag v-else-if="record.gender === 1" color="blue">男</a-tag>
          <a-tag v-else-if="record.gender === 2" color="pink">女</a-tag>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'account'">
          {{ record.user?.username || record.accountNo || "-" }}
        </template>
        <template v-else-if="column.key === 'contact'">
          {{ record.user?.phone || record.phone || "-" }}
        </template>
        <template v-else-if="column.key === 'organization'">
          {{ getOrganizationInfo(record) }}
        </template>
        <template v-else-if="column.key === 'teacher'">
          <a-space v-if="record.teachers && record.teachers.length > 0" wrap>
            <a-tag
              v-for="teacher in record.teachers"
              :key="teacher.id"
              :closable="
                !teacher.isDefault && record.id && record.registrationState
              "
              @close="handleRemoveTeacher(record, teacher.userId)"
            >
              {{ teacher.user.nickname || teacher.user.username }}
            </a-tag>
          </a-space>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag
            v-if="record.registrationState"
            :color="getStatusColor(record.registrationState)"
          >
            {{ getStatusText(record.registrationState) }}
          </a-tag>
          <a-tag v-else color="default">待报名</a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button
              v-if="record.id && record.registrationState"
              type="link"
              size="small"
              @click="handleAddTeacher(record)"
            >
              添加指导老师
            </a-button>
            <a-button
              v-if="record.id && record.registrationState"
              type="link"
              size="small"
              danger
              @click="handleCancelRegistration(record)"
            >
              取消报名
            </a-button>
            <a-button
              v-if="!record.registrationState"
              type="link"
              size="small"
              danger
              @click="handleRemoveParticipant(record.id)"
            >
              移除
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 底部操作按钮 -->
    <div class="footer-actions">
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定报名
        </a-button>
      </a-space>
    </div>

    <!-- 添加参赛人侧边抽屉 -->
    <AddParticipantDrawer
      v-model:open="addParticipantVisible"
      :registered-user-ids="registeredUserIds"
      @confirm="handleAddParticipantConfirm"
    />

    <!-- 添加指导老师抽屉 -->
    <AddTeacherDrawer
      v-model:open="addTeacherVisible"
      :selected-teacher-user-ids="selectedTeacherUserIds"
      @confirm="handleAddTeacherConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue"
import { useRoute, useRouter } from "vue-router"
import { message, Modal } from "ant-design-vue"
import { PlusOutlined, UploadOutlined } from "@ant-design/icons-vue"
import type { TableColumnsType } from "ant-design-vue"
import {
  contestsApi,
  registrationsApi,
  type Contest,
  type ContestRegistration,
} from "@/api/contests"
import { useListRequest } from "@/composables/useListRequest"
import { type Student } from "@/api/students"
import AddParticipantDrawer from "./components/AddParticipantDrawer.vue"
import AddTeacherDrawer from "./components/AddTeacherDrawer.vue"

const route = useRoute()
const router = useRouter()
const contestId = Number(route.params.id)

const submitLoading = ref(false)
const addParticipantVisible = ref(false)

const addTeacherVisible = ref(false)
const currentRegistrationId = ref<number | null>(null)
const contest = ref<Contest | null>(null)

// 选中的参赛人列表
const selectedParticipants = ref<Student[]>([])

// 使用列表请求组合函数
const {
  loading,
  dataSource,
  pagination,
  handleTableChange,
  refresh: refreshList,
} = useListRequest<ContestRegistration, { contestId: number }>({
  requestFn: registrationsApi.getList,
  defaultSearchParams: { contestId },
  defaultPageSize: 10,
  errorMessage: "获取报名列表失败",
})

// 表格列定义
const columns: TableColumnsType = [
  {
    title: "序号",
    key: "index",
    width: 80,
    align: "center",
  },
  {
    title: "姓名",
    key: "name",
    width: 120,
  },
  {
    title: "性别",
    key: "gender",
    width: 80,
    align: "center",
  },
  {
    title: "账号",
    key: "account",
    width: 120,
  },
  {
    title: "联系方式",
    key: "contact",
    width: 120,
  },
  {
    title: "机构信息",
    key: "organization",
    width: 200,
  },
  {
    title: "指导老师",
    key: "teacher",
    width: 120,
  },
  {
    title: "审核状态",
    key: "status",
    width: 100,
    align: "center",
  },
  {
    title: "操作",
    key: "action",
    width: 200,
    fixed: "right" as const,
  },
]

// 获取机构信息
const getOrganizationInfo = (record: ContestRegistration | Student): string => {
  // 优先从 user.student.class 获取（已报名状态）
  if ("user" in record && record.user) {
    const user = record.user as any
    if (user.student?.class) {
      return `${user.student.class.grade?.name || ""} - ${
        user.student.class.name || ""
      }`
    }
  }
  // 从 record.class 获取（待报名状态）
  if ("class" in record && record.class) {
    return `${record.class.grade?.name || ""} - ${record.class.name || ""}`
  }
  return "-"
}

// 已报名的用户ID列表
const registeredUserIds = computed(() => {
  return dataSource.value.map((registration) => registration.userId)
})

// 当前报名记录已选择的教师用户ID列表
const selectedTeacherUserIds = computed(() => {
  if (!currentRegistrationId.value) return []
  const registration = dataSource.value.find(
    (r) => r.id === currentRegistrationId.value
  )
  if (!registration || !registration.teachers) return []
  return registration.teachers.map((t) => t.userId)
})

// 合并显示数据源（已报名的 + 待报名的）
const displayDataSource = computed(() => {
  // 将选中的参赛人转换为表格显示格式
  const pendingParticipants = selectedParticipants.value.map((student) => ({
    id: student.id,
    userId: student.userId,
    user: student.user,
    gender: student.gender,
    phone: student.phone,
    class: student.class,
    registrationState: undefined, // 待报名状态
  }))

  // 合并已报名和待报名的数据
  return [...dataSource.value, ...pendingParticipants]
})

// 获取状态颜色
const getStatusColor = (status?: string) => {
  switch (status) {
    case "passed":
      return "green"
    case "rejected":
      return "red"
    case "pending":
      return "orange"
    case "withdrawn":
      return "default"
    default:
      return "default"
  }
}

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

// 添加参赛人表单验证规则
const addParticipantRules = {
  userId: [{ required: true, message: "请选择用户", trigger: "change" }],
}

// 加载活动详情
const fetchContestDetail = async () => {
  try {
    contest.value = await contestsApi.getDetail(contestId)
  } catch (error: any) {
    message.error(error?.response?.data?.message || "获取活动详情失败")
  }
}

// 添加参赛人
const handleAddParticipant = () => {
  addParticipantVisible.value = true
}

// 添加参赛人确认（从组件接收选中的学生）
const handleAddParticipantConfirm = (students: Student[]) => {
  // 合并新选中的参赛人到列表（去重）
  const existingIds = new Set(selectedParticipants.value.map((p) => p.id))
  const newStudents = students.filter((s) => !existingIds.has(s.id))

  if (newStudents.length > 0) {
    selectedParticipants.value.push(...newStudents)
    message.success(`已选择 ${selectedParticipants.value.length} 个参赛人`)
  } else {
    message.info("没有新的参赛人被添加")
  }
}

// 从选中列表中移除参赛人
const handleRemoveParticipant = (studentId: number) => {
  selectedParticipants.value = selectedParticipants.value.filter(
    (p) => p.id !== studentId
  )
  message.success("已移除参赛人")
}

// 导入
const handleImport = () => {
  message.info("导入功能开发中")
}

// 添加指导老师
const handleAddTeacher = (record: ContestRegistration) => {
  currentRegistrationId.value = record.id
  addTeacherVisible.value = true
}

// 添加指导老师确认（从组件接收选中的教师）
const handleAddTeacherConfirm = async (teachers: any[]) => {
  if (!currentRegistrationId.value) {
    return
  }

  try {
    // 批量添加选中的教师
    const promises = teachers.map((teacher) =>
      registrationsApi.addTeacher(currentRegistrationId.value!, teacher.userId)
    )

    await Promise.all(promises)

    message.success(`成功添加 ${teachers.length} 个指导老师`)
    addTeacherVisible.value = false
    currentRegistrationId.value = null
    refreshList()
  } catch (error: any) {
    message.error(error?.response?.data?.message || "添加指导老师失败")
  }
}

// 移除指导老师
const handleRemoveTeacher = async (
  record: ContestRegistration,
  teacherUserId: number
) => {
  if (!record.id) {
    return
  }

  try {
    await registrationsApi.removeTeacher(record.id, teacherUserId)
    message.success("移除指导老师成功")
    refreshList()
  } catch (error: any) {
    message.error(error?.response?.data?.message || "移除指导老师失败")
  }
}

// 取消添加指导老师（由组件内部处理）

// 取消报名
const handleCancelRegistration = (record: ContestRegistration) => {
  Modal.confirm({
    title: "确认取消报名",
    content: `确定要取消 "${
      record.user?.nickname || record.accountName
    }" 的报名吗？`,
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    onOk: async () => {
      try {
        await registrationsApi.delete(record.id)
        message.success("取消报名成功")
        refreshList()
      } catch (error: any) {
        message.error(error?.response?.data?.message || "取消报名失败")
      }
    },
  })
}

// 取消
const handleCancel = () => {
  router.back()
}

// 确定报名
const handleSubmit = async () => {
  if (selectedParticipants.value.length === 0) {
    message.warning("请至少添加一个参赛人")
    return
  }

  submitLoading.value = true
  try {
    // 批量添加选中的参赛人
    const promises = selectedParticipants.value.map((student) =>
      registrationsApi.create({
        contestId,
        registrationType: "individual",
        userId: student.userId,
      })
    )

    await Promise.all(promises)

    message.success(`成功报名 ${selectedParticipants.value.length} 个参赛人`)
    selectedParticipants.value = []

    // 重置到第一页并刷新列表，确保能看到新创建的记录
    pagination.current = 1
    await refreshList()
  } catch (error: any) {
    message.error(error?.response?.data?.message || "报名提交失败")
  } finally {
    submitLoading.value = false
  }
}

onMounted(() => {
  fetchContestDetail()
})
</script>

<style lang="scss" scoped>
.register-individual-page {
  .page-title {
    display: flex;
    align-items: center;
    gap: 16px;

    .contest-name {
      font-size: 14px;
      color: #8c8c8c;
      font-weight: normal;
    }
  }

  .footer-actions {
    margin-top: 24px;
    padding: 16px;
    background: #fff;
    border-radius: 8px;
    text-align: right;
  }

  // 抽屉样式
  :deep(.ant-drawer-header) {
    border-bottom: 2px solid #409eff;
    padding: 16px 24px;

    .drawer-title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }

  :deep(.ant-drawer-body) {
    padding: 24px;
  }

  .search-section {
    margin-bottom: 24px;
    display: flex;
    flex-direction: row;
    gap: 16px;
    align-items: center;
    flex-wrap: nowrap;

    .search-item {
      display: flex;
      align-items: center;
      gap: 8px;
      flex-shrink: 0;

      .search-label {
        font-size: 14px;
        color: #303133;
        font-weight: 500;
        white-space: nowrap;
        flex-shrink: 0;
      }
    }
  }

  .table-section {
    margin-bottom: 24px;

    :deep(.ant-table-thead > tr > th) {
      background-color: #f5f7fa;
      font-weight: 500;
      color: #303133;
    }

    :deep(.ant-table-tbody > tr:hover > td) {
      background-color: #f5f7fa;
    }

    :deep(.ant-table-tbody > tr:nth-child(even) > td) {
      background-color: #fafafa;
    }
  }

  .selected-info {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px;
    background-color: #ecf5ff;
    border-radius: 4px;
    color: #409eff;
    font-size: 14px;
    margin-bottom: 16px;

    .anticon {
      font-size: 16px;
    }

    span {
      font-weight: 500;
    }
  }
}
</style>
