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'
import { ElMessage } from 'element-plus'

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 liveData = detail.live_data
    const competitionRule = detail.competition_rule

    let prompt = ''
    if (competitionRule?.competition == 1) {
      if (competitionRule?.questions == 1) {
        prompt = generatePrompt(detail.live_data)
      } else {
        prompt = generatePrompt2(detail.live_data)
      }
    } else {
      const rules = JSON.parse(competitionRule?.config || '{}')?.rules || []
      rules.forEach((item: any) => {
        if (item.rule_mode != 2) return

        if (item.type == 1) {
          prompt += `请根据选手提交的商品品类信息进行评分（满分${item.percent}分）：
         选手提交内容：
${JSON.stringify(liveData.commodity_types)}`
        } else if (item.type == 2) {
          prompt += `请根据选手提交的商品属性配置信息进行评分（满分${item.percent}分）：
         选手提交内容：
${JSON.stringify(liveData.commodity_attrs)}`
        } else if (item.type == 3) {
          prompt += `请根据选手提交的商品信息维护内容进行评分（满分${item.percent}分）：
         选手提交内容：
${JSON.stringify(liveData.commodities)}`
        } else if (item.type == 4) {
          prompt += `请根据选手提交的直播话术进行评分（满分${item.percent}分）：
         选手提交内容：
${JSON.stringify(liveData.speeches)}`
        }
      })
      prompt += `EXAMPLE JSON OUTPUT:
{
  "commodity_type": {
    "score": 5,
    "comment": "这是评语"
  },
  "commodity_attr": {
    "score": 5,
    "comment": "这是评语"
  },
  "commodity": {
    "score": 5,
    "comment": "这是评语"
  }
}`
    }

    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)
    }
  }

  const handleResetScoreStatus = async (id: string) => {
    await updateScore({ id, check_status: 2 })
    ElMessage.success('重置成绩状态成功')
  }

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