<script setup>
import LiveProductCategory from '@/components/LiveProductCategory.vue'
import { getScoreList, getScoreDetail, publishAll, 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 { useIntervalFn } from '@vueuse/core'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const route = useRoute()
const appList = ref(null)

defineProps({ hasAI: { type: Boolean, default: true } })
// 刷新
const handleRefresh = () => {
  appList.value?.refetch()
}
const listParams = reactive({ name: '', check_status: '' })

// 列表配置
const listOptions = computed(() => {
  return {
    remote: { httpRequest: getScoreList, params: listParams },
    filters: [
      { label: '姓名', prop: 'name', type: 'input' },
      {
        label: '状态',
        prop: 'check_status',
        type: 'select',
        options: [
          { label: '暂未评分', value: '0' },
          { label: '评分中', value: '1' },
          { label: '已评分', value: '2' },
          { label: 'AI评分完成', value: '3' },
        ],
      },
    ],
    columns: [
      { label: '序号', type: 'index', width: 60 },
      { label: 'ID', prop: 'id' },
      { label: '姓名', prop: 'student_name' },
      // { label: '专业', prop: 'specialty_name' },
      // { label: '班级', prop: 'class_name' },
      { label: '成绩', prop: 'score_display' },
      { label: '状态', prop: 'check_status_name' },
      {
        label: '评分人',
        prop: 'checker_name',
        computed: ({ row }) => {
          try {
            const scores = row.score_details ? JSON.parse(row.score_details) : []
            return Array.isArray(scores)
              ? scores
                  .filter((item) => !item.is_ai)
                  .map((item) => `${item.checker_name}(${item.total_score})`)
                  .join('<br/>')
              : ''
          } catch (error) {
            console.log('评分人解析失败', error)
            return ''
          }
        },
      },
      { label: '提交时间', prop: 'commit_time' },
      { label: '批改时间', prop: 'commit_time' },
      { label: '操作', slots: 'table-x', width: 120 },
    ],
  }
})

const handleExport = () => {
  window.open(`/api/lab/v1/experiment/live-student-record/export?experiment_id=${route.query.experiment_id}`)
}

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

const handleAIScore = async () => {
  console.log('AI一键评分')
  const res = await getScoreList({ 'per-page': 200, check_status: 0 })
  const list = res.data.list

  list.forEach(async (item) => {
    const detailRes = await getScoreDetail({ id: item.id })
    const detail = detailRes.data.detail
    // 仅保留两条记录，并按时间顺序排序
    detail.live_data.practices = detail.live_data.practices.slice(0, 2).reverse()

    const parsed = detail.score_details ? JSON.parse(detail.score_details) : []
    let scores = Array.isArray(parsed) ? parsed : []

    const prompt =
      detail.competition_rule?.questions == 1 ? generatePrompt(detail.live_data) : generatePrompt2(detail.live_data)
    // 修改为评分中
    updateScore({ id: item.id, check_status: 1 })
    const result = await generateText({ prompt, response_format: { type: 'json_object' } })

    try {
      const scoreDetails = JSON.parse(result.content)
      const totalScore = Object.values(scoreDetails).reduce((acc, curr) => acc + (curr.score || 0), 0)
      console.log(scoreDetails)
      const myScore = {
        is_ai: true,
        checker_id: userStore.user.id,
        checker_name: userStore.user.name,
        scores: scoreDetails,
        total_score: totalScore,
        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

      updateScore({
        id: item.id,
        check_status: 3,
        total_score: totalAverageScore,
        score_details: JSON.stringify(scores),
      }).then(() => {
        console.log('AI评分完成')
      })
    } catch (error) {
      console.log('评分失败', error)
    }
  })
}

const handlePublishScore = () => {
  publishAll().then(() => {
    ElMessage.success('发布成绩成功')
    handleRefresh()
  })
}

useIntervalFn(() => {
  handleRefresh()
}, 5000)
</script>

<template>
  <AppCard title="成绩管理">
    <AppList v-bind="listOptions" ref="appList">
      <template #header-buttons>
        <el-row justify="space-between">
          <el-button type="primary" @click="handleExport">导出成绩</el-button>
          <div>
            <el-button type="primary" @click="handleAIScore" :loading="isLoading" v-if="hasAI">AI一键评分</el-button>
            <el-button type="primary" @click="handlePublishScore" v-if="false">一键发布成绩</el-button>
          </div>
        </el-row>
      </template>

      <template #filter-category>
        <LiveProductCategory v-model="listParams.live_commodity_type_id" @change="handleRefresh"></LiveProductCategory>
      </template>
      <template #table-x="{ row }">
        <el-button text type="primary" v-if="row.check_status != '2'">
          <router-link :to="{ path: '/live/score/view', query: { ...$route.query, id: row.id } }">评分</router-link>
        </el-button>
      </template>
    </AppList>
  </AppCard>
</template>
