<template>
    <div class="ai-chat-container">
        <!-- 折叠状态的历史栏 -->
        <div v-if="!isHistoryOpen" class="history-collapsed">
            <button class="history-toggle-btn" @click="toggleHistory" title="展开历史对话">
                <Clock :size="20" />
            </button>
            <div class="history-icons">
                <button
                    v-for="conv in chatHistory.slice(0, 8)"
                    :key="conv.chatId"
                    @click="loadChat(conv.chatId!); toggleHistory()"
                    class="history-icon-btn"
                    :class="{ active: currentChatId === conv.chatId }"
                    :title="conv.title"
                >
                    <MessageCircle :size="16" />
                </button>
            </div>
            <button class="expand-btn" @click="toggleHistory" title="展开历史对话">
                <ChevronRight :size="18" />
            </button>
        </div>

        <!-- 展开时的关闭按钮 -->
        <button
            v-if="isHistoryOpen"
            class="history-close-btn"
            @click="toggleHistory"
        >
            <ChevronLeft :size="18" />
        </button>

        <!-- 历史对话侧边栏 -->
        <aside 
            class="history-sidebar"
            :class="{ open: isHistoryOpen }"
        >
            <div class="sidebar-inner">
                <!-- 头部 -->
                <div class="sidebar-header">
                    <span class="title">历史对话</span>
                    <button class="new-chat-btn" @click="startNewChat" title="新建对话">
                        <Plus :size="18" />
                    </button>
                </div>

                <!-- 对话列表 -->
                <div class="conversation-list">
                    <div v-if="chatHistory.length === 0" class="empty-tip">
                        暂无历史对话
                    </div>
                    <div
                        v-for="conv in chatHistory"
                        :key="conv.chatId"
                        @click="loadChat(conv.chatId!)"
                        class="conversation-item"
                        :class="{ active: currentChatId === conv.chatId }"
                    >
                        <MessageCircle :size="16" class="conv-icon" />
                        <div class="conv-info">
                            <div class="conv-title">{{ getPlainTextPreview(conv.title || '新对话') }}</div>
                            <div class="conv-time">{{ formatTime(conv.createTime) }}</div>
                        </div>
                        <button
                            class="delete-btn"
                            @click.stop="deleteConversation(conv.chatId!)"
                            title="删除"
                        >
                            <Trash2 :size="14" />
                        </button>
                    </div>
                </div>
            </div>
        </aside>

        <!-- 主聊天区域 -->
        <main class="chat-main" :class="{ 'sidebar-open': isHistoryOpen }">
            <!-- 消息区域 -->
            <div ref="messagesRef" class="messages-container">
                <!-- 空状态 -->
                <div v-if="messages.length === 0" class="empty-state">
                    <div class="empty-content">
                        <!-- Logo -->
                        <div class="logo-wrapper">
                            <Headphones :size="40" class="logo-icon" />
                        </div>
                        <h1 class="title">泰豪小电</h1>
                        <p class="desc">电源设备智能客服助手，为您提供设备操作、故障排查、维修服务等专业支持</p>

                        <!-- 快捷命令 -->
                        <div class="quick-grid">
                            <button
                                v-for="cmd in quickCommands"
                                :key="cmd.label"
                                @click="handleQuickCommand(cmd.query)"
                                class="quick-card"
                            >
                                <div class="quick-icon">
                                    <component :is="cmd.icon" :size="18" />
                                </div>
                                <span class="quick-label">{{ cmd.label }}</span>
                            </button>
                        </div>
                    </div>
                </div>
                <!-- 消息列表 -->
                <div v-else class="messages-list">
                    <!-- 对话标题 -->
                    <div v-if="currentChatTitle" class="chat-header">
                        <h2 class="chat-title">{{ currentChatTitle }}</h2>
                    </div>
                    <div
                        v-for="msg in messages"
                        :key="msg.id"
                        class="message-row"
                        :class="msg.role"
                    >
                        <!-- 头像 -->
                        <div class="avatar" :class="msg.role">
                            <User v-if="msg.role === 'user'" :size="16" />
                            <Headphones v-else :size="16" />
                        </div>

                        <!-- 消息内容区域 -->
                        <div class="message-content" :class="msg.role">
                            <!-- 文字气泡 -->
                            <div v-if="msg.text || (isStreaming && msg.role === 'assistant' && messages.indexOf(msg) === messages.length - 1)" class="message-bubble" :class="msg.role">
                                <div
                                    v-if="msg.text"
                                    class="message-text"
                                    v-html="msg.role === 'assistant' ? renderMarkdown(msg.text) : msg.text"
                                >
                                </div>
                                <span v-if="isStreaming && msg.role === 'assistant' && messages.indexOf(msg) === messages.length - 1" class="typing-cursor">|</span>
                                <div v-if="!msg.text && isStreaming && msg.role === 'assistant'" class="loading-dots">
                                    <span></span><span></span><span></span>
                                </div>
                            </div>
                            <!-- 消息携带的文件（在气泡外面） -->
                            <div v-if="msg.files && msg.files.length > 0" class="message-files">
                                <a
                                    v-for="fileId in msg.files"
                                    :key="fileId"
                                    :href="getFileDownloadUrl(fileId)"
                                    target="_blank"
                                    class="message-file-item"
                                >
                                    <div v-if="isImageFileById(fileId)" class="file-preview image">
                                        <img :src="getFileDownloadUrl(fileId)" :alt="getFileName(fileId)" />
                                    </div>
                                    <div v-else class="file-preview document">
                                        <FileIcon :size="18" />
                                    </div>
                                    <span class="file-name">{{ getFileName(fileId) }}</span>
                                </a>
                            </div>
                            <div class="message-time">{{ msg.time }}</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 快捷命令栏（有消息时显示） -->
            <div v-if="messages.length > 0" class="quick-bar">
                <div class="quick-bar-inner">
                    <button
                        v-for="cmd in quickCommands"
                        :key="cmd.label"
                        @click="handleQuickCommand(cmd.query)"
                        class="quick-pill"
                    >
                        <component :is="cmd.icon" :size="18" />
                        <span>{{ cmd.label }}</span>
                    </button>
                </div>
            </div>

            <!-- 输入区域 -->
            <div class="input-area">
                <div class="input-wrapper">
                    <!-- 输入卡片 -->
                    <div class="input-card">
                        <!-- 已上传文件预览 -->
                        <div v-if="uploadedFiles.length > 0" class="uploaded-files">
                            <div
                                v-for="(file, index) in uploadedFiles"
                                :key="file.id || index"
                                class="uploaded-file-item"
                            >
                                <div v-if="isImageFile(file)" class="file-preview image">
                                    <img :src="getFilePreviewUrl(file)" :alt="file.name" />
                                </div>
                                <div v-else class="file-preview document">
                                    <FileIcon :size="20" />
                                </div>
                                <span class="file-name">{{ file.name }}</span>
                                <button class="remove-file-btn" @click="removeUploadedFile(index)">
                                    <X :size="14" />
                                </button>
                            </div>
                        </div>
                        <!-- 输入框行（包含输入框和按钮） -->
                        <div class="input-row">
                            <!-- 隐藏的文件输入 -->
                            <input
                                ref="fileInputRef"
                                type="file"
                                multiple
                                accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.txt"
                                style="display: none"
                                @change="handleFileSelect"
                            />
                            <button 
                                class="tool-btn" 
                                :class="{ uploading: isUploading }"
                                :disabled="isUploading"
                                @click="triggerFileUpload"
                                title="添加附件"
                            >
                                <Loader2 v-if="isUploading" :size="18" class="spin" />
                                <Paperclip v-else :size="18" />
                            </button>
                            <textarea
                                ref="textareaRef"
                                v-model="inputText"
                                @input="adjustHeight"
                                @keydown="handleKeyDown"
                                placeholder="请输入您的问题，例如：电源模块过热报警怎么处理..."
                                :rows="1"
                                class="chat-textarea"
                            />
                            <button
                                class="send-btn"
                                :class="{ active: inputText.trim() || uploadedFiles.length > 0 }"
                                :disabled="(!inputText.trim() && uploadedFiles.length === 0) || isStreaming"
                                @click="sendMessage"
                            >
                                <Send :size="18" />
                            </button>
                        </div>
                    </div>
                    <p class="disclaimer">AI 生成内容仅供参考 · 泰豪集团内部绝密信息请勿上传</p>
                </div>
            </div>
        </main>
    </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted, computed } from 'vue'
