<template>
  <div class="contests-activities-page">
    <a-card class="mb-4">
      <template #title>
        <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
          <a-tab-pane key="all" tab="全部赛事" />
          <a-tab-pane key="my" tab="我参与的赛事" />
        </a-tabs>
      </template>
      <template #extra>
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索赛事"
          style="width: 300px"
          @search="handleSearch"
          @press-enter="handleSearch"
        />
      </template>
    </a-card>

    <!-- 赛事列表 -->
    <div v-if="loading" class="loading-container">
      <a-spin size="large" />
    </div>

    <div v-else-if="dataSource.length === 0" class="empty-container">
      <a-empty description="暂无赛事" />
    </div>

    <div v-else class="contests-list">
      <a-row :gutter="[24, 24]">
        <a-col
          v-for="contest in dataSource"
          :key="contest.id"
          :xs="24"
          :sm="12"
          :md="12"
          :lg="8"
          :xl="6"
        >
          <a-card
            class="contest-card"
            :hoverable="true"
            @click="handleViewDetail(contest.id)"
          >
            <template #cover>
              <div class="contest-cover">
                <img
                  v-if="contest.coverUrl && !imageErrors[contest.id]"
                  :src="contest.coverUrl"
                  :alt="contest.contestName"
                  @error="(e) => handleImageError(e, contest.id)"
                />
                <div
                  v-if="!contest.coverUrl || imageErrors[contest.id]"
                  class="cover-placeholder"
                >
                  <span>赛事封面</span>
                </div>
                <a-tag
                  class="contest-type-tag"
                  :color="contest.contestType === 'individual' ? 'blue' : 'green'"
                >
                  {{ contest.contestType === "individual" ? "个人赛" : "团队赛" }}
                </a-tag>
              </div>
            </template>
            <a-card-meta>
              <template #title>
                <div class="contest-title">{{ contest.contestName }}</div>
              </template>
              <template #description>
                <div class="contest-status">
                  <div class="status-row">
                    <a-tag
                      :color="getStatusColor(contest)"
                      class="status-tag"
                    >
                      {{ getStatusText(contest) }}
                    </a-tag>
                    <span v-if="contest.status === 'ongoing'" class="stage-text">
                      {{ getStageText(contest) }}
                    </span>
                  </div>
                  <div v-if="contest.status === 'finished'" class="result-info">
                    <a-tag
                      v-if="contest.resultState === 'published'"
                      color="success"
                      class="result-tag"
                    >
                      结果已公布
                    </a-tag>
                    <span v-else class="result-text">结果未公布</span>
                  </div>
                  <div class="time-info">
                    <div v-if="contest.status === 'ongoing'">
                      <span v-if="isRegistering(contest)" class="time-label">
                        报名时间:
                      </span>
                      <span v-else-if="isSubmitting(contest)" class="time-label">
                        征稿时间:
                      </span>
                      <span v-else-if="isReviewing(contest)" class="time-label">
                        评审时间:
                      </span>
                      <span class="time-value">
                        {{ getCurrentTimeRange(contest) }}
                      </span>
                    </div>
                    <div v-else>
                      <span class="time-label">赛事时间:</span>
                      <span class="time-value">
                        {{ formatDate(contest.startTime) }} ~
                        {{ formatDate(contest.endTime) }}
                      </span>
                    </div>
                  </div>
                </div>
              </template>
            </a-card-meta>
            <template #actions>
              <a-button type="primary" @click.stop="handleViewDetail(contest.id)">
                查看活动
              </a-button>
            </template>
          </a-card>
        </a-col>
      </a-row>

      <!-- 分页 -->
      <div class="pagination-container">
        <a-pagination
          v-model:current="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :show-size-changer="true"
          :show-total="(total) => `共 ${total} 条`"
          @change="handlePageChange"
          @show-size-change="handlePageChange"
        />
      </div>
    </div>
  </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 dayjs from "dayjs"
import {
  contestsApi,
  type Contest,
  type QueryContestParams,
} from "@/api/contests"

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

// Tab切换
const activeTab = ref<"all" | "my">("all")
const searchKeyword = ref<string>("")

// 加载状态
const loading = ref(false)
const dataSource = ref<Contest[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 12,
  total: 0,
})
const searchParams = reactive<QueryContestParams>({})

// 获取列表数据
const fetchList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchParams,
    } as QueryContestParams

    const apiFn =
      activeTab.value === "my"
        ? contestsApi.getMyContests
        : contestsApi.getList

    const response = await apiFn(params)
    dataSource.value = response.list
    pagination.total = response.total
  } catch (error) {
    message.error("获取赛事列表失败")
    console.error("List request error:", error)
  } finally {
    loading.value = false
  }
}

