<script setup>
import { getScoreDetail, updateScore } from '../api'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useChat } from '@ezijing/ai-vue'
import { generatePrompt } from '../prompt'

const CompetitionLive = defineAsyncComponent(() => import('../components/CompetitionLive.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)
})

const fetchDetail = async () => {
  const res = await getScoreDetail({ id })
  detail.value = res.data.detail
  Object.assign(scoreDetails, res.data.detail.score_details ? JSON.parse(res.data.detail.score_details) : {})
}

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

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

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

const commitScore = (status = 0) => {
  return updateScore({
    id: route.query.id,
    score_status: status,
    total_score: totalScore.value,
    score_details: JSON.stringify(scoreDetails),
  })
}

const handlePublishScore = () => {
  ElMessageBox.confirm('确定要发布成绩吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await commitScore(1)
    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.status_name }}</el-form-item>
        <el-form-item label="提交时间">{{ detail.commit_time }}</el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :disabled="detail.status == '2'"
            :loading="isLoading"
            @click="handleAIScore"
            v-if="detail.competition_rule?.competition == 1"
            >AI一键评分</el-button
          >
          <el-button type="primary" :disabled="detail.status == '2'" @click="handlePublishScore">发布成绩</el-button>
        </el-form-item>
      </el-form>
      <div class="score-box">
        <span>{{ totalScore || '--' }}分</span>
      </div>
    </div>
    <el-divider />
    <CompetitionLive
      :detail="detail"
      @save="handleSave"
      v-model:scoreDetails="scoreDetails"
      v-if="detail.competition_rule?.competition == 1" />
    <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>