import { 
    Plus, 
    MessageCircle,
    Clock,
    Trash2,
    ChevronLeft,
    ChevronRight,
    FileText, 
    AlertTriangle, 
    Wrench, 
    Search, 
    Paperclip, 
    Send,
    User,
    Headphones,
    X,
    Image,
    File as FileIcon,
    Loader2
} from 'lucide-vue-next'
import { aiChatAPI, agentAPI } from 'shared/api/ai'
import { fileAPI } from 'shared/api/file'
import type { 
    TbChat, 
    TbChatMessage, 
    TbAgent, 
    ChatPrepareData,
    SSEMessageData,
    DifyFileInfo,
    TbSysFileDTO
} from 'shared/types'
import { AGENT_ID, FILE_DOWNLOAD_URL } from '@/config'

// 用户信息（TODO: 从实际用户store获取）
const userId = computed(()=>{
    return JSON.parse(localStorage.getItem("loginDomain")||'{}').user.userId;
})
const userType = ref<boolean>(true) // 系统内部人员

// 智能体信息
const currentAgent = ref<TbAgent | null>(null)
const agentId = AGENT_ID

// 历史对话展开状态
const isHistoryOpen = ref(false)

// 当前选中的对话ID
const currentChatId = ref<string | null>(null)

// 历史对话列表
const chatHistory = ref<TbChat[]>([])
const currentChatTitle = ref<string>('')

