<template>
  <div class="student-homework-detail">
    <a-spin :spinning="loading">
      <!-- 顶部返回按钮 -->
      <a-page-header
        :title="homework?.name || '作业详情'"
        @back="handleBack"
      >
        <template #extra>
          <a-tag :color="getSubmitStatusColor()">
            {{ getSubmitStatusText() }}
          </a-tag>
        </template>
      </a-page-header>

      <a-row :gutter="16">
        <!-- 左侧：作业信息 -->
        <a-col :span="14">
          <a-card title="作业信息" class="mb-4">
            <a-descriptions :column="1" bordered>
              <a-descriptions-item label="作业名称">
                {{ homework?.name }}
              </a-descriptions-item>
              <a-descriptions-item label="提交时间">
                {{ formatDateTime(homework?.submitStartTime) }} ~
                {{ formatDateTime(homework?.submitEndTime) }}
              </a-descriptions-item>
              <a-descriptions-item label="作业内容">
                <div class="homework-content" v-html="formatContent(homework?.content)"></div>
              </a-descriptions-item>
              <a-descriptions-item label="附件" v-if="attachments.length > 0">
                <div class="attachment-list">
                  <a
                    v-for="(att, index) in attachments"
                    :key="index"
                    :href="att.fileUrl"
                    target="_blank"
                    class="attachment-item"
                  >
                    <PaperClipOutlined />
                    {{ att.fileName }}
                  </a>
                </div>
              </a-descriptions-item>
            </a-descriptions>
          </a-card>

          <!-- 评审规则（如果有） -->
          <a-card title="评分规则" v-if="homework?.reviewRule" class="mb-4">
            <a-descriptions :column="1" bordered>
              <a-descriptions-item label="规则名称">
                {{ homework.reviewRule.name }}
              </a-descriptions-item>
              <a-descriptions-item label="评分标准">
                <div class="criteria-list">
                  <div
                    v-for="(criterion, index) in reviewCriteria"
                    :key="index"
                    class="criterion-item"
                  >
                    <span class="criterion-name">{{ criterion.name }}</span>
                    <span class="criterion-score">{{ criterion.maxScore }}分</span>
                    <span class="criterion-desc" v-if="criterion.description">
                      {{ criterion.description }}
                    </span>
                  </div>
                </div>
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
        </a-col>

        <!-- 右侧：我的提交 -->
        <a-col :span="10">
          <a-card title="我的提交" class="mb-4">
            <!-- 已提交状态 -->
            <template v-if="submission">
              <a-descriptions :column="1" bordered size="small">
                <a-descriptions-item label="作品名称">
                  {{ submission.workName }}
                </a-descriptions-item>
                <a-descriptions-item label="作品编号">
                  {{ submission.workNo }}
                </a-descriptions-item>
                <a-descriptions-item label="提交时间">
                  {{ formatDateTime(submission.submitTime) }}
                </a-descriptions-item>
                <a-descriptions-item label="作品描述" v-if="submission.workDescription">
                  {{ submission.workDescription }}
                </a-descriptions-item>
                <a-descriptions-item label="提交文件" v-if="submissionFiles.length > 0">
                  <div class="file-list">
                    <a
                      v-for="(file, index) in submissionFiles"
                      :key="index"
                      :href="file.fileUrl"
                      target="_blank"
                      class="file-item"
                    >
                      <FileOutlined />
                      {{ file.fileName }}
                    </a>
                  </div>
                </a-descriptions-item>
                <a-descriptions-item label="得分" v-if="submission.totalScore !== null">
                  <a-tag color="blue" style="font-size: 16px;">
                    {{ submission.totalScore }}分
                  </a-tag>
                </a-descriptions-item>
              </a-descriptions>

              <!-- 评分详情 -->
              <template v-if="submission.scores && submission.scores.length > 0">
                <a-divider>评分详情</a-divider>
                <div v-for="score in submission.scores" :key="score.id" class="score-detail">
                  <div class="score-header">
                    <span>评审人: {{ score.reviewer?.realName || '匿名' }}</span>
                    <span>{{ formatDateTime(score.scoreTime) }}</span>
                  </div>
                  <div class="dimension-scores" v-if="score.dimensionScores">
                    <div
                      v-for="(ds, key) in parseDimensionScores(score.dimensionScores)"
                      :key="key"
                      class="dimension-item"
                    >
                      <span>{{ key }}:</span>
                      <span>{{ ds }}分</span>
                    </div>
                  </div>
                  <div class="score-comments" v-if="score.comments">
                    评语: {{ score.comments }}
                  </div>
                </div>
              </template>
            </template>

            <!-- 未提交状态 -->
            <template v-else>
              <a-result
                v-if="isExpired"
                status="warning"
                title="提交已截止"
                sub-title="很抱歉，作业提交时间已过"
              />

              <template v-else>
                <a-form
                  ref="formRef"
                  :model="submitForm"
                  :rules="formRules"
                  layout="vertical"
                >
                  <a-form-item label="作品名称" name="workName">
                    <a-input
                      v-model:value="submitForm.workName"
                      placeholder="请输入作品名称"
                    />
                  </a-form-item>
                  <a-form-item label="作品描述" name="workDescription">
                    <a-textarea
                      v-model:value="submitForm.workDescription"
                      placeholder="请输入作品描述"
                      :rows="4"
                    />
                  </a-form-item>
                  <a-form-item label="作品文件" name="files">
                    <a-upload
                      v-model:file-list="submitForm.fileList"
                      :before-upload="beforeUpload"
                      :custom-request="customUpload"
                    >
                      <a-button>
                        <template #icon><UploadOutlined /></template>
                        上传文件
                      </a-button>
                    </a-upload>
                  </a-form-item>
                  <a-form-item>
                    <a-button
                      type="primary"
                      block
                      :loading="submitting"
                      @click="handleSubmit"
                    >
                      提交作业
                    </a-button>
                  </a-form-item>
                </a-form>
              </template>
            </template>
          </a-card>
        </a-col>
      </a-row>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from "vue"
