<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="my" :tab="myTabTitle" />
          <a-tab-pane key="all" 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-grid">
      <div
        v-for="contest in dataSource"
        :key="contest.id"
        class="contest-card"
        @click="handleViewDetail(contest.id)"
      >
        <!-- 卡片图标 -->
        <div class="card-icon">
          <TrophyOutlined />
        </div>

        <!-- 卡片标题 -->
        <div class="card-title">{{ contest.contestName }}</div>

        <!-- 卡片描述 -->
        <div class="card-desc">
          赛事时间：{{ formatDate(contest.startTime) }} ~ {{ formatDate(contest.endTime) }}
        </div>

        <!-- 卡片标签 -->
        <div class="card-tags">
          <span class="tag tag-type">
            {{ contest.contestType === "individual" ? "个人赛" : "团队赛" }}
          </span>
          <span class="tag tag-status" :class="{ 'tag-ongoing': contest.status === 'ongoing' }">
            {{ getStatusText(contest) }}
          </span>
          <span v-if="getStageText(contest)" class="tag tag-stage">
            {{ getStageText(contest) }}
          </span>
        </div>

        <!-- 操作按钮区域 - 我的赛事tab显示 -->
        <div v-if="activeTab === 'my'" class="card-actions" @click.stop>
          <!-- 学生角色按钮 -->
          <template v-if="userRole === 'student'">
            <template v-if="contest.contestType === 'individual'">
              <a-button
                v-if="isSubmitting(contest)"
                type="primary"
                size="small"
                @click="handleUploadWork(contest.id)"
              >
                上传作品
              </a-button>
              <a-button size="small" @click="handleViewWorks(contest.id)">
                参赛作品
              </a-button>
            </template>
            <template v-else>
              <a-button size="small" @click="handleViewWorks(contest.id)">
                参赛作品
              </a-button>
              <a-button size="small" @click="handleViewTeam(contest.id)">
                我的队伍
              </a-button>
            </template>
          </template>

          <!-- 教师角色按钮 -->
          <template v-if="userRole === 'teacher'">
            <a-button
              type="primary"
              size="small"
              @click="handleMyGuidance(contest.id)"
            >
              我的指导
            </a-button>
          </template>

          <!-- 评委角色按钮 -->
          <template v-if="userRole === 'judge'">
            <a-button
              type="primary"
              size="small"
              :disabled="isReviewEnded(contest)"
              @click="handleReviewWorks(contest.id)"
            >
              评审作品
            </a-button>
            <a-button
              size="small"
              :disabled="isReviewEnded(contest)"
              @click="handlePresetComments(contest.id)"
            >
              预设评语
            </a-button>
          </template>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <a-pagination
          v-model:current="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :show-size-changer="true"
          :page-size-options="['12', '24', '50', '100']"
          :show-total="(total: number) => `共 ${total} 条`"
          @change="handlePageChange"
          @show-size-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 上传作品抽屉 -->
    <SubmitWorkDrawer
      v-model:open="submitWorkDrawerVisible"
      :contest-id="currentContestId"
      @success="handleSubmitWorkSuccess"
    />

    <!-- 查看参赛作品抽屉 -->
    <ViewWorkDrawer
      v-model:open="viewWorkDrawerVisible"
      :contest-id="currentContestIdForView"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue"
import { useRouter, useRoute } from "vue-router"
import { message } from "ant-design-vue"
import { TrophyOutlined } from "@ant-design/icons-vue"
import dayjs from "dayjs"
import {
  contestsApi,
  type Contest,
  type QueryContestParams,
} from "@/api/contests"
import { useAuthStore } from "@/stores/auth"
import SubmitWorkDrawer from "./components/SubmitWorkDrawer.vue"
import ViewWorkDrawer from "./components/ViewWorkDrawer.vue"

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

// 获取用户角色
const userRole = computed((): "student" | "teacher" | "judge" => {
  const roles = authStore.user?.roles || []
  // 按优先级判断角色（roles 是字符串数组如 ['judge', 'student']）
  if (roles.includes("judge")) {
    return "judge"
  }
  if (roles.includes("teacher")) {
    return "teacher"
  }
  if (roles.includes("student")) {
    return "student"
  }
  return "student" // 默认学生
})

// 根据角色计算Tab标题
const myTabTitle = computed(() => {
  switch (userRole.value) {
    case "teacher":
      return "我参与的赛事"
    case "judge":
      return "我评审的赛事"
    case "student":
    default:
      return "我报名的赛事"
  }
})

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

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