// 聊天消息列表
const messages = ref<TbChatMessage[]>([])

// 流式对话状态
const isStreaming = ref(false)
const currentTaskId = ref<string>('')
const eventSource = ref<EventSource | null>(null)

// 输入框文本
const inputText = ref('')

// 上传的文件列表
const uploadedFiles = ref<DifyFileInfo[]>([])
const isUploading = ref(false)
const fileInputRef = ref<HTMLInputElement | null>(null)

// 文件信息缓存 (fileId -> TbSysFileDTO)
const fileInfoCache = ref<Map<string, TbSysFileDTO>>(new Map())

// 消息容器引用
const messagesRef = ref<HTMLElement | null>(null)
const textareaRef = ref<HTMLTextAreaElement | null>(null)

// 快捷命令
const quickCommands = [
    { label: '设备操作手册', icon: FileText, query: '请帮我查询设备操作手册的相关内容' },
    { label: '故障排查指南', icon: AlertTriangle, query: '请提供故障排查指南' },
    { label: '维修服务规范', icon: Wrench, query: '请查询维修服务规范' },
    { label: '技术参数查询', icon: Search, query: '请帮我查询设备技术参数' }
]

// 切换历史对话侧边栏
const toggleHistory = () => {
    isHistoryOpen.value = !isHistoryOpen.value
}

// 开始新对话
const startNewChat = async () => {
    currentChatId.value = null
    currentChatTitle.value = ''
    messages.value = []
    inputText.value = ''
    uploadedFiles.value = []
    
    // 创建新会话
    if (agentId && userId.value) {
        try {
            const result = await aiChatAPI.createChat({
                agentId: agentId,
                userId: userId.value,
                userType: userType.value
            })
            if (result.success && result.data) {
                currentChatId.value = result.data.chatId || null
            }
        } catch (error) {
            console.error('创建会话失败:', error)
        }
    }
}

// 加载历史对话
const loadChat = async (chatId: string) => {
    currentChatId.value = chatId
    messages.value = []
    
    // 设置当前对话标题
    const chat = chatHistory.value.find((c: TbChat) => c.chatId === chatId)
    currentChatTitle.value = chat?.title || '新对话'
    
    try {
        const result = await aiChatAPI.getMessageList({ chatId })
        if (result.success && result.dataList) {
            const messageList = Array.isArray(result.dataList) ? result.dataList : [result.dataList]
            messages.value = messageList.map((msg: TbChatMessage) => ({
                ...msg,
                id: msg.messageId || String(Date.now()),
                text: msg.content || '',
                time: formatTime(msg.createTime)
            } as TbChatMessage))
            
            // 加载消息中的文件信息
            await loadMessagesFilesInfo(messageList)
        }
    } catch (error) {
        console.error('加载对话消息失败:', error)
    }
    
    scrollToBottom()
}

