import md5 from 'blueimp-md5'
import { useStorage } from '@vueuse/core'
import { fetchEventSource } from '@fortaine/fetch-event-source'
import axios from 'axios'
import { getAIUsage } from '@/api/ai'
import { ElMessage } from 'element-plus'
import { createAIService } from '@ezijing/ai-core'

export function useAI(config) {
  // AI 配置列表
  const options = [
    { label: '文心一言', value: 'yiyan' },
    { label: 'DeepSeek', value: 'deepseek' },
    { label: '通义千问', value: 'qwen' },
    // { label: '天工', value: 'tiangong' },
  ]

  const ai = useStorage('ai', 'tiangong')
  const messages = ref([])
  const isLoading = ref(false)

  async function post(data) {
    isLoading.value = true
    try {
      switch (ai.value) {
        case 'yiyan':
          await yiyan(data)
          break
        case 'deepseek':
          await siliconflow(data)
          break
        case 'qwen':
          await qwen(data)
          break
        case 'tiangong':
          await tiangong(data)
          break
        default:
          throw new Error('未找到对应的 AI 配置')
      }
    } catch (err) {
      console.error('AI 请求失败:', err)
    } finally {
      isLoading.value = false
    }
  }

  // 文心一言
  async function yiyan(data) {
    // 获取token
    const getAccessToken = async () => {
      const AK = 'wY7bvMpkWeZbDVq9w3EDvpjU'
      const SK = 'XJwpiJWxs5HXkOtbo6tQrvYPZFJAWdAy'
      const resp = await axios.post(
        '/api/qianfan/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK
      )
      return resp.data.access_token
    }
    const resp = await axios.post(
      '/api/qianfan/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=' + (await getAccessToken()),
      {
        messages: [{ role: 'user', content: data.content }],
      }
    )
    messages.value.push({ role: 'assistant', content: resp.data.result.replaceAll('\n', '<br/>') })
  }

  // DeepSeek
  // async function deepseek(data) {
  //   const apiKey = 'sk-f1a6f0a7013241de8393cb2cb108e777'
  //   const resp = await axios.post(
  //     '/api/deepseek/chat/completions',
  //     {
  //       model: 'deepseek-chat',
  //       messages: [{ role: 'user', content: data.content }],
  //     },
  //     {
  //       headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
  //     }
  //   )
  //   if (resp.data) {
  //     const [choice = {}] = resp.data.choices
  //     messages.value.push({ role: 'assistant', content: choice.message.content.replaceAll('\n', '<br/>') })
  //   }
  // }

  // 硅基流动
  async function siliconflow(data) {
    const apiKey = 'sk-bivnwauskdbvpspvmdorrgkrpwlyfxbfcezqsfsevowzubdj'
    const resp = await axios.post(
      '/api/siliconflow/v1/chat/completions',
      {
        model: 'deepseek-ai/DeepSeek-V3',
        messages: [{ role: 'user', content: data.content }],
      },
      {
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
      }
    )
    if (resp.data) {
      const [choice = {}] = resp.data.choices
      messages.value.push({ role: 'assistant', content: choice.message.content.replaceAll('\n', '<br/>') })
    }
  }
  // 通义千问
  async function qwen(data) {
    const apiKey = 'sk-afd0fcdb53bf4058b2068b8548820150'
    const resp = await axios.post(
      '/api/qwen/compatible-mode/v1/chat/completions',
      {
        model: 'qwen-max',
        messages: [{ role: 'user', content: data.content }],
      },
      {
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
      }
    )
    if (resp.data) {
      const [choice = {}] = resp.data.choices
      messages.value.push({ role: 'assistant', content: choice.message.content.replaceAll('\n', '<br/>') })
    }
  }

  // 天工
  async function tiangong(data) {
    const appKey = 'a8701b73637562d33a53c668a90ee3be'
    const appSecret = 'e191593f486bb88a39c634f46926762dddc97b9082e192af'
    const timestamp = Math.floor(Date.now() / 1000)
    const sign = md5(`${appKey}${appSecret}${timestamp}`)

    return await fetchEventSource('/api/tiangong/sky-saas-writing/api/v1/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', app_key: appKey, sign, timestamp, stream: 'true' },
      body: JSON.stringify({
        chat_history: [{ role: 'user', content: data.content }],
        stream_resp_type: 'update',
      }),
      async onopen(response) {
        console.log(response)
        if (response.ok) {
          return response
        } else {
          throw response
        }
      },
      onmessage(res) {
        console.log(res.data)
        const message = JSON.parse(res.data)
        if (message.type !== 1) return
        const messageId = message.conversation_id
        const messageIndex = messages.value.findIndex((message) => message.id === messageId)
        const content = message?.arguments?.[0]?.messages?.[0]?.text || ''
        if (messageIndex === -1) {
          messages.value.push({ id: messageId, role: 'assistant', content })
        } else {
          messages.value[messageIndex].content = content
        }
        isLoading.value = false
      },
      onerror(err) {
        isLoading.value = false
        throw err
      },
    })
  }

  const usages = ref({
    chart_count: 0,
    ai_creation_count: 0,
    ai_polish_count: 0,
    ai_expand_count: 0,
    ai_refresh_count: 0,
    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(config)
    usages.value = res.data.detail
  }

  async function generateText(data) {
    isLoading.value = true

    // const docAction = {
    //   2: 'write',
    //   3: 'rewrite',
    //   4: 'expand',
    //   5: 'rewrite',
    //   7: 'abbreviate',
    //   8: 'summary',
    // }
    // const params = {
    //   content: data.content,
    //   doc_action: docAction[data.type],
    //   full_text: !!(data.type === 2),
    // }
    await fetchEventSource('/api/qwen/compatible-mode/v1/chat/completions', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer sk-afd0fcdb53bf4058b2068b8548820150` },
      body: JSON.stringify({ stream: true, model: 'qwen-max', messages: [{ role: 'user', content: data.content }] }),
      async onopen(response) {
        if (response.ok) {
          return response
        } else {
          isLoading.value = false
          // reject(response)
          throw response
        }
      },

      onmessage(res) {
        console.log(res.data)
        if (res.data === '[DONE]') {
          isLoading.value = false
          // resolve(messages.value.at(-1))
          return
        }
        try {
          const message = JSON.parse(res.data)
          if (message.error) {
            ElMessage.error(message.error.message)
            return
          }
          const id = message.id
          const messageIndex = messages.value.findIndex((session) => session.id === id)
          let content = message?.choices[0]?.delta.content || ''
          // if (isReplace) {
          //   content = content.replaceAll('\n', '<br/>')
          // }
          if (messageIndex === -1) {
            messages.value.push({
              conversationId: id,
              id,
              role: 'assistant',
              content: content.replace(/<think>[\s\S]*?<\/think>/g, '').replace(/^((<br\s*\/?>)|\s|\\n|\\r)+/g, ''),
              input: data.context,
            })
          } else {
            messages.value[messageIndex].content = (messages.value[messageIndex].content + content)
              .replace(/<think>[\s\S]*?<\/think>/g, '')
              .replace(/^((<br\s*\/?>)|\s|\\n|\\r)+/g, '')
          }
        } catch (error) {
          console.log(error)
          isLoading.value = false
          // reject(error)
        }
        // 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, b) => {
        //     a = b?.messages[0]?.text || ''
        //     return a
        //   }, '')
        //   if (messageIndex === -1) {
        //     messages.value.push({ conversationId, role: 'assistant', 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: 'assistant',
        //       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) {
    const ai = createAIService('volcano')
    isLoading.value = true
    try {
      const res = await ai.generateImage({ prompt: data.content, watermark: false, response_format: 'b64_json' })
      if (res.url) {
        messages.value.push({
          type: 'image',
          role: 'assistant',
          image_url: res.url,
          content: data.content,
        })
      } else {
        ElMessage.error(res.error)
      }
      fetchUsages()
    } catch (error) {
      console.log(error)
    }
    isLoading.value = false
  }
  return { ai, options, post, messages, isLoading, usages, fetchUsages, generateText, generateImage }
}
