<template>
  <div class="registrations-page">
    <a-card class="mb-4">
      <template #title>报名管理</template>
    </a-card>

    <!-- Tab栏切换 -->
    <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
      <a-tab-pane key="individual" tab="个人赛" />
      <a-tab-pane key="team" tab="团队赛" />
    </a-tabs>

    <!-- 搜索表单 -->
    <a-form
      :model="searchParams"
      layout="inline"
      class="search-form"
      @finish="handleSearch"
    >
      <a-form-item label="赛事名称">
        <a-input
          v-model:value="searchParams.contestName"
          placeholder="请输入赛事名称"
          allow-clear
          style="width: 200px"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">
          <template #icon><SearchOutlined /></template>
          搜索
        </a-button>
        <a-button style="margin-left: 8px" @click="handleReset">
          <template #icon><ReloadOutlined /></template>
          重置
        </a-button>
      </a-form-item>
    </a-form>

    <!-- 个人赛表格 -->
    <a-table
      v-if="activeTab === 'individual'"
      :columns="individualColumns"
      :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 === 'contestName'">
          <a @click="handleViewContest(record.id)">{{ record.contestName }}</a>
        </template>
        <template v-else-if="column.key === 'organizers'">
          {{ formatOrganizers(record.organizers) }}
        </template>
        <template v-else-if="column.key === 'registrationCount'">
          {{ record._count?.registrations || 0 }}
        </template>
        <template v-else-if="column.key === 'registerTime'">
          <div v-if="record.registerStartTime || record.registerEndTime">
            <div>开始：{{ formatDateTime(record.registerStartTime) }}</div>
            <div>结束：{{ formatDateTime(record.registerEndTime) }}</div>
          </div>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button
              type="link"
              size="small"
              @click="handleViewRecords(record)"
            >
              报名记录
            </a-button>
            <a-button
              v-permission="'contest:update'"
              type="link"
              size="small"
              :disabled="record.registerState === 'open'"
              @click="handleStartRegistration(record)"
            >
              启动报名
            </a-button>
            <a-button
              v-permission="'contest:update'"
              type="link"
              danger
              size="small"
              :disabled="record.registerState !== 'open'"
              @click="handleStopRegistration(record)"
            >
              关闭报名
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 团队赛表格 -->
    <a-table
      v-else
      :columns="teamColumns"
      :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 === 'contestName'">
          <a @click="handleViewContest(record.id)">{{ record.contestName }}</a>
        </template>
        <template v-else-if="column.key === 'organizers'">
          {{ formatOrganizers(record.organizers) }}
        </template>
        <template v-else-if="column.key === 'teamCount'">
          {{ record._count?.teams || 0 }}
        </template>
        <template v-else-if="column.key === 'totalMembers'">
          {{ record.totalMembers || 0 }}
        </template>
        <template v-else-if="column.key === 'registerTime'">
          <div v-if="record.registerStartTime || record.registerEndTime">
            <div>开始：{{ formatDateTime(record.registerStartTime) }}</div>
            <div>结束：{{ formatDateTime(record.registerEndTime) }}</div>
          </div>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button
              type="link"
              size="small"
              @click="handleViewRecords(record)"
            >
              报名记录
            </a-button>
            <a-button
              v-permission="'contest:update'"
              type="link"
              size="small"
              :disabled="record.registerState === 'open'"
              @click="handleStartRegistration(record)"
            >
              启动报名
            </a-button>
            <a-button
              v-permission="'contest:update'"
              type="link"
              danger
              size="small"
              :disabled="record.registerState !== 'open'"
              @click="handleStopRegistration(record)"
            >
              关闭报名
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue"
import { useRouter, useRoute } from "vue-router"
import { message } from "ant-design-vue"
import {
  SearchOutlined,
  ReloadOutlined,
} from "@ant-design/icons-vue"
import {
  contestsApi,
  type Contest,
  type QueryContestParams,
} from "@/api/contests"
import dayjs from "dayjs"

const router = useRouter()
const route = useRoute()
const tenantCode = route.params.tenantCode as string

// Tab状态
const activeTab = ref<"individual" | "team">("individual")

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

// 搜索参数
const searchParams = reactive<QueryContestParams>({
  contestName: "",
})

// 个人赛表格列
const individualColumns = [
  {
    title: "序号",
    key: "index",
    width: 70,
  },
  {
    title: "赛事名称",
    key: "contestName",
    dataIndex: "contestName",
    width: 250,
  },
  {
    title: "主办单位",
    key: "organizers",
    width: 200,
  },
  {
    title: "报名人数",
    key: "registrationCount",
    width: 120,
  },
  {
    title: "报名时间",
    key: "registerTime",
    width: 200,
  },
  {
    title: "操作",
    key: "action",
    width: 220,
    fixed: "right" as const,
  },
]

