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() })
    if (!params.size) {
      if (content.includes('1:1') || content.includes('正方形')) params.size = '2048x2048'
      if (content.includes('4:3') || content.includes('横屏')) params.size = '2304x1728'
      if (content.includes('3:4') || content.includes('竖屏')) params.size = '1728x2304'
      if (content.includes('16:9')) params.size = '2560x1440'
      if (content.includes('9:16')) params.size = '1440x2560'
      if (content.includes('3:2')) params.size = '2496x1664'
      if (content.includes('2:3')) params.size = '1664x2496'
    }
    // 所有聊天都生成图片
    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 }
}