// 获取列表数据
const fetchList = async () => {
  loading.value = true
  try {
    const pageSize = Math.min(pagination.pageSize, 100)

    const params: QueryContestParams = {
      ...searchParams,
      page: pagination.current,
      pageSize,
    }

    let response
    if (activeTab.value === "my") {
      // 根据角色调用API，传递 role 参数
      response = await contestsApi.getMyContests({
        ...params,
        role: userRole.value,
      })
    } else {
      response = await contestsApi.getList(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 handleSearch = () => {
  searchParams.contestName = searchKeyword.value || undefined
  pagination.current = 1
  fetchList()
}

// 分页变化处理
const handlePageChange = (page?: number, size?: number) => {
  if (size !== undefined) {
    pagination.pageSize = Math.min(size, 100)
  }
  if (page !== undefined) {
    pagination.current = page
  }
  fetchList()
}

// 查看详情
// 跳转到竞赛详情页
const handleViewDetail = (contestId: number) => {
  router.push(`/${tenantCode}/contests/${contestId}`)
}

// ===== 学生相关操作 =====
// 上传作品
const submitWorkDrawerVisible = ref(false)
const currentContestId = ref<number>(0)

const handleUploadWork = (id: number) => {
  currentContestId.value = id
  submitWorkDrawerVisible.value = true
}

const handleSubmitWorkSuccess = () => {
  message.success("作品提交成功")
}

// 查看参赛作品
const viewWorkDrawerVisible = ref(false)
const currentContestIdForView = ref<number>(0)

const handleViewWorks = (id: number) => {
  currentContestIdForView.value = id
  viewWorkDrawerVisible.value = true
}

// 查看我的队伍
const handleViewTeam = (id: number) => {
  // TODO: 跳转到我的队伍页面或打开抽屉
  message.info("查看我的队伍功能开发中")
}

// ===== 教师相关操作 =====
// 我的指导
const handleMyGuidance = (id: number) => {
  router.push(`/${tenantCode}/student-activities/guidance?contestId=${id}`)
}

// ===== 评委相关操作 =====
// 评审作品
const handleReviewWorks = (id: number) => {
  router.push(`/${tenantCode}/student-activities/review?contestId=${id}`)
}

// 预设评语
const handlePresetComments = (id: number) => {
  router.push(`/${tenantCode}/student-activities/comments?contestId=${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 => {
  if (!contest.submitStartTime || !contest.submitEndTime) {
    return false
  }
  const now = dayjs()
  const start = dayjs(contest.submitStartTime)
  const end = dayjs(contest.submitEndTime)
  return (
    (now.isAfter(start) || now.isSame(start, "day")) &&
    (now.isBefore(end) || now.isSame(end, "day"))
  )
}

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

// 判断评审是否已结束
const isReviewEnded = (contest: Contest): boolean => {
  if (!contest.reviewEndTime) {
    return false
  }
  const now = dayjs()
  const end = dayjs(contest.reviewEndTime)
  return now.isAfter(end)
}

// 判断评审是否已开始
const isReviewStarted = (contest: Contest): boolean => {
  if (!contest.reviewStartTime) {
    return false
  }
  const now = dayjs()
  const start = dayjs(contest.reviewStartTime)
  return now.isAfter(start)
}

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

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

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

<style lang="scss" scoped>
// 主题色
$primary: #0958d9;
$primary-light: #1677ff;

.contests-activities-page {
  padding: 24px;

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

  .contests-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;

    .contest-card {
      background: #fff;
      border-radius: 16px;
      padding: 24px;
      cursor: pointer;
      transition: all 0.3s ease;
      border: 1px solid #f0f0f0;
      display: flex;
      flex-direction: column;
      gap: 16px;

      &:hover {
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
        transform: translateY(-2px);

        .card-icon {
          background: linear-gradient(135deg, #ff7a45 0%, #fa541c 100%);
          color: #fff;
        }
      }

      .card-icon {
        width: 48px;
        height: 48px;
        background: rgba($primary, 0.08);
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 22px;
        color: $primary;
        transition: all 0.3s ease;
      }

      .card-title {
        font-size: 16px;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.85);
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      .card-desc {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.45);
        line-height: 1.6;
      }

      .card-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-top: auto;

        .tag {
          display: inline-flex;
          align-items: center;
          padding: 4px 12px;
          border-radius: 16px;
          font-size: 12px;
          font-weight: 500;
          transition: all 0.2s;
        }

        .tag-type {
          background: rgba($primary, 0.08);
          color: $primary;
          border: 1px solid rgba($primary, 0.2);
        }

        .tag-status {
          background: rgba(0, 0, 0, 0.04);
          color: rgba(0, 0, 0, 0.65);
          border: 1px solid rgba(0, 0, 0, 0.08);

          &.tag-ongoing {
            background: rgba(82, 196, 26, 0.08);
            color: #52c41a;
            border-color: rgba(82, 196, 26, 0.2);
          }
        }

        .tag-stage {
          background: rgba(250, 173, 20, 0.08);
          color: #d48806;
          border: 1px solid rgba(250, 173, 20, 0.2);
        }
      }

      .card-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        padding-top: 12px;
        border-top: 1px solid #f0f0f0;
        margin-top: 4px;
      }
    }

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