<template>
  <div class="review-detail-page">
    <a-card class="mb-4">
      <template #title>
        <a-breadcrumb>
          <a-breadcrumb-item>
            <router-link :to="`/${tenantCode}/activities/review`">评审作品</router-link>
          </a-breadcrumb-item>
          <a-breadcrumb-item>{{ contestName || '作品评审' }}</a-breadcrumb-item>
        </a-breadcrumb>
      </template>
    </a-card>

    <!-- 搜索表单 -->
    <a-form
      :model="searchParams"
      layout="inline"
      class="search-form"
      @finish="handleSearch"
    >
      <a-form-item label="作品编号">
        <a-input
          v-model:value="searchParams.workNo"
          placeholder="请输入作品编号"
          allow-clear
          style="width: 150px"
        />
      </a-form-item>
      <a-form-item label="报名账号">
        <a-input
          v-model:value="searchParams.accountNo"
          placeholder="请输入报名账号"
          allow-clear
          style="width: 150px"
        />
      </a-form-item>
      <a-form-item label="评审状态">
        <a-select
          v-model:value="searchParams.reviewStatus"
          placeholder="请选择状态"
          allow-clear
          style="width: 120px"
        >
          <a-select-option value="pending">未评审</a-select-option>
          <a-select-option value="reviewed">已评审</a-select-option>
        </a-select>
      </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-selection="rowSelection"
      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 === 'workNo'">
          <a @click="handleViewWork(record)">{{ record.workNo || "-" }}</a>
        </template>
        <template v-else-if="column.key === 'score'">
          <span v-if="record.score !== null" class="score">
            {{ Number(record.score).toFixed(2) }}
          </span>
          <span v-else class="text-gray">-</span>
        </template>
        <template v-else-if="column.key === 'reviewStatus'">
          <a-tag v-if="record.reviewStatus === 'reviewed'" color="success">已评审</a-tag>
          <a-tag v-else color="default">未评审</a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-button type="link" size="small" @click="handleReview(record)">
            {{ record.reviewStatus === 'reviewed' ? '查看' : '评审' }}
          </a-button>
        </template>
      </template>
    </a-table>

    <!-- 作品评审弹框 -->
    <ReviewWorkModal
      v-model:open="reviewModalVisible"
      :assignment-id="currentAssignmentId"
      :work-id="currentWorkId"
      :contest-id="contestId"
      :work-list="workListForNav"
      :current-index="currentWorkIndex"
      @success="handleReviewSuccess"
      @navigate="handleNavigate"
    />

    <!-- 作品详情弹框 -->
    <WorkDetailModal
      v-model:open="workDetailModalVisible"
      :work-id="viewWorkId"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue"
import { useRoute } from "vue-router"
import { message } from "ant-design-vue"
import type { TableProps } from "ant-design-vue"
import { SearchOutlined, ReloadOutlined } from "@ant-design/icons-vue"
import { reviewsApi, contestsApi } from "@/api/contests"
import ReviewWorkModal from "./components/ReviewWorkModal.vue"
import WorkDetailModal from "../contests/components/WorkDetailModal.vue"

const route = useRoute()
const tenantCode = route.params.tenantCode as string
const contestId = Number(route.params.id)

// 活动名称
const contestName = ref("")

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

// 搜索参数
const searchParams = reactive({
  workNo: "",
  accountNo: "",
  reviewStatus: undefined as string | undefined,
})

// 选中的行
const selectedRowKeys = ref<number[]>([])
const rowSelection = computed<TableProps["rowSelection"]>(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: any) => {
    selectedRowKeys.value = keys
  },
}))

// 表格列定义
const columns = [
  {
    title: "序号",
    key: "index",
    width: 70,
  },
  {
    title: "作品编号",
    key: "workNo",
    width: 150,
  },
  {
    title: "报名账号",
    key: "accountNo",
    dataIndex: "accountNo",
    width: 150,
  },
  {
    title: "评分",
    key: "score",
    width: 100,
  },
  {
    title: "评审状态",
    key: "reviewStatus",
    width: 100,
  },
  {
    title: "操作",
    key: "action",
    width: 100,
    fixed: "right" as const,
  },
]

// 评审弹框
const reviewModalVisible = ref(false)
const currentAssignmentId = ref<number | null>(null)
const currentWorkId = ref<number | null>(null)
const currentWorkIndex = ref<number>(0)

// 用于作品切换导航的列表
const workListForNav = computed(() => {
  return dataSource.value.map((item: any) => ({
    workId: item.workId,
    assignmentId: item.id,
  }))
})

// 作品详情弹框
const workDetailModalVisible = ref(false)
const viewWorkId = ref<number | null>(null)

// 获取活动信息
const fetchContestInfo = async () => {
  try {
    const contest = await contestsApi.getDetail(contestId)
    contestName.value = contest.contestName
  } catch (error) {
    console.error("获取活动信息失败", error)
  }
}

// 获取列表数据
const fetchList = async () => {
  loading.value = true
  try {
    const response = await reviewsApi.getJudgeContestWorks(contestId, {
      page: pagination.current,
      pageSize: pagination.pageSize,
      workNo: searchParams.workNo || undefined,
      accountNo: searchParams.accountNo || undefined,
      reviewStatus: searchParams.reviewStatus || undefined,
    })
    dataSource.value = response.list
    pagination.total = response.total
  } catch (error: any) {
    message.error(error?.response?.data?.message || "获取数据失败")
  } finally {
    loading.value = false
  }
}

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

// 重置
const handleReset = () => {
  searchParams.workNo = ""
  searchParams.accountNo = ""
  searchParams.reviewStatus = undefined
  pagination.current = 1
  fetchList()
}

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

// 查看作品详情
const handleViewWork = (record: any) => {
  viewWorkId.value = record.workId
  workDetailModalVisible.value = true
}

// 评审作品
const handleReview = (record: any) => {
  currentAssignmentId.value = record.id
  currentWorkId.value = record.workId
  // 查找当前作品在列表中的索引
  const index = dataSource.value.findIndex((item: any) => item.id === record.id)
  currentWorkIndex.value = index >= 0 ? index : 0
  reviewModalVisible.value = true
}

// 导航到其他作品
const handleNavigate = (index: number) => {
  const item = dataSource.value[index]
  if (item) {
    currentAssignmentId.value = item.id
    currentWorkId.value = item.workId
    currentWorkIndex.value = index
  }
}

// 评审成功回调
const handleReviewSuccess = () => {
  fetchList()
}

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

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

.review-detail-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;
    }
  }

  :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);
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  gap: 16px 24px;

  :deep(.ant-form-item) {
    margin-bottom: 0;
    margin-right: 0;
  }
}

.mb-4 {
  margin-bottom: 16px;
}

.score {
  font-weight: bold;
  color: #52c41a;
}

.text-gray {
  color: #999;
}
</style>
