<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.id"
                    @click="loadChat(conv.id); toggleHistory()"
                    class="history-icon-btn"
                    :class="{ active: currentChatId === conv.id }"
                    :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.id"
                        @click="loadChat(conv.id)"
                        class="conversation-item"
                        :class="{ active: currentChatId === conv.id }"
                    >
                        <MessageCircle :size="16" class="conv-icon" />
                        <div class="conv-info">
                            <div class="conv-title">{{ conv.title }}</div>
                            <div class="conv-time">{{ conv.time }}</div>
                        </div>
                        <button
                            class="delete-btn"
                            @click.stop="deleteConversation(conv.id)"
                            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-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-bubble" :class="msg.role">
                            <p class="message-text">{{ msg.text }}</p>
                            <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 class="input-row">
                            <textarea
                                ref="textareaRef"
                                v-model="inputText"
                                @input="adjustHeight"
                                @keydown="handleKeyDown"
                                placeholder="请输入您的问题，例如：电源模块过热报警怎么处理..."
                                :rows="1"
                                class="chat-textarea"
                            />
                        </div>
                        <!-- 工具栏 -->
                        <div class="toolbar-row">
                            <div class="toolbar-actions">
                                <button class="tool-btn" title="添加附件">
                                    <Paperclip :size="18" />
                                </button>
                                <button
                                    class="send-btn"
                                    :class="{ active: inputText.trim() }"
                                    :disabled="!inputText.trim()"
                                    @click="sendMessage"
                                >
                                    <Send :size="18" />
                                </button>
                            </div>
                        </div>
                    </div>
                    <p class="disclaimer">AI 生成内容仅供参考 · 泰豪集团内部绝密信息请勿上传</p>
                </div>
            </div>
        </main>
    </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { 
    Plus, 
    MessageCircle,
    Clock,
    Trash2,
    ChevronLeft,
    ChevronRight,
    FileText, 
    AlertTriangle, 
    Wrench, 
    Search, 
    Paperclip, 
    Send,
    User,
    Headphones
} from 'lucide-vue-next'

interface Message {
    id: number
    role: 'user' | 'assistant'
    text: string
    time: string
}

interface Conversation {
    id: number
    title: string
    time: string
}

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

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

// 历史对话列表
const chatHistory = ref<Conversation[]>([
    { id: 1, title: '发电机故障咨询', time: '今天 10:30' },
    { id: 2, title: '设备维保规范查询', time: '今天 09:15' },
    { id: 3, title: '配件更换流程', time: '昨天 16:42' },
    { id: 4, title: 'TH-500GF参数查询', time: '昨天 14:20' },
    { id: 5, title: '巡检报告模板', time: '12月10日' },
    { id: 6, title: '客户投诉处理流程', time: '12月09日' }
])

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

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

// 消息容器引用
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 = () => {
    currentChatId.value = null
    messages.value = []
    inputText.value = ''
}

// 加载历史对话
const loadChat = (chatId: number) => {
    currentChatId.value = chatId
    // 模拟加载历史对话
    messages.value = [
        { 
            id: 1, 
            role: 'assistant', 
            text: '您好，欢迎使用泰豪智能客服，请问有什么可以帮您的？', 
            time: '10:00' 
        }
    ]
}

// 删除对话
const deleteConversation = (convId: number) => {
    chatHistory.value = chatHistory.value.filter(c => c.id !== convId)
    if (currentChatId.value === convId) {
        startNewChat()
    }
}

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

// 发送消息
const sendMessage = async () => {
    if (!inputText.value.trim()) return
    
    const userMessage: Message = {
        id: Date.now(),
        role: 'user',
        text: inputText.value.trim(),
        time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    }
    
    messages.value.push(userMessage)
    const query = inputText.value
    inputText.value = ''
    
    // 重置输入框高度
    if (textareaRef.value) {
        textareaRef.value.style.height = 'auto'
    }
    
    scrollToBottom()
    
    // 模拟 AI 回复
    setTimeout(() => {
        const assistantMessage: Message = {
            id: Date.now() + 1,
            role: 'assistant',
            text: `感谢您的咨询！关于"${query}"，我正在为您查询相关信息...\n\n这是一个模拟回复。在实际应用中，这里会连接到后端AI服务获取真实回答。`,
            time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
        }
        messages.value.push(assistantMessage)
        
        // 保存到对话列表
        if (!currentChatId.value) {
            const newConv: Conversation = {
                id: Date.now(),
                title: query.slice(0, 20) + (query.length > 20 ? '...' : ''),
                time: '刚刚'
            }
            chatHistory.value.unshift(newConv)
            currentChatId.value = newConv.id
        }
        
        scrollToBottom()
    }, 1000)
}

// 处理快捷命令
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()
    }
}
</script>

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