<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { BubbleList } from 'vue-element-plus-x'
import { BubbleProps } from 'vue-element-plus-x/./types/Bubble'
import { streamApi } from '@/api/agent'

// 消息类型定义
interface ChatMessage {
  key: number // 唯一标识
  role: 'user' | 'ai' // 消息角色
  isMarkdown?: boolean // 是否为Markdown格式
  content: string // 消息内容
  loading?: boolean // 加载状态
  typing?: boolean // 打字效果
}

// 组件props
interface Props {
  modelValue?: boolean // 控制抽屉显示
  title?: string // 抽屉标题
  width?: string // 抽屉宽度
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: 'AI助手',
  width: '400px'
})

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'send': [message: string]
}>()

// 消息列表
const messages = ref<ChatMessage[]>([]);
(window as any).agentMessages = messages.value;
// 输入内容
const inputText = ref('')
// 消息计数器
const messageCounter = ref(0)
// 是否正在生成AI回复
const isGenerating = ref(false)
// 用于取消请求的AbortController
const abortController = ref<AbortController | null>(null)
// BubbleList引用
const bubbleListRef = ref()

// 计算属性：转换为BubbleList需要的格式
const bubbleListData = computed<BubbleProps[]>(() => {
  return messages.value.map(msg => ({
    ...msg,
    placement: msg.role === 'ai' ? 'start' : 'end', // AI在左边，用户在右边
    loading: msg.loading || false,
    shape: 'corner' as const,
    variant: msg.role === 'ai' ? 'filled' as const : 'outlined' as const,
    isMarkdown: msg.isMarkdown || false,
    typing: msg.typing || false,
    isFog: msg.role === 'ai' && msg.typing, // AI消息开启打字雾化效果
    avatar: msg.role === 'ai'
      ? 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
      : 'https://avatars.githubusercontent.com/u/76239030?v=4',
    avatarSize: '24px',
    avatarGap: '12px'
  }))
})

// 监听消息变化，滚动到底部
watch(messages, () => {
  nextTick(() => {
    if (bubbleListRef.value) {
      // BubbleList可能有自己的滚动方法，这里先简单处理
      const container = bubbleListRef.value.$el?.querySelector?.('.bubble-list-container')
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    }
  })
}, { deep: true })

// 添加用户消息
const addUserMessage = (content: string) => {
  if (!content.trim()) return

  messageCounter.value++
  const userMessage: ChatMessage = {
    key: messageCounter.value,
    role: 'user',
    content: content.trim(),
    loading: false,
    typing: false
  }

  messages.value.push(userMessage)
  inputText.value = ''

  // 生成AI回复（真实API调用）
  generateAIResponse(content.trim())
}

// 生成AI回复（真实API调用）
const generateAIResponse = (userMessage: string) => {
  // 取消之前的请求（如果存在）
  if (abortController.value) {
    abortController.value.abort()
    abortController.value = null
  }

  isGenerating.value = true

  // 创建新的AbortController
  const controller = new AbortController()
  abortController.value = controller

  messageCounter.value++
  const aiMessage: ChatMessage = {
    key: messageCounter.value,
    role: 'ai',
    content: '',
    isMarkdown: true,
    loading: true,
    typing: false
  }

  messages.value.push(aiMessage)
  const aiMessageIndex = messages.value.length - 1

  // 调用流式API，使用回调方式
  streamApi(
    userMessage,
    {
      onopen(response) {
        // 连接成功，设置加载完成，开始流式接收
        messages.value[aiMessageIndex].loading = false
        messages.value[aiMessageIndex].typing = true
      },
      onmessage(data) {
        // data 是服务器发送的原始字符串，如 '{"text":"..."}'
        try {
          if (data === '[DONE]') return;

          // 解析 JSON 数据
          const parsed = JSON.parse(data);
          if (parsed.text) {
            // 更新AI消息内容（追加方式）
            messages.value[aiMessageIndex].content += parsed.text
          }
        } catch (e) {
          console.warn('解析JSON失败:', data, e)
        }
      },
      onclose() {
        // 流式接收完成，关闭打字效果
        messages.value[aiMessageIndex].typing = false
        isGenerating.value = false
        abortController.value = null
      },
      onerror(error) {
        // 显示错误信息
        console.error('AI回复生成失败:', error)
        messages.value[aiMessageIndex].content = `抱歉，生成回复时出现错误: ${error.message}`
        messages.value[aiMessageIndex].loading = false
        messages.value[aiMessageIndex].typing = false

        isGenerating.value = false
        abortController.value = null
      }
    },
    { signal: controller.signal }
  )
}

// 取消AI回复生成
const cancelAIResponse = () => {
  if (abortController.value) {
    abortController.value.abort()
    abortController.value = null
  }
  isGenerating.value = false

  // 如果正在生成AI消息，将其标记为取消状态
  const lastMessageIndex = messages.value.length - 1
  if (lastMessageIndex >= 0 && messages.value[lastMessageIndex].role === 'ai' &&
      (messages.value[lastMessageIndex].loading || messages.value[lastMessageIndex].typing)) {
    messages.value[lastMessageIndex].loading = false
    messages.value[lastMessageIndex].typing = false
    if (!messages.value[lastMessageIndex].content) {
      messages.value[lastMessageIndex].content = '请求已取消'
    }
  }
}

// 发送消息
const sendMessage = () => {
  if (inputText.value.trim() && !isGenerating.value) {
    emit('send', inputText.value.trim())
    addUserMessage(inputText.value)
  }
}

// 清空对话
const clearMessages = () => {
  // 取消正在进行的请求
  cancelAIResponse()
  messages.value = []
  messageCounter.value = 0
}

// 关闭抽屉
const closeDrawer = () => {
  emit('update:modelValue', false)
}

// 监听外部modelValue变化
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    // 抽屉打开时的初始化逻辑
    nextTick(() => {
      // 确保BubbleList正确渲染
    })
  }
})

// 暴露方法给父组件
defineExpose({
  clearMessages,
  addUserMessage: (content: string) => {
    addUserMessage(content)
  },
  cancelAIResponse,
  isGenerating
})
</script>

<template>
  <el-drawer
    v-model="props.modelValue"
    :title="props.title"
    :size="props.width"
    direction="rtl"
    :close-on-click-modal="false"
    @close="closeDrawer"
  >
    <div class="ai-chat-drawer">
      <!-- 消息列表区域 -->
      <div class="message-area">
        <BubbleList
          ref="bubbleListRef"
          :list="bubbleListData"
          max-height="100%"
        />
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <el-input
          v-model="inputText"
          type="textarea"
          :rows="3"
          placeholder="请输入您的问题..."
          :disabled="isGenerating"
          @keydown.enter.prevent="sendMessage"
        />
        <div class="input-actions">
          <el-button
            type="primary"
            :loading="isGenerating"
            :disabled="!inputText.trim() || isGenerating"
            @click="sendMessage"
          >
            发送
          </el-button>
          <el-button
            @click="clearMessages"
            :disabled="messages.length === 0 || isGenerating"
          >
            清空
          </el-button>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<style scoped lang="scss">
.ai-chat-drawer {
  display: flex;
  flex-direction: column;
  height: 100%;

  .message-area {
    flex: 1;
    overflow: hidden;
    margin-bottom: 16px;

    :deep(.bubble-list-container) {
      height: 100%;
    }
  }

  .input-area {
    border-top: 1px solid var(--el-border-color-light);
    padding-top: 16px;

    .input-actions {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
      margin-top: 12px;
    }
  }
}
</style>