<template>
  <div class="guidance-page">
    <!-- 顶部返回和标题 -->
    <a-card class="mb-4">
      <template #title>
        <div class="page-header">
          <a-button type="link" @click="handleBack" class="back-btn">
            <template #icon><ArrowLeftOutlined /></template>
            返回
          </a-button>
          <span class="page-title">我的指导</span>
        </div>
      </template>
    </a-card>

    <!-- 搜索表单 -->
    <a-form
      :model="searchParams"
      layout="inline"
      class="search-form"
      @finish="handleSearch"
    >
      <a-form-item label="选手姓名">
        <a-input
          v-model:value="searchParams.playerName"
          placeholder="请输入选手姓名"
          allow-clear
          style="width: 160px"
        />
      </a-form-item>
      <a-form-item label="报名账号">
        <a-input
          v-model:value="searchParams.accountNo"
          placeholder="请输入报名账号"
          allow-clear
          style="width: 160px"
        />
      </a-form-item>
      <a-form-item label="作品编号">
        <a-input
          v-model:value="searchParams.workNo"
          placeholder="请输入作品编号"
          allow-clear
          style="width: 160px"
        />
      </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 === 'workNo'">
          <a class="work-link" @click="handleViewWork(record)">{{
            record.workNo || "-"
          }}</a>
        </template>
        <template v-else-if="column.key === 'accountNo'">
          {{ record.registration?.user?.username || "-" }}
        </template>
        <template v-else-if="column.key === 'playerName'">
          {{ record.registration?.user?.nickname || "-" }}
        </template>
        <template v-else-if="column.key === 'submitTime'">
          {{ formatDateTime(record.submitTime) }}
        </template>
        <template v-else-if="column.key === 'reviewProgress'">
          <a-tag :color="getProgressColor(record.reviewProgress)">
            {{ record.reviewProgress }}
          </a-tag>
        </template>
      </template>
    </a-table>

    <!-- 作品详情抽屉 -->
    <a-drawer
      v-model:open="workModalVisible"
      placement="right"
      width="600px"
      :footer-style="{ textAlign: 'right', padding: '16px 24px' }"
      @close="workModalVisible = false"
    >
      <template #title>
        <div class="drawer-title">
          {{ currentWork?.workNo || '-' }} - {{ currentWork?.title || '作品详情' }}
        </div>
      </template>

      <a-spin :spinning="workDetailLoading">
        <div v-if="currentWork" class="work-detail">
          <!-- 提交时间 -->
          <div class="work-section">
            <div class="section-label">提交时间</div>
            <div class="section-content">{{ formatDateTime(currentWork.submitTime) }}</div>
          </div>

          <!-- 作品介绍 -->
          <div class="work-section">
            <div class="section-label">作品介绍</div>
            <div class="section-content description-text">
              {{ currentWork.description || '暂无介绍' }}
            </div>
          </div>

          <!-- 参赛作品 -->
          <div class="work-section">
            <div class="section-label">参赛作品</div>
            <div class="work-file-container">
              <div v-if="workFile" class="work-image-item">
                <div class="image-wrapper">
                  <img
                    v-if="isImageFile(workFile)"
                    :src="getFileUrl(workFile)"
                    alt="作品图片"
                    class="work-image"
                    @click="handlePreviewImage(workFile)"
                  />
                  <div v-else-if="is3DModelFile(workFile)" class="file-placeholder model-file">
                    <FileOutlined class="file-icon" />
                    <span class="file-name">{{ getFileName(workFile) }}</span>
                    <a-button
                      type="primary"
                      size="small"
                      class="preview-btn"
                      @click.stop="handlePreview3DModel(workFile)"
                    >
                      <template #icon><EyeOutlined /></template>
                      预览3D模型
                    </a-button>
                  </div>
                  <div v-else class="file-placeholder">
                    <FileOutlined class="file-icon" />
                    <span class="file-name">{{ getFileName(workFile) }}</span>
                    <a-button type="link" size="small" @click="handleDownloadFile(workFile)">
                      <DownloadOutlined /> 下载
                    </a-button>
                  </div>
                </div>
              </div>
              <div v-else class="no-files">暂无作品文件</div>
            </div>
          </div>

          <!-- 作品信息 -->
          <div class="work-section">
            <div class="section-label">作品信息</div>
            <div class="work-info">
              <div class="info-item">
                <span class="info-label">作品编号：</span>
                <span class="info-value">{{ currentWork.workNo || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">所属活动：</span>
                <span class="info-value">{{ currentWork.contest?.contestName || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">提交人：</span>
                <span class="info-value">{{ currentWork.registration?.user?.nickname || currentWork.submitterAccountNo || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">报名账号：</span>
                <span class="info-value">{{ currentWork.registration?.user?.username || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">评审进度：</span>
                <a-tag :color="getProgressColor(currentWork.reviewProgress || '未分配')">
                  {{ currentWork.reviewProgress || '未分配' }}
                </a-tag>
              </div>
              <div v-if="currentWork.averageScore !== null && currentWork.averageScore !== undefined" class="info-item">
                <span class="info-label">当前得分：</span>
                <span class="score-text">{{ currentWork.averageScore?.toFixed(2) }} 分</span>
              </div>
            </div>
          </div>

          <!-- 上传附件 -->
          <div v-if="workAttachments.length > 0" class="work-section">
            <div class="section-label">上传附件</div>
            <div class="attachments-list">
              <div
                v-for="(att, index) in workAttachments"
                :key="index"
                class="attachment-item"
              >
                <div class="attachment-info">
                  <FileOutlined class="attachment-icon" />
                  <span class="attachment-name">{{ att.fileName }}</span>
                  <span v-if="att.size" class="attachment-size">({{ formatFileSize(att.size) }})</span>
                </div>
                <a-button type="link" size="small" @click="handleDownloadAttachment(att)">
                  <DownloadOutlined /> 下载
                </a-button>
              </div>
            </div>
          </div>
        </div>
      </a-spin>

      <template #footer>
        <a-button @click="workModalVisible = false">关闭</a-button>
      </template>
    </a-drawer>

    <!-- 图片预览 -->
    <a-image
      :style="{ display: 'none' }"
      :preview="{
        visible: previewVisible,
        onVisibleChange: (vis: boolean) => (previewVisible = vis),
      }"
      :src="previewImageUrl"
    />

  </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 {
  ArrowLeftOutlined,
  SearchOutlined,
  ReloadOutlined,
  FileOutlined,
  DownloadOutlined,
  EyeOutlined,
} from "@ant-design/icons-vue"
import {
  worksApi,
  type GuidedWork,
  type QueryGuidedWorkParams,
  type ContestWork,
} from "@/api/contests"
import dayjs from "dayjs"

const router = useRouter()
const route = useRoute()
const tenantCode = route.params.tenantCode as string
const contestId = route.query.contestId
  ? Number(route.query.contestId)
  : undefined

// 加载状态
const loading = ref(false)
const dataSource = ref<GuidedWork[]>([])

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
})

// 搜索参数
const searchParams = reactive<QueryGuidedWorkParams>({
  contestId,
  playerName: "",
  accountNo: "",
  workNo: "",
})

// 作品详情抽屉
const workModalVisible = ref(false)
const workDetailLoading = ref(false)
const currentWork = ref<(ContestWork & { reviewProgress?: string; averageScore?: number }) | null>(null)

// 图片预览
const previewVisible = ref(false)
const previewImageUrl = ref("")

// 作品文件（取第一个）
const workFile = computed(() => {
  if (!currentWork.value) return null
  let files = currentWork.value.files || []

  // 如果 files 是字符串（JSON），需要解析
  if (typeof files === 'string') {
    try {
      files = JSON.parse(files)
    } catch {
      return null
    }
  }

  if (!Array.isArray(files) || files.length === 0) return null

  // 处理可能是对象 {fileUrl: string} 或字符串的情况
  const firstFile = files[0]
  return typeof firstFile === 'object' && firstFile?.fileUrl
    ? firstFile.fileUrl
    : firstFile
})

// 解析附件列表
const workAttachments = computed(() => {
  if (!currentWork.value) return []

  // 优先使用 attachments 数组
  if (currentWork.value.attachments && currentWork.value.attachments.length > 0) {
    return currentWork.value.attachments
  }

  return []
})

// 判断是否为图片文件
const isImageFile = (fileUrl: string): boolean => {
  if (!fileUrl) return false
  const imageExtensions = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".svg"]
  const lowerUrl = fileUrl.toLowerCase()
  return imageExtensions.some((ext) => lowerUrl.includes(ext))
}

// 判断是否为3D模型文件
const is3DModelFile = (fileUrl: string): boolean => {
  if (!fileUrl) return false
  const modelExtensions = [".glb", ".gltf", ".obj", ".fbx", ".3ds", ".dae", ".stl", ".ply"]
  const lowerUrl = fileUrl.toLowerCase()
  return modelExtensions.some((ext) => lowerUrl.includes(ext))
}

// 获取文件URL
const getFileUrl = (fileUrl: string): string => {
  if (!fileUrl) return ""
  if (fileUrl.startsWith("http://") || fileUrl.startsWith("https://")) {
    return fileUrl
  }
  const baseURL = import.meta.env.VITE_API_BASE_URL || ""
  return `${baseURL}${fileUrl.startsWith("/") ? "" : "/"}${fileUrl}`
}

// 获取文件名
const getFileName = (fileUrl: string): string => {
  if (!fileUrl) return "文件"
  try {
    const urlWithoutQuery = fileUrl.split("?")[0].split("#")[0]
    const parts = urlWithoutQuery.split("/")
    let fileName = parts[parts.length - 1] || "文件"
    try {
      fileName = decodeURIComponent(fileName)
    } catch {
      // ignore
    }
    return fileName
  } catch {
    return "文件"
  }
}

// 预览图片
const handlePreviewImage = (fileUrl: string) => {
  previewImageUrl.value = getFileUrl(fileUrl)
  previewVisible.value = true
}

// 下载文件
const handleDownloadFile = (fileUrl: string) => {
  const url = getFileUrl(fileUrl)
  const link = document.createElement("a")
  link.href = url
  link.download = getFileName(fileUrl)
  link.target = "_blank"
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 下载附件
const handleDownloadAttachment = (attachment: any) => {
  const url = getFileUrl(attachment.fileUrl)
  const link = document.createElement("a")
  link.href = url
  link.download = attachment.fileName
  link.target = "_blank"
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 预览3D模型
const handlePreview3DModel = (fileUrl: string) => {
  console.log("handlePreview3DModel called with:", fileUrl)
  if (!fileUrl) {
    message.error("文件路径无效")
    return
  }
  const fullUrl = getFileUrl(fileUrl)
  console.log("预览3D模型，原始URL:", fileUrl, "完整URL:", fullUrl)
  // 跳转到模型查看器页面
  const tenantCode = route.params.tenantCode as string
  router.push({
    path: `/${tenantCode}/workbench/model-viewer`,
    query: { url: fullUrl },
  })
}

// 表格列定义
const columns = [
  {
    title: "序号",
    key: "index",
    width: 70,
    align: "center" as const,
  },
  {
    title: "作品编号",
    key: "workNo",
    dataIndex: "workNo",
    width: 180,
  },
  {
    title: "报名账号",
    key: "accountNo",
    width: 150,
  },
  {
    title: "选手姓名",
    key: "playerName",
    width: 120,
  },
  {
    title: "递交时间",
    key: "submitTime",
    width: 180,
  },
  {
    title: "评审进度",
    key: "reviewProgress",
    width: 120,
    align: "center" as const,
  },
]

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

// 格式化文件大小
const formatFileSize = (size?: string | number) => {
  if (!size) return ""
  const bytes = typeof size === "string" ? parseInt(size) : size
  if (isNaN(bytes)) return ""
  if (bytes < 1024) return bytes + " B"
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + " KB"
  return (bytes / (1024 * 1024)).toFixed(2) + " MB"
}

// 获取进度颜色
const getProgressColor = (progress: string) => {
  if (progress === "未分配") return "default"
  const [reviewed, total] = progress.split("/").map(Number)
  if (reviewed === 0) return "warning"
  if (reviewed >= total) return "success"
  return "processing"
}

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

    if (searchParams.playerName) {
      params.playerName = searchParams.playerName
    }
    if (searchParams.accountNo) {
      params.accountNo = searchParams.accountNo
    }
    if (searchParams.workNo) {
      params.workNo = searchParams.workNo
    }

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

// 查看作品详情
const handleViewWork = async (record: GuidedWork) => {
  workModalVisible.value = true
  workDetailLoading.value = true
  currentWork.value = null

  try {
    const detail = await worksApi.getDetail(record.id)
    currentWork.value = {
      ...detail,
      reviewProgress: record.reviewProgress,
      averageScore: record.averageScore,
    }
  } catch (error) {
    message.error("获取作品详情失败")
  } finally {
    workDetailLoading.value = false
  }
}

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

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

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

// 返回
const handleBack = () => {
  router.push(`/${tenantCode}/activities`)
}

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

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

.page-header {
  display: flex;
  align-items: center;
}

.back-btn {
  padding: 0;
  margin-right: 8px;
}

.page-title {
  font-size: 16px;
  font-weight: 500;
}

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

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

.work-link {
  color: #1890ff;
  cursor: pointer;
}

.work-link:hover {
  text-decoration: underline;
}

/* 抽屉样式 */
.drawer-title {
  font-size: 16px;
  font-weight: 500;
}

.work-detail {
  padding: 0;
}

.work-section {
  margin-bottom: 24px;
}

.work-section:last-child {
  margin-bottom: 0;
}

.section-label {
  font-size: 14px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 12px;
}

.section-content {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
  line-height: 1.6;
}

.description-text {
  white-space: pre-wrap;
  word-break: break-word;
}

.work-file-container {
  display: flex;
  justify-content: flex-start;
}

.work-image-item {
  position: relative;
  width: 300px;
  height: 300px;
}

.image-wrapper {
  width: 100%;
  height: 100%;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafafa;
}

.image-wrapper:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.work-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px;
  color: rgba(0, 0, 0, 0.45);
  position: relative;
}

.file-placeholder.model-file {
  padding-bottom: 60px;
}

.preview-btn {
  position: absolute;
  bottom: 12px;
  left: 50%;
  transform: translateX(-50%);
}

.file-icon {
  font-size: 48px;
  margin-bottom: 8px;
}

.file-name {
  font-size: 12px;
  text-align: center;
  word-break: break-word;
  margin-bottom: 8px;
}

.no-files {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
  padding: 20px 0;
}

.work-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.info-label {
  color: rgba(0, 0, 0, 0.65);
  margin-right: 8px;
  min-width: 80px;
}

.info-value {
  color: rgba(0, 0, 0, 0.85);
}

.score-text {
  font-size: 16px;
  font-weight: 600;
  color: #1890ff;
}

.attachments-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.attachment-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  transition: all 0.3s;
}

.attachment-item:hover {
  border-color: #1890ff;
  background: #f0f7ff;
}

.attachment-info {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.attachment-icon {
  font-size: 16px;
  color: #1890ff;
  margin-right: 8px;
}

.attachment-name {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.85);
  margin-right: 8px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.attachment-size {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  white-space: nowrap;
}
</style>
