import { fetchEventSource } from '@fortaine/fetch-event-source'
import { getAIUsage, postGenerateImage } from '../api'
import type { Message } from '../types'
import { ElMessage } from 'element-plus'

export function useChat(options: any) {
  const messages = ref<Message[]>([])
  const chatId = ref<string | null>(null)
  const isLoading = ref(false)

  const usages = ref({
    chart_count: 0,
    ai_creation_count: 2,
    ai_polish_count: 0,
    ai_expand_count: 0,
    ai_refresh_count: 0,
    experiment_id: 121,
    chart_max_count: 20,
    ai_creation_max_count: 5,
    ai_polish_max_count: 5,
    ai_expand_max_count: 5,
    ai_refresh_max_count: 5
  })

  async function fetchUsages() {
    const res = await getAIUsage(options)
    usages.value = res.data.detail
  }

  onMounted(() => {
    fetchUsages()
  })

  async function post(data: any) {
    if (options.fileType == 1) {
      await generateText(data)
    } else {
      await generateImage(data)
    }
  }

  // 生成文本
  // async function generateText(data: any) {
  //   isLoading.value = true
  //   await fetchEventSource('/api/lab/v1/experiment/marketing-ai/sky-agents-chat', {
  //     method: 'POST',
  //     headers: {
  //       'Content-Type': 'application/json'
  //     },
  //     body: JSON.stringify({ ...options, ...data, context: data.content, chart_id: chatId.value }),
  //     async onopen(response) {
  //       if (response.ok) {
  //         return
  //       } else {
  //         throw response
  //       }
  //     },
  //     onmessage(res) {
  //       const message = JSON.parse(res.data)
  //       if (message.code === 0) {
  //         ElMessage.error(message.message)
  //         return
  //       }
  //       chatId.value = message.chatId + ''
  //       const conversationId = message.conversationId
  //       const messageIndex = messages.value.findIndex(session => session.conversationId === conversationId)
  //       const content = message.content || ''
  //       // if (message.content === '\n') content = '<br/>'
  //       if (messageIndex === -1) {
  //         messages.value.push({ conversationId, role: 'bot', content, input: data.context })
  //       } else {
  //         messages.value[messageIndex].content = messages.value[messageIndex].content + content
  //       }
  //       isLoading.value = false
  //     },
  //     onclose() {
  //       fetchUsages()
  //       isLoading.value = false
  //     },
  //     onerror(err) {
  //       console.log(err)
  //       isLoading.value = false
  //       throw err
  //     }
  //   })
  // }
  async function generateText(data: any) {
    isLoading.value = true
    let params = {}
    if (data.type === '1') {
      params = {
        chat_history: messages.value
      }
    } else {
      const docAction: any = {
        2: 'write',
        3: 'rewrite',
        4: 'expand',
        5: 'rewrite',
        7: 'abbreviate',
        8: 'summary'
      }
      params = {
        content: data.content,
        doc_action: docAction[data.type],
        full_text: !!(data.type === 2)
      }
    }
    await fetchEventSource('/api/lab/v1/experiment/marketing-ai/sky-agent3-chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        ...options, ...data, api_type: parseInt(data.type) === 1 ? 1 : 2, context: data.content, params: params
      }),
      async onopen(response) {
        if (response.ok) {
          return
        } else {
          throw response
        }
      },
      onmessage(res) {
        const message = JSON.parse(res.data)
        // 聊天返回内容
        if (data.type === '1') {
          if (message.code === 0) {
            ElMessage.error(message.message)
            return
          }
          const conversationId = message.conversation_id
          const messageIndex = messages.value.findIndex(session => session.conversationId === conversationId)
          const content = message?.arguments?.reduce((a: any, b: any) => {
            a = b?.messages[0]?.text || ''
            return a
          }, '')
          if (messageIndex === -1) {
            messages.value.push({ conversationId, role: 'bot', content, input: data.context })
          } else {
            if (content) {
              messages.value[messageIndex].content = content
            }
          }
        } else {
          // 按钮功能返回内容
          const requestId = message.request_id
          const messageIndex = messages.value.findIndex(session => session.conversationId === requestId)
          if (messageIndex === -1) {
            messages.value.push({ conversationId: requestId, role: 'bot', content: message.data?.text || '', input: data.context })
          } else {
            messages.value[messageIndex].content = message.data?.text
          }
        }
        isLoading.value = false
      },
      onclose() {
        fetchUsages()
        isLoading.value = false
      },
      onerror(err) {
        console.log(err)
        isLoading.value = false
        throw err
      }
    })
  }

  // 生成图片
  async function generateImage(data: any) {
    isLoading.value = true
    try {
      const res = await postGenerateImage({ ...options, ...data })
      if (res.data.detail.image_url) {
        messages.value.push({ type: 'image', role: 'bot', ...res.data.detail })
      } else {
        ElMessage.error(res.data.detail.failure_reason)
      }
      fetchUsages()
    } catch (error) {
      console.log(error)
    }
    isLoading.value = false
  }

  return { usages, chatId, messages, post, generateImage, isLoading }
}
