import { ref } from 'vue'
import { useImage } from '@ezijing/ai-vue'

export function useChatImage() {
  const { generateImage, isLoading, error, cancel } = useImage({ provider: 'volcano' })

  // 聊天相关状态
  const messages = ref([])

  // 聊天功能
  const sendMessage = async (content, params = {}) => {
    messages.value.push({ role: 'user', content, timestamp: new Date() })
    // 所有聊天都生成图片
    await handleImageGeneration({ prompt: content, ...params })
  }

  // 处理图片生成
  const handleImageGeneration = async (params) => {
    if (params.image && params.image.length === 0) delete params.image
    try {
      // 调用图片生成API
      const result = await generateImage({
        // model: 'doubao-seedream-4.0',
        sequential_image_generation: 'auto',
        watermark: true,
        ...params,
      })
      if (result && result.urls && result.urls.length > 0) {
        // 添加AI回复
        messages.value.push({
          role: 'assistant',
          content: `我已经为您生成了图片！共生成 ${result.urls.length} 张图片。`,
          images: result.urls.map((url) => ({ url })),
          timestamp: new Date(),
        })
      } else {
        throw new Error('图片生成失败，请重试')
      }
    } catch (err) {
      messages.value.push({
        role: 'assistant',
        content: `抱歉，图片生成失败了：${err.message}。请检查您的描述或稍后重试。`,
        timestamp: new Date(),
      })
    }
  }

  return { messages, isLoading, error, sendMessage, generateImage: handleImageGeneration, cancel }
}
