<template>
  <div class="review-tasks-page">
    <a-card class="mb-4">
      <template #title>我的评审任务</template>
      <template #extra>
        <a-button type="primary" @click="fetchList">
          <template #icon><ReloadOutlined /></template>
          刷新
        </a-button>
      </template>
    </a-card>

    <!-- Tab栏 -->
    <a-tabs v-model:activeKey="activeTab" class="contest-tabs" @change="handleTabChange">
      <a-tab-pane key="pending" tab="待评审" />
      <a-tab-pane key="completed" 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
      :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 === 'contestType'">
          <a-tag :color="record.contestType === 'individual' ? 'blue' : 'green'">
            {{ record.contestType === 'individual' ? '个人参与' : '团队参与' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'reviewProgress'">
          <a-progress
            :percent="getReviewProgress(record)"
            :status="getProgressStatus(record)"
            size="small"
          />
          <span class="progress-text">{{ record.reviewedCount || 0 }} / {{ record.totalWorksCount || 0 }}</span>
        </template>
        <template v-else-if="column.key === 'reviewTime'">
          <div v-if="record.reviewStartTime || record.reviewEndTime">
            <div>{{ formatDate(record.reviewStartTime) }}</div>
            <div>至 {{ formatDate(record.reviewEndTime) }}</div>
          </div>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="getStatusColor(record)">
            {{ getStatusText(record) }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button
              type="link"
              size="small"
              :disabled="!canReview(record)"
              @click="handleStartReview(record)"
            >
              {{ activeTab === 'pending' ? '开始评审' : '查看详情' }}
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 空状态 -->
    <a-empty v-if="!loading && dataSource.length === 0" description="暂无评审任务" />
  </div>
</template>

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

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

// Tab状态
const activeTab = ref<"pending" | "completed">("pending")

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

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

// 表格列定义
const columns = computed(() => [
  { title: "序号", key: "index", width: 70 },
  { title: "活动名称", dataIndex: "contestName", key: "contestName", width: 200 },
  { title: "活动类型", key: "contestType", width: 100 },
  { title: "评审进度", key: "reviewProgress", width: 180 },
  { title: "评审时间", key: "reviewTime", width: 180 },
  { title: "状态", key: "status", width: 100 },
  { title: "操作", key: "action", width: 120, fixed: "right" as const },
])

// 计算评审进度百分比
const getReviewProgress = (record: Contest) => {
  if (!record.totalWorksCount || record.totalWorksCount === 0) return 0
  return Math.round(((record.reviewedCount || 0) / record.totalWorksCount) * 100)
}

// 获取进度条状态
const getProgressStatus = (record: Contest) => {
  const progress = getReviewProgress(record)
  if (progress === 100) return "success"
  if (progress > 0) return "active"
  return "normal"
}

// 获取状态颜色
const getStatusColor = (record: Contest) => {
  const now = new Date()
  const start = record.reviewStartTime ? new Date(record.reviewStartTime) : null
  const end = record.reviewEndTime ? new Date(record.reviewEndTime) : null

  if (!start || now < start) return "default"
  if (end && now > end) return "success"
  return "processing"
}

// 获取状态文本
const getStatusText = (record: Contest) => {
  const now = new Date()
  const start = record.reviewStartTime ? new Date(record.reviewStartTime) : null
  const end = record.reviewEndTime ? new Date(record.reviewEndTime) : null

  if (!start || now < start) return "未开始"
  if (end && now > end) return "已结束"
  return "进行中"
}

// 判断是否可以评审
const canReview = (record: Contest) => {
  const now = new Date()
  const start = record.reviewStartTime ? new Date(record.reviewStartTime) : null
  const end = record.reviewEndTime ? new Date(record.reviewEndTime) : null

  if (!start) return false
  if (now < start) return false
  if (end && now > end) return false
  return true
}

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

// 获取列表数据
const fetchList = async () => {
  loading.value = true
  try {
    // TODO: 这里需要调用专门的评委任务API
    // 暂时使用活动列表API，后续需要替换为评委专属API
    const response = await contestsApi.getList({
      page: pagination.current,
      pageSize: pagination.pageSize,
      contestName: searchParams.contestName || undefined,
    })
    dataSource.value = response.list
    pagination.total = response.total
  } catch (error: any) {
    message.error(error?.response?.data?.message || "获取评审任务失败")
  } 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 handleStartReview = (record: Contest) => {
  // 跳转到作品评审详情页面
  router.push(`/${tenantCode}/contests/works/${record.id}/list`)
}

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

<style scoped>
.review-tasks-page {
  padding: 0;
}

.contest-tabs {
  margin-bottom: 16px;
  background: #fff;
  padding: 0 16px;
  border-radius: 8px;
}

.search-form {
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
}

.progress-text {
  margin-left: 8px;
  font-size: 12px;
  color: #666;
}

.mb-4 {
  margin-bottom: 16px;
}
</style>
