<script setup>
import { getScoreDetail, updateScore } from '../api'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useChat } from '@ezijing/ai-vue'
import { generatePrompt } from '../prompt'
import { generatePrompt as generatePrompt2 } from '../prompt2'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const CompetitionLive = defineAsyncComponent(() => import('../components/CompetitionLive.vue'))
const CompetitionLiveProd = defineAsyncComponent(() => import('../components/CompetitionLiveProd.vue'))
const CompetitionOperations = defineAsyncComponent(() => import('../components/CompetitionOperations.vue'))
const route = useRoute()
const id = route.query.id

const { isLoading, generateText } = useChat({ provider: 'volcano' })

const detail = ref(null)

const scoreDetails = reactive({})

const totalScore = computed(() => {
  return Object.values(scoreDetails).reduce((acc, curr) => acc + (curr.score || 0), 0)
})

// 所有评分人的评分列表
let scores = []
const fetchDetail = async () => {
  const res = await getScoreDetail({ id })
  const resDetail = res.data.detail
  detail.value = resDetail
  try {
    const parsed = JSON.parse(resDetail.score_details)
    scores = Array.isArray(parsed) ? parsed : []
  } catch (error) {
    console.log('评分列表解析失败', error)
    scores = []
  }
  const myScore = scores.find((item) => item.checker_id == userStore.user.id)?.scores
  const firstScore = { ...scores[0]?.scores }
  Object.assign(scoreDetails, myScore || firstScore || {})
}

onMounted(() => {
  fetchDetail()
})

const handleAIScore = async () => {
  console.log('AI一键评分')
  const prompt =
    detail.value.competition_rule?.questions == 1
      ? generatePrompt(detail.value.live_data)
      : generatePrompt2(detail.value.live_data)
  const result = await generateText({ prompt, response_format: { type: 'json_object' } })
  try {
    const parsed = JSON.parse(result.content)
    Object.assign(scoreDetails, parsed)
    commitScore(1, true).then(() => {
      ElMessage.success('保存成功')
    })
  } catch (error) {
    console.log(error)
    ElMessage.error('评分失败')
    return
  }
}

const handleSave = () => {
  commitScore().then(() => {
    ElMessage.success('保存成功')
  })
}

const commitScore = (status = 1, isAI = false) => {
  const myScore = {
    is_ai: isAI,
    checker_id: userStore.user.id,
    checker_name: userStore.user.name,
    scores: scoreDetails,
    total_score: totalScore.value,
    updated_at: new Date().toLocaleString(),
  }

  // 去掉当前评分人的评分，并添加当前评分人的评分
  scores = [...scores.filter((item) => item.checker_id != userStore.user.id), myScore]

  // 总平均分,过滤掉AI评分
  const validScores = scores.filter((item) => !item.is_ai)
  const totalAverageScore = validScores.reduce((acc, curr) => acc + (curr.total_score || 0), 0) / validScores.length

  return updateScore({
    id: route.query.id,
    check_status: status,
    total_score: totalAverageScore,
    score_details: JSON.stringify(scores),
  })
}
const handlePublishScore = () => {
  ElMessageBox.confirm('确定要发布成绩吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await commitScore(2)
    await fetchDetail()
    ElMessage.success('发布成绩成功')
  })
}
</script>
<template>
  <AppCard title="成绩管理" v-if="detail">
    <div class="score-header">
      <el-form label-suffix=":" inline class="info">
        <el-form-item label="姓名">{{ detail.student_name }}</el-form-item>
        <el-form-item label="专业">{{ detail.specialty_name }}</el-form-item>
        <el-form-item label="班级">{{ detail.class_name }}</el-form-item>
        <el-form-item label="状态">{{ detail.check_status_name }}</el-form-item>
        <el-form-item label="提交时间">{{ detail.commit_time }}</el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :disabled="detail.check_status == '2'"
            :loading="isLoading"
            @click="handleAIScore"
            v-if="detail.competition_rule?.competition == 1"
            >AI一键评分</el-button
          >
          <el-button type="primary" :disabled="detail.check_status == '2'" @click="handlePublishScore"
            >发布成绩</el-button
          >
        </el-form-item>
      </el-form>
      <div class="score-box">
        <span>{{ totalScore || '--' }}分</span>
      </div>
    </div>
    <el-divider />
    <template v-if="detail.competition_rule?.competition == 1">
      <CompetitionLive
        :detail="detail"
        @save="handleSave"
        v-model:scoreDetails="scoreDetails"
        v-if="detail.competition_rule?.questions == 1" />
      <CompetitionLiveProd :detail="detail" @save="handleSave" v-model:scoreDetails="scoreDetails" v-else />
    </template>
    <CompetitionOperations :detail="detail" @save="handleSave" v-model:scoreDetails="scoreDetails" v-else />
  </AppCard>
</template>

<style lang="scss" scoped>
.score-tabs {
  :deep(.el-tabs__header) {
    width: 1000px;
    margin: 0 auto 20px;
  }
  :deep(.el-tabs__nav-wrap::after) {
    display: none;
  }
}
.score-header {
  display: flex;
  align-items: center;
  .el-form {
    flex: 1;
  }
}
.score-box {
  width: 100px;
  border: 1px solid #dcdfe6;
  padding: 10px;
  border-radius: 10px;
  font-size: 30px;
  color: var(--main-color);
  display: flex;
  align-items: center;
  justify-content: center;
}
.table-expand-box {
  border: 1px solid #dcdfe6;
  padding: 20px;
  border-radius: 10px;
}
.form-box {
  width: 100%;
  border: 1px solid #dcdfe6;
  padding: 10px;
  border-radius: 6px;
}
</style>