// Tab切换处理
const handleTabChange = () => {
  searchKeyword.value = ""
  Object.assign(searchParams, {})
  pagination.current = 1
  fetchList()
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ""
  Object.assign(searchParams, {})
  pagination.current = 1
  fetchList()
}

// 搜索处理
const handleSearch = () => {
  searchParams.contestName = searchKeyword.value || undefined
  pagination.current = 1
  fetchList()
}

// 分页变化处理
const handlePageChange = () => {
  fetchList()
}

// 查看详情
const handleViewDetail = (id: number) => {
  router.push(`/${tenantCode}/contests/${id}`)
}

// 图片加载错误记录
const imageErrors = ref<Record<number, boolean>>({})

// 图片加载错误处理
const handleImageError = (_event: Event, contestId: number) => {
  imageErrors.value[contestId] = true
}

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

// 判断是否在报名中
const isRegistering = (contest: Contest): boolean => {
  const now = dayjs()
  const start = dayjs(contest.registerStartTime)
  const end = dayjs(contest.registerEndTime)
  return now.isAfter(start) && now.isBefore(end)
}

// 判断是否在征稿中
const isSubmitting = (contest: Contest): boolean => {
  const now = dayjs()
  const start = dayjs(contest.submitStartTime)
  const end = dayjs(contest.submitEndTime)
  return now.isAfter(start) && now.isBefore(end)
}

// 判断是否在评审中
const isReviewing = (contest: Contest): boolean => {
  const now = dayjs()
  const start = dayjs(contest.reviewStartTime)
  const end = dayjs(contest.reviewEndTime)
  return now.isAfter(start) && now.isBefore(end)
}

// 获取当前阶段文本
const getStageText = (contest: Contest): string => {
  if (isRegistering(contest)) {
    return "报名中"
  }
  if (isSubmitting(contest)) {
    return "征稿中"
  }
  if (isReviewing(contest)) {
    return "评审中"
  }
  return ""
}

// 获取当前时间范围
const getCurrentTimeRange = (contest: Contest): string => {
  if (isRegistering(contest)) {
    return `${formatDate(contest.registerStartTime)} ~ ${formatDate(
      contest.registerEndTime
    )}`
  }
  if (isSubmitting(contest)) {
    return `${formatDate(contest.submitStartTime)} ~ ${formatDate(
      contest.submitEndTime
    )}`
  }
  if (isReviewing(contest)) {
    return `${formatDate(contest.reviewStartTime)} ~ ${formatDate(
      contest.reviewEndTime
    )}`
  }
  return ""
}

// 获取状态文本
const getStatusText = (contest: Contest): string => {
  if (contest.status === "finished") {
    return "赛事已结束"
  }
  return "赛事进行中"
}

// 获取状态颜色
const getStatusColor = (contest: Contest): string => {
  if (contest.status === "finished") {
    return "orange"
  }
  return "processing"
}

// 初始化
onMounted(() => {
  fetchList()
})
</script>

<style lang="scss" scoped>
.contests-activities-page {
  padding: 24px;

  .loading-container,
  .empty-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
  }

  .contests-list {
    .contest-card {
      height: 100%;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        transform: translateY(-4px);
      }

      .contest-cover {
        position: relative;
        width: 100%;
        height: 200px;
        overflow: hidden;
        background-color: #f5f5f5;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .cover-placeholder {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #999;
          font-size: 14px;
          background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%);
        }

        .contest-type-tag {
          position: absolute;
          top: 12px;
          left: 12px;
          margin: 0;
        }
      }

      .contest-title {
        font-size: 16px;
        font-weight: 500;
        color: #262626;
        margin-bottom: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .contest-status {
        .status-row {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;

          .status-tag {
            margin: 0;
          }

          .stage-text {
            color: #1890ff;
            font-size: 14px;
          }
        }

        .result-info {
          margin-bottom: 8px;

          .result-tag {
            margin: 0;
          }

          .result-text {
            color: #999;
            font-size: 14px;
          }
        }

        .time-info {
          font-size: 12px;
          color: #8c8c8c;

          .time-label {
            margin-right: 4px;
          }

          .time-value {
            color: #595959;
          }
        }
      }
    }

    .pagination-container {
      margin-top: 24px;
      display: flex;
      justify-content: center;
    }
  }
}
</style>

