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'
import {
  importType,
  requiredType,
  deliveryMode,
  deliveryTime,
  orderStockCount,
  shippingTemplate,
  afterSalesPolicy,
} from '@/utils/dictionary'

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 processBatch = async (items: any[], batchSize: number) => {
    const results = []
    for (let i = 0; i < items.length; i += batchSize) {
      const batch = items.slice(i, i + batchSize)
      const batchPromises = batch.map(async (item) => {
        try {
          console.log('AI评分中', item.id)
          const detail = await fetchScoreDetail(item.id)
          // 修改为评分中
          await updateScore({ id: detail.id, check_status: 1 })
          await handleAIScore(detail)
          return { success: true, id: item.id }
        } catch (error) {
          console.error(`AI评分失败 ${item.id}:`, error)
          return { success: false, id: item.id, error }
        }
      })
      const batchResults = await Promise.allSettled(batchPromises)
      results.push(...batchResults)
    }
    return results
  }

  const handleAIScoreList = async () => {
    isLoading.value = true
    try {
      const list = await fetchScoreList()
      // 并发处理，每批处理5个，可以根据需要调整
      const batchSize = 5
      await processBatch(list, batchSize)
      ElMessage.success(`批量评分完成，共处理 ${list.length} 条`)
    } catch (error) {
      console.error('批量评分失败:', error)
      ElMessage.error('批量评分过程中出现错误')
    } finally {
      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(importType)}
必要性字典：${JSON.stringify(requiredType)}

选手提交内容：
${JSON.stringify(liveData.commodity_attrs)}`
        } else if (item.type == 3) {
          prompt += `请根据选手提交的商品信息维护内容进行评分（满分${item.percent}分）：
发货模式字典：${JSON.stringify(deliveryMode)}
发货时效字典：${JSON.stringify(deliveryTime)}
订单库存扣减规则字典：${JSON.stringify(orderStockCount)}
运费模板字典：${JSON.stringify(shippingTemplate)}
售后政策字典：${JSON.stringify(afterSalesPolicy)}

选手提交内容：
${JSON.stringify(liveData.commodities)}`
        } else if (item.type == 4) {
          prompt += `请根据选手提交的直播话术进行评分（满分${item.percent}分）：
选手提交内容：
${JSON.stringify(liveData.speeches)}`
        }
        prompt += `评分标准：
        ${item.content}`
      })

      prompt += `EXAMPLE JSON OUTPUT:
{
  "commodity_type": {
    "score": 5,
    "comment": "这是评语"
  },
  "commodity_attr": {
    "score": 5,
    "comment": "这是评语"
  },
  "commodity": {
    "score": 5,
    "comment": "这是评语"
  }
}`
    }
    const messages = [
      {
        role: 'system',
        content: `你是一位专业的电商运营评分专家，负责对选手的商品信息维护操作进行客观、准确的评分。`,
      },
      { role: 'user', content: prompt },
    ]
    const result = await generateText({ messages, 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 }
}