// 团队赛表格列
const teamColumns = [
  {
    title: "序号",
    key: "index",
    width: 70,
  },
  {
    title: "赛事名称",
    key: "contestName",
    dataIndex: "contestName",
    width: 250,
  },
  {
    title: "主办单位",
    key: "organizers",
    width: 200,
  },
  {
    title: "报名队伍数",
    key: "teamCount",
    width: 120,
  },
  {
    title: "参赛总人数",
    key: "totalMembers",
    width: 120,
  },
  {
    title: "报名时间",
    key: "registerTime",
    width: 200,
  },
  {
    title: "操作",
    key: "action",
    width: 220,
    fixed: "right" as const,
  },
]

// 格式化日期时间
const formatDateTime = (dateStr?: string) => {
  if (!dateStr) return "-"
  return dayjs(dateStr).format("YYYY-MM-DD HH:mm")
}

// 格式化主办单位
const formatOrganizers = (organizers: any) => {
  if (!organizers) return "-"
  if (Array.isArray(organizers)) {
    return organizers.join("、") || "-"
  }
  if (typeof organizers === "string") {
    try {
      const parsed = JSON.parse(organizers)
      if (Array.isArray(parsed)) {
        return parsed.join("、") || "-"
      }
    } catch {
      return organizers || "-"
    }
  }
  return "-"
}

// 获取列表数据
const fetchList = async () => {
  loading.value = true
  try {
    const params: QueryContestParams = {
      ...searchParams,
      contestType: activeTab.value,
      page: pagination.current,
      pageSize: pagination.pageSize,
    }
    const response = await contestsApi.getList(params)
    dataSource.value = response.list
    pagination.total = response.total
  } catch (error) {
    message.error("获取列表失败")
  } finally {
    loading.value = false
  }
}

// Tab切换
const handleTabChange = () => {
  pagination.current = 1
  fetchList()
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchList()
}

// 重置
const handleReset = () => {
  searchParams.contestName = ""
  pagination.current = 1
  fetchList()
}

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

// 查看比赛
const handleViewContest = (contestId: number) => {
  router.push({ name: "ContestsDetail", params: { tenantCode, id: contestId } })
}

// 查看报名记录
const handleViewRecords = (record: Contest) => {
  router.push({
    name: "RegistrationRecords",
    params: { tenantCode, id: record.id },
  })
}

// 启动报名
const handleStartRegistration = async (record: Contest) => {
  try {
    await contestsApi.update(record.id, {
      registerState: "open",
    })
    message.success("已启动报名")
    fetchList()
  } catch (error: any) {
    message.error(error?.response?.data?.message || "启动报名失败")
  }
}

// 关闭报名
const handleStopRegistration = async (record: Contest) => {
  try {
    await contestsApi.update(record.id, {
      registerState: "closed",
    })
    message.success("已关闭报名")
    fetchList()
  } catch (error: any) {
    message.error(error?.response?.data?.message || "关闭报名失败")
  }
}

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

<style scoped lang="scss">
// 主色调
$primary: #1890ff;
$primary-dark: #0958d9;
$gradient-primary: linear-gradient(135deg, $primary 0%, $primary-dark 100%);

.registrations-page {
  // 标题卡片样式
  :deep(.ant-card) {
    border: none;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    margin-bottom: 16px;

    .ant-card-head {
      border-bottom: none;
      padding: 16px 24px;

      .ant-card-head-title {
        font-size: 18px;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.85);
      }
    }

    .ant-card-body {
      padding: 0;
    }
  }

  // Tab栏样式
  :deep(.ant-tabs) {
    background: #fff;
    padding: 0 24px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    margin-bottom: 16px;
  }

  // 渐变主按钮样式
  :deep(.ant-btn-primary) {
    background: $gradient-primary;
    border: none;
    box-shadow: 0 4px 12px rgba($primary, 0.35);
    transition: all 0.3s ease;

    &:hover {
      background: linear-gradient(135deg, $primary-dark 0%, darken($primary-dark, 8%) 100%);
      box-shadow: 0 6px 16px rgba($primary, 0.45);
      transform: translateY(-1px);
    }

    &:active {
      transform: translateY(0);
    }
  }

  // 表格样式
  :deep(.ant-table-wrapper) {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    overflow: hidden;

    .ant-table {
      .ant-table-thead > tr > th {
        background: #fafafa;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.85);
        border-bottom: 1px solid #f0f0f0;
      }

      .ant-table-tbody > tr {
        transition: all 0.2s ease;

        &:hover > td {
          background: rgba($primary, 0.04);
        }

        > td {
          border-bottom: 1px solid #f5f5f5;
        }
      }
    }

    .ant-table-pagination {
      padding: 16px;
      margin: 0;
    }
  }
}

.search-form {
  margin-bottom: 16px;
  padding: 20px 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

  // 自适应换行
  :deep(.ant-form-item) {
    margin-bottom: 16px;
    margin-right: 16px;

    &:last-child {
      margin-right: 0;
    }
  }
}
</style>
