import { getScoreList, getScoreDetail, updateScore } from '../api'
import { useUserStore } from '@/stores/user'
import { useChat } from '@ezijing/ai-vue'
import { generatePrompt } from '../prompt'
import { generatePrompt as generatePrompt2 } from '../prompt2'

interface ScoreDetail {
  is_ai?: boolean
  checker_id?: string
  checker_name?: string
  scores: Record<string, ScoreItem>
  total_score: number
  updated_at: string
}

interface ScoreItem {
  score: number
  comment: string
}

export function useScore() {
  const userStore = useUserStore()
  const isLoading = ref(false)
  const { generateText } = useChat({ provider: 'volcano' })

  const fetchScoreList = async () => {
    const res = await getScoreList({ 'per-page': 200, check_status: 0 })
    return res.data.list
  }

  const fetchScoreDetail = async (id: string) => {
    const res = await getScoreDetail({ id })
    const detail = res.data.detail
    // 仅保留两条记录，并按时间顺序排序
    detail.live_data.practices = detail.live_data.practices.slice(0, 2).reverse()
    const parsed = detail.score_details ? JSON.parse(detail.score_details) : []
    const scores = Array.isArray(parsed) ? parsed : []
    return { ...detail, scores }
  }

  const handleAIScoreList = async () => {
    isLoading.value = true
    const list = await fetchScoreList()
    for (const item of list) {
      console.log('AI评分中', item.id)
      const detail = await fetchScoreDetail(item.id)
      // 修改为评分中
      await updateScore({ id: detail.id, check_status: 1 })
      await handleAIScore(detail)
    }
    isLoading.value = false
  }

  const handleAIScore = async (detail: any) => {
    const prompt =
      detail.competition_rule?.questions == 1 ? generatePrompt(detail.live_data) : generatePrompt2(detail.live_data)

    const result = await generateText({ prompt, response_format: { type: 'json_object' } } as any)
    if (!result) return

    try {
      const scoreDetails: Record<string, ScoreItem> = JSON.parse(result.content)
      const totalScore = Object.values(scoreDetails).reduce((acc, curr) => acc + (curr.score || 0), 0)
      console.log(scoreDetails)
      const myScore: ScoreDetail = {
        is_ai: true,
        checker_id: userStore.user?.id,
        checker_name: userStore.user?.name,
        scores: scoreDetails,
        total_score: totalScore,
        updated_at: new Date().toLocaleString(),
      }
      const scores = [...detail.scores.filter((item: any) => 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
      await updateScore({
        id: detail.id,
        check_status: 2,
        total_score: totalAverageScore,
        score_details: JSON.stringify(scores),
      })
      console.log('AI评分完成', {
        id: detail.id,
        check_status: 2,
        total_score: totalAverageScore,
        score_details: JSON.stringify(scores),
      })
    } catch (error) {
      console.log('评分失败', error)
    }
  }

  return { isLoading, fetchScoreList, fetchScoreDetail, handleAIScoreList, handleAIScore }
}