import { useRouter, useRoute } from "vue-router"
import { message } from "ant-design-vue"
import type { FormInstance, UploadProps } from "ant-design-vue"
import {
  PaperClipOutlined,
  FileOutlined,
  UploadOutlined,
} from "@ant-design/icons-vue"
import {
  homeworksApi,
  submissionsApi,
  type Homework,
  type HomeworkSubmission,
  type HomeworkAttachment,
} from "@/api/homework"
import { uploadApi } from "@/api/upload"
import dayjs from "dayjs"

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

const loading = ref(false)
const homework = ref<Homework | null>(null)
const submission = ref<HomeworkSubmission | null>(null)
const submitting = ref(false)
const formRef = ref<FormInstance>()

// 解析附件
const attachments = computed<HomeworkAttachment[]>(() => {
  if (!homework.value?.attachments) return []
  if (typeof homework.value.attachments === "string") {
    try {
      return JSON.parse(homework.value.attachments)
    } catch {
      return []
    }
  }
  return homework.value.attachments as HomeworkAttachment[]
})

// 解析提交的文件
const submissionFiles = computed<HomeworkAttachment[]>(() => {
  if (!submission.value?.files) return []
  if (typeof submission.value.files === "string") {
    try {
      return JSON.parse(submission.value.files)
    } catch {
      return []
    }
  }
  return submission.value.files as HomeworkAttachment[]
})

// 解析评审标准
const reviewCriteria = computed(() => {
  if (!homework.value?.reviewRule?.criteria) return []
  if (typeof homework.value.reviewRule.criteria === "string") {
    try {
      return JSON.parse(homework.value.reviewRule.criteria)
    } catch {
      return []
    }
  }
  return homework.value.reviewRule.criteria
})

// 是否过期
const isExpired = computed(() => {
  if (!homework.value) return false
  return dayjs().isAfter(dayjs(homework.value.submitEndTime))
})

// 提交表单
const submitForm = reactive<{
  workName: string
  workDescription: string
  fileList: any[]
}>({
  workName: "",
  workDescription: "",
  fileList: [],
})

const formRules = {
  workName: [{ required: true, message: "请输入作品名称" }],
}

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

// 格式化内容（保留换行）
const formatContent = (content?: string) => {
  if (!content) return ""
  return content.replace(/\n/g, "<br/>")
}

// 解析评分维度
const parseDimensionScores = (dimensionScores: any) => {
  if (typeof dimensionScores === "string") {
    try {
      return JSON.parse(dimensionScores)
    } catch {
      return {}
    }
  }
  return dimensionScores || {}
}

// 获取提交状态颜色
const getSubmitStatusColor = () => {
  if (submission.value) return "success"
  if (isExpired.value) return "error"
  return "warning"
}

// 获取提交状态文本
const getSubmitStatusText = () => {
  if (submission.value) return "已提交"
  if (isExpired.value) return "已过期"
  return "待提交"
}

// 返回上一页
const handleBack = () => {
  router.back()
}

// 加载作业详情
const loadHomework = async () => {
  loading.value = true
  try {
    homework.value = await homeworksApi.getDetail(homeworkId)

    // 同时获取我的提交记录
    try {
      const mySubmission = await submissionsApi.getMySubmission(homeworkId)
      submission.value = mySubmission
    } catch {
      // 没有提交记录
      submission.value = null
    }
  } catch (error: any) {
    message.error(error?.response?.data?.message || "获取作业详情失败")
  } finally {
    loading.value = false
  }
}

// 文件上传
const beforeUpload: UploadProps["beforeUpload"] = () => {
  return false
}

const customUpload = async ({ file, onSuccess, onError }: any) => {
  try {
    const formData = new FormData()
    formData.append("file", file)
    const result = await uploadApi.upload(formData)
    file.url = result.url
    onSuccess(result)
  } catch (error) {
    onError(error)
  }
}

// 提交作业
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitting.value = true

    const files = submitForm.fileList.map((file) => ({
      fileName: file.name,
      fileUrl: file.url || file.response?.url,
      size: file.size?.toString(),
    }))

    await submissionsApi.submit({
      homeworkId,
      workName: submitForm.workName,
      workDescription: submitForm.workDescription,
      files,
    })

    message.success("提交成功")
    loadHomework()
  } catch (error: any) {
    if (error?.errorFields) return
    message.error(error?.response?.data?.message || "提交失败")
  } finally {
    submitting.value = false
  }
}

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

<style scoped>
.student-homework-detail {
  padding: 16px;
}

.homework-content {
  white-space: pre-wrap;
  line-height: 1.8;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.attachment-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #1890ff;
}

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

.criterion-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;
  background: #fafafa;
  border-radius: 4px;
}

.criterion-name {
  font-weight: 500;
}

.criterion-score {
  color: #1890ff;
  font-weight: 600;
}

.criterion-desc {
  color: #666;
  font-size: 12px;
}

.file-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #1890ff;
}

.score-detail {
  padding: 12px;
  background: #fafafa;
  border-radius: 8px;
  margin-bottom: 12px;
}

.score-header {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 12px;
  margin-bottom: 8px;
}

.dimension-scores {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 8px;
}

.dimension-item {
  display: flex;
  gap: 4px;
}

.score-comments {
  color: #333;
  font-size: 14px;
  border-top: 1px solid #eee;
  padding-top: 8px;
  margin-top: 8px;
}

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