<script setup>
import { getScoreDetail, updateScore } from '../api'
import { ElMessage } from 'element-plus'
import { useChat } from '@ezijing/ai-vue'
import { generatePrompt } from '../prompt'
import { generatePrompt as generatePrompt2 } from '../prompt2'
import { cloneDeep } from 'lodash-es'
import { useUserStore } from '@/stores/user'
import { useEventListener } from '@vueuse/core'

const router = useRouter()
const userStore = useUserStore()

const CompetitionLive = defineAsyncComponent(() => import('../components/CompetitionLive.vue'))
const CompetitionLiveProd = defineAsyncComponent(() => import('../components/CompetitionLiveProd.vue'))
const CompetitionLive3 = defineAsyncComponent(() => import('../components/CompetitionLive3.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 competitionRule = computed(() => {
  const competition_rule = detail.value?.competition_rule || {}
  if (competition_rule.config) {
    const config = JSON.parse(competition_rule.config)
    return { ...competition_rule, ...config }
  } else {
    return competition_rule
  }
})

// 所有评分人的评分列表
let scores = []
const fetchDetail = async () => {
  const res = await getScoreDetail({ id })
  const resDetail = res.data.detail
  // 仅保留两条记录，并按时间顺序排序
  resDetail.live_data.practices = resDetail.live_data.practices.slice(0, 2).reverse()
  detail.value = resDetail
  try {
    const parsed = resDetail.score_details ? 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 && !item.is_ai)?.scores
  const aiScore = scores.find((item) => item.is_ai)?.scores
  Object.assign(scoreDetails, cloneDeep(myScore || aiScore || {}))
}

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 && !item.is_ai)), 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,
    check_status: status,
    total_score: totalAverageScore,
    score_details: JSON.stringify(scores),
  })
}
const handlePublishScore = async () => {
  await commitScore(2)
  ElMessage.success('提交成绩成功')
  router.push('../score')
}

onMounted(() => {
  updateScore({ id, check_status: 1 })
})

onBeforeUnmount(() => {
  updateScore({ id, check_status: 2 })
})

useEventListener(window, 'pagehide', () => {
  const formData = new FormData()
  formData.append('id', id)
  formData.append('check_status', '2')
  formData.append('experiment_id', route.query.experiment_id)

  navigator.sendBeacon('/api/lab/v1/experiment/live-student-record/score', formData)
})
</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"
            :loading="isLoading"
            @click="handleAIScore"
            v-if="detail.competition_rule?.competition == 1"
            v-show="false"
            >AI一键评分</el-button
          >
          <el-button type="primary" @click="handlePublishScore">提交成绩</el-button>
        </el-form-item>
      </el-form>
      <div class="score-box">
        <span>{{ totalScore || '--' }}分</span>
      </div>
    </div>
    <el-divider />
    <!-- 网络主播赛项 -->
    <template v-if="competitionRule.competition == 1">
      <!-- “悦颜坊”美妆护肤案例 -->
      <CompetitionLive
        :detail="detail"
        @save="handleSave"
        v-model:scoreDetails="scoreDetails"
        v-if="competitionRule.questions == 1" />
      <!-- 襄阳牛肉面2桶装（有牛肉） -->
      <CompetitionLiveProd :detail="detail" @save="handleSave" v-model:scoreDetails="scoreDetails" v-else />
    </template>
    <!-- 全媒体运营赛项 -->
    <CompetitionOperations
      :detail="detail"
      @save="handleSave"
      v-model:scoreDetails="scoreDetails"
      v-else-if="competitionRule.competition == 2" />
    <!-- 互联网营销师（直播销售） -->
    <CompetitionLive3
      :detail="detail"
      @save="handleSave"
      v-model:scoreDetails="scoreDetails"
      v-else-if="competitionRule.competition == 3" />
  </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>