// 删除对话
const deleteConversation = async (chatId: string) => {
    try {
        const result = await aiChatAPI.deleteChat({ chatId })
        if (result.success) {
            chatHistory.value = chatHistory.value.filter((c: TbChat) => c.chatId !== chatId)
            if (currentChatId.value === chatId) {
                startNewChat()
            }
        }
    } catch (error) {
        console.error('删除对话失败:', error)
    }
}

// 滚动到底部
const scrollToBottom = () => {
    nextTick(() => {
        if (messagesRef.value) {
            messagesRef.value.scrollTop = messagesRef.value.scrollHeight
        }
    })
}

// 发送消息
const sendMessage = async () => {
    // 允许只有文件或只有文本
    if ((!inputText.value.trim() && uploadedFiles.value.length === 0) || isStreaming.value) return
    if (!agentId) {
        console.error('未选择智能体')
        return
    }
    
    const query = inputText.value.trim() || '[文件]'
    const currentFiles = [...uploadedFiles.value] // 保存当前文件列表副本
    const userMessage: TbChatMessage = {
        id: String(Date.now()),
        role: 'user',
        text: inputText.value.trim(),
        time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
        files: currentFiles.length > 0 ? currentFiles.map(item => item.sys_file_id): undefined
    }
    
    // 将上传文件的信息缓存起来，用于立即渲染
    currentFiles.forEach(f => {
        if (f.sys_file_id) {
            fileInfoCache.value.set(f.sys_file_id, {
                fileId: f.sys_file_id,
                name: f.name,
                url: f.preview_url || f.source_url,
                extension: f.extension,
                mimeType: f.mime_type
            } as TbSysFileDTO)
        }
    })
    
    messages.value.push(userMessage)
    inputText.value = ''
    
    // 重置输入框高度
    if (textareaRef.value) {
        textareaRef.value.style.height = 'auto'
    }
    
    scrollToBottom()
    
    // 如果没有当前会话，先创建
    if (!currentChatId.value) {
        try {
            const createResult = await aiChatAPI.createChat({
                agentId: agentId,
                userId: userId.value,
                userType: userType.value,
                title: query.slice(0, 20) + (query.length > 20 ? '...' : '')
            })
            if (createResult.success && createResult.data) {
                currentChatId.value = createResult.data.chatId || null
                chatHistory.value.unshift(createResult.data)
            }
        } catch (error) {
            console.error('创建会话失败:', error)
            return
        }
    }
    
    // 准备流式对话参数
    const prepareParam: ChatPrepareData = {
        chatId: currentChatId.value!,
        query: query,
        agentId: agentId,
        userType: userType.value,
        userId: userId.value,
        files: uploadedFiles.value.length > 0 ? uploadedFiles.value : undefined,
        service: "workcase"
    }
    
    // 清空已上传的文件
    uploadedFiles.value = []
    
    try {
        // 准备流式对话
        const prepareResult = await aiChatAPI.prepareStreamChat(prepareParam)
        if (!prepareResult.success || !prepareResult.data) {
            throw new Error('准备流式对话失败')
        }
        
        const sessionId = prepareResult.data
        
        // 创建AI回复消息占位
        const assistantMessage: TbChatMessage = {
            id: String(Date.now() + 1),
            role: 'assistant',
            text: '',
            time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
        }
        messages.value.push(assistantMessage)
        
        // 开始流式对话
        isStreaming.value = true
        eventSource.value = aiChatAPI.createStreamChat(sessionId)
        
        const es = eventSource.value
        if (!es) return
        
        es.onmessage = (event) => {
            try {
                console.log('SSE原始数据:', event.data)
                const data = JSON.parse(event.data)
                console.log('SSE解析数据:', data)
                
                if (data.task_id) {
                    currentTaskId.value = data.task_id
                }
                
                // 支持多种事件格式
                if (data.event === 'message' && data.answer) {
                    // 更新最后一条消息
                    const lastMsg = messages.value[messages.value.length - 1]
                    if (lastMsg && lastMsg.role === 'assistant') {
                        lastMsg.text += data.answer
                    }
                    scrollToBottom()
                } else if (data.event === 'message_end' || data.event === 'workflow_finished') {
                    closeEventSource()
                } else if (data.event === 'error') {
                    console.error('SSE错误:', data.message)
                    closeEventSource()
                }
            } catch (e) {
                console.error('解析SSE数据失败:', e, event.data)
            }
        }
        
        es.onerror = () => {
            closeEventSource()
        }
        
    } catch (error) {
        console.error('发送消息失败:', error)
        isStreaming.value = false
    }
}

// 关闭EventSource
const closeEventSource = () => {
    if (eventSource.value) {
        eventSource.value.close()
        eventSource.value = null
    }
    isStreaming.value = false
    currentTaskId.value = ''
}

// 停止对话
const stopChat = async () => {
    if (currentTaskId.value && agentId && userId.value) {
        try {
            await aiChatAPI.stopChat({
                taskId: currentTaskId.value,
                agentId: agentId,
                userId: userId.value
            })
        } catch (error) {
            console.error('停止对话失败:', error)
        }
    }
    closeEventSource()
}

// 加载对话列表
const loadChatHistory = async () => {
    if (!userId.value) return
    
    try {
        const result = await aiChatAPI.getChatList({
            agentId: agentId
        })
        if (result.success && result.dataList) {
            chatHistory.value = result.dataList
        }
    } catch (error) {
        console.error('加载对话列表失败:', error)
    }
}

// 格式化时间
const formatTime = (time?: string | number): string => {
    if (!time) return ''
    const date = new Date(time)
    const now = new Date()
    const isToday = date.toDateString() === now.toDateString()

    if (isToday) {
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    }
    return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
}

// 去除markdown语法并截取前10个字符（用于历史对话列表预览）
const getPlainTextPreview = (text: string): string => {
    if (!text) return ''

    // 去除markdown语法
    let plainText = text
        // 去除代码块
        .replace(/```[\s\S]*?```/g, '[代码]')
        // 去除行内代码
        .replace(/`([^`]+)`/g, '$1')
        // 去除粗体
        .replace(/\*\*([^\*]+)\*\*/g, '$1')
        // 去除斜体
        .replace(/\*([^\*]+)\*/g, '$1')
        // 去除链接
        .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
        // 去除标题标记
        .replace(/^#{1,6}\s+/gm, '')
        // 去除列表标记
        .replace(/^[*-]\s+/gm, '')
        // 去除多余的空白字符
        .replace(/\s+/g, ' ')
        .trim()

    // 截取前10个字符
    if (plainText.length > 10) {
        return plainText.substring(0, 10) + '...'
    }

    return plainText
}

// Markdown渲染函数
const renderMarkdown = (text: string): string => {
    if (!text) return ''

    // 转义HTML标签
    let html = text
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')

    // 处理代码块（```语法）
    html = html.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, lang, code) => {
        return `<pre class="code-block"><code class="language-${lang || 'text'}">${code.trim()}</code></pre>`
    })

    // 处理行内代码（`语法）
    html = html.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>')

    // 处理粗体（**语法）
    html = html.replace(/\*\*([^\*]+)\*\*/g, '<strong>$1</strong>')

    // 处理斜体（*语法）
    html = html.replace(/\*([^\*]+)\*/g, '<em>$1</em>')

    // 处理链接（[text](url)语法）
    html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" class="md-link">$1</a>')

    // 处理标题（# ## ###等）
    html = html.replace(/^### (.+)$/gm, '<h3 class="md-h3">$1</h3>')
    html = html.replace(/^## (.+)$/gm, '<h2 class="md-h2">$1</h2>')
    html = html.replace(/^# (.+)$/gm, '<h1 class="md-h1">$1</h1>')

    // 处理无序列表（- 或 * 开头）
    html = html.replace(/^[*-] (.+)$/gm, '<li class="md-li">$1</li>')
    html = html.replace(/(<li class="md-li">.*<\/li>)/s, '<ul class="md-ul">$1</ul>')

    // 处理有序列表（数字. 开头）
    html = html.replace(/^\d+\. (.+)$/gm, '<li class="md-li">$1</li>')

    // 处理换行
    html = html.replace(/\n/g, '<br>')

    return html
}

// 处理快捷命令
const handleQuickCommand = (query: string) => {
    inputText.value = query
    sendMessage()
}

// 自动调整输入框高度
const adjustHeight = () => {
    const el = textareaRef.value
    if (el) {
        el.style.height = 'auto'
        el.style.height = Math.min(el.scrollHeight, 150) + 'px'
    }
}

// 键盘事件
const handleKeyDown = (e: KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault()
        sendMessage()
    }
}

// 触发文件选择
const triggerFileUpload = () => {
    fileInputRef.value?.click()
}

// 处理文件选择
const handleFileSelect = async (e: Event) => {
    const target = e.target as HTMLInputElement
    const files = target.files
    if (!files || files.length === 0) return
    
    for (const file of Array.from(files)) {
        await uploadFile(file)
    }
    
    // 清空input，允许重复选择同一文件
    target.value = ''
}

// 上传单个文件
const uploadFile = async (file: File) => {
    if (!agentId) {
        console.error('未选择智能体')
        return
    }
    
    // 文件大小限制 10MB
    const maxSize = 10 * 1024 * 1024
    if (file.size > maxSize) {
        console.error('文件大小超过10MB限制')
        return
    }
    
    isUploading.value = true
    
    try {
        const result = await aiChatAPI.uploadFileForChat(file, agentId)
        if (result.success && result.data) {
            uploadedFiles.value.push(result.data)
        } else {
            console.error('文件上传失败:', result.message)
        }
    } catch (error) {
        console.error('文件上传失败:', error)
    } finally {
        isUploading.value = false
    }
}

// 移除已上传的文件
const removeUploadedFile = (index: number) => {
    uploadedFiles.value.splice(index, 1)
}

// 判断是否为图片文件
const isImageFile = (file: DifyFileInfo): boolean => {
    return file.type === 'image' || file.mime_type?.startsWith('image/') || false
}

// 获取文件预览URL
const getFilePreviewUrl = (file: DifyFileInfo): string => {
    return file.preview_url || file.source_url || file.url || ''
}

// 加载消息中的文件信息
const loadMessagesFilesInfo = async (messageList: TbChatMessage[]) => {
    // 收集所有文件ID
    const fileIds: string[] = []
    messageList.forEach(msg => {
        if (msg.files) {
            const filesArray = Array.isArray(msg.files) ? msg.files : [msg.files]
            filesArray.forEach(id => {
                if (id && !fileInfoCache.value.has(id)) {
                    fileIds.push(id)
                }
            })
        }
    })
    
    if (fileIds.length === 0) return
    
    // 逐个查询文件信息
    for (const fileId of fileIds) {
        try {
            const res = await fileAPI.getFileById(fileId)
            if (res.success && res.data) {
                fileInfoCache.value.set(fileId, res.data)
            }
        } catch (error) {
            console.error(`加载文件信息失败: ${fileId}`, error)
        }
    }
}

// 获取缓存的文件信息
const getFileInfo = (fileId: string): TbSysFileDTO | undefined => {
    return fileInfoCache.value.get(fileId)
}

// 获取文件名（从缓存）
const getFileName = (fileId: string): string => {
    const fileInfo = fileInfoCache.value.get(fileId)
    return fileInfo?.name || fileId.substring(0, 8) + '...'
}

// 获取文件下载URL
const getFileDownloadUrl = (fileId: string): string => {
    if (!fileId) return ''
    const fileInfo = fileInfoCache.value.get(fileId)
    if (fileInfo?.url) return fileInfo.url
    return `${FILE_DOWNLOAD_URL}${fileId}`
}

// 判断文件ID对应的文件是否为图片
const isImageFileById = (fileId: string): boolean => {
    const fileInfo = fileInfoCache.value.get(fileId)
    if (!fileInfo) return false
    const ext = (fileInfo.extension || fileInfo.name?.split('.').pop() || '').toLowerCase()
    return ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(ext)
}

// 组件挂载
onMounted(async () => {
    // TODO: 根据路由参数或配置获取智能体ID
    // 示例：从路由获取 agentId
    // const route = useRoute()
    // if (route.query.agentId) {
    //     await loadAgent(route.query.agentId as string)
    // }
    
    // 加载对话历史
    await loadChatHistory()
})
</script>

<style scoped lang="scss">
@import url("./AIChatView.scss");
</style>
