/**
 * AI聊天页面Vue应用
 */
require(['jquery', 'vue', 'utils', 'echarts', 'global'], function ($, Vue, utils, echarts) {
    const app = new Vue({
        el: '#app',
        data: {
            // 用户相关数据
            currentLoginUser: {},
            
            // 聊天相关数据
            chatHistory: [],
            sessionId: "",
            currentEventSource: null,
            
            // UI相关数据
            theme: localStorage.getItem('ai-chat-theme') || 'light',
            isResponding: false,
            userInput: "",
            
            // 历史对话分类
            historySections: [
                {
                    label: '今天',
                    items: [
                        { id: 'chat1', title: '如何学习人工智能', time: '10:30', active: true, showMenu: false },
                        { id: 'chat2', title: '机器学习与深度学习的区别机器学习与深度学习的区别', time: '09:15', active: false, showMenu: false }
                    ]
                },
                {
                    label: '昨天',
                    items: [
                        { id: 'chat3', title: 'Python编程基础', time: '16:45', active: false, showMenu: false }
                    ]
                },
                {
                    label: '7天内',
                    items: [
                        { id: 'chat4', title: '数据结构与算法', time: '周一', active: false, showMenu: false }
                    ]
                },
                {
                    label: '30天内',
                    items: [
                        { id: 'chat5', title: '网络安全入门', time: '6月10日', active: false, showMenu: false }
                    ]
                },
                {
                    label: '2023年5月',
                    items: [
                        { id: 'chat6', title: '区块链技术解析', time: '5月20日', active: false, showMenu: false }
                    ]
                },
            ],
            
            // 消息列表
            messages: [
                { role: 'ai', content: '您好！我是您的AI助手，有什么可以帮助您的吗？' }
            ]
        },
        computed: {
            isDarkTheme() {
                return this.theme === 'dark';
            }
        },
        created: function () {
            this.currentUser();
            this.getSessionId();
        },
        mounted: function () {
            // 监听输入框的键盘事件
            this.$nextTick(() => {
                const textarea = document.getElementById('user-input');
                if (textarea) {
                    textarea.addEventListener('keypress', this.handleKeyPress);
                }
                
                // 添加全局点击事件以关闭菜单
                document.addEventListener('click', (event) => {
                    // 检查点击是否在菜单按钮上
                    if (!event.target.closest('.menu-btn') && !event.target.closest('.menu-dropdown')) {
                        this.closeAllMenus();
                    }
                });
            });
        },
        methods: {
            // 用户相关方法
            currentUser: function () {
                const that = this;
                $.ajax({
                    url: "../../auth/current-user",
                    type: "get",
                    dataType: "json",
                    contentType: "application/json;charset=UTF-8",
                    async: false,
                    success: function (data) {
                        that.currentLoginUser = data.data;
                    }
                });
            },
            
            // 主题相关方法
            toggleTheme() {
                this.theme = this.theme === 'light' ? 'dark' : 'light';
                localStorage.setItem('ai-chat-theme', this.theme);
                document.body.classList.toggle('dark-theme', this.theme === 'dark');
            },
            
            // 会话相关方法
            async getSessionId() {
                try {
                    const response = await fetch('../../api/langchain/getSessionId');
                    const dataJson = await response.json();
                    this.sessionId = dataJson.data;
                } catch (error) {
                    console.error('会话ID获取失败', error);
                }
            },
            
            // 聊天相关方法
            handleKeyPress(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    this.sendMessage();
                }
            },
            
            sendMessage() {
                const message = this.userInput.trim();
                if (!message) return;
                
                // 添加用户消息
                this.addMessage('user', message);
                this.userInput = '';
                
                // 显示终止按钮，隐藏发送按钮
                this.isResponding = true;
                
                // 调用API获取响应
                this.connectSSE(message);
            },
            
            stopResponse() {
                if (this.currentEventSource) {
                    this.currentEventSource.close();
                    this.currentEventSource = null;
                    
                    // 切换回发送按钮
                    this.isResponding = false;
                    
                    // 在最后一条AI消息后添加"(已终止)"标记
                    const aiMessages = this.messages.filter(msg => msg.role === 'ai');
                    if (aiMessages.length > 0) {
                        const lastAIMessage = aiMessages[aiMessages.length - 1];
                        if (!lastAIMessage.content.includes('(已终止)')) {
                            lastAIMessage.content += ' (已终止)';
                        }
                    }
                }
            },
            
            addMessage(role, content) {
                this.messages.push({ role, content });
                this.chatHistory.push({ role, content });
                
                // 自动滚动到底部
                this.$nextTick(() => {
                    const messagesDiv = document.getElementById('chat-messages');
                    if (messagesDiv) {
                        messagesDiv.scrollTop = messagesDiv.scrollHeight;
                    }
                });
            },
            
            connectSSE(chatMessage) {
                // 在消息列表中添加一个带"正在输入"指示器的AI消息
                const aiMessageIndex = this.messages.length;
                this.messages.push({ role: 'ai', content: '', typing: true });
                
                // 自动滚动到底部
                this.$nextTick(() => {
                    const messagesDiv = document.getElementById('chat-messages');
                    if (messagesDiv) {
                        messagesDiv.scrollTop = messagesDiv.scrollHeight;
                    }
                });
                
                // 连接SSE
                this.currentEventSource = new EventSource('../../api/langchain/sseBigTwo?chatMessage=' + encodeURIComponent(chatMessage) + "&sessionId=" + this.sessionId);
                
                let responseText = '';
                
                this.currentEventSource.onmessage = (event) => {
                    const data = JSON.parse(event.data);
                    const content = data.dataToSend[1].data;
                    
                    if (content !== "stop") {
                        responseText += content;
                        this.messages[aiMessageIndex].content = responseText;
                    } else {
                        // 移除输入指示器
                        this.messages[aiMessageIndex].typing = false;
                        this.chatHistory.push({ role: 'ai', content: responseText });
                        
                        // 切换回发送按钮
                        this.isResponding = false;
                        
                        // 关闭事件源
                        this.currentEventSource.close();
                        this.currentEventSource = null;
                    }
                    
                    // 自动滚动到底部
                    this.$nextTick(() => {
                        const messagesDiv = document.getElementById('chat-messages');
                        if (messagesDiv) {
                            messagesDiv.scrollTop = messagesDiv.scrollHeight;
                        }
                    });
                };
                
                this.currentEventSource.onerror = () => {
                    console.error('SSE连接异常');
                    
                    // 移除输入指示器，显示错误信息
                    this.messages[aiMessageIndex].typing = false;
                    this.messages[aiMessageIndex].content = responseText || '抱歉，连接出现问题，请稍后再试。';
                    
                    // 切换回发送按钮
                    this.isResponding = false;
                    
                    // 关闭事件源
                    this.currentEventSource.close();
                    this.currentEventSource = null;
                };
            },
            
            clearChat() {
                // 清空消息，保留欢迎消息
                this.messages = [
                    { role: 'ai', content: '您好！我是您的AI助手，有什么可以帮助您的吗？' }
                ];
                
                // 清空历史记录
                this.chatHistory = [];
            },
            
            newChat() {
                // 终止当前响应（如果有）
                if (this.currentEventSource) {
                    this.currentEventSource.close();
                    this.currentEventSource = null;
                    this.isResponding = false;
                }
                
                // 获取新的会话ID并清空对话
                this.getSessionId().then(() => {
                    this.clearChat();
                    
                    // 这里可以添加将新对话添加到历史列表的逻辑
                    // this.addChatToHistory('新对话', new Date());
                });
            },
            
            loadChatHistory(chatId) {
                // 关闭所有菜单
                this.historySections.forEach(section => {
                    section.items.forEach(item => {
                        item.showMenu = false;
                    });
                });
                
                // 设置活跃状态
                this.historySections.forEach(section => {
                    section.items.forEach(item => {
                        item.active = (item.id === chatId);
                    });
                });
                
                // 这里添加加载对应对话历史的逻辑
                // 实际实现时可以调用API获取历史记录
            },
            
            // 切换菜单显示状态
            toggleMenu(chatId, event) {
                // 关闭其他所有菜单
                this.historySections.forEach(section => {
                    section.items.forEach(item => {
                        if (item.id !== chatId) {
                            item.showMenu = false;
                        }
                    });
                });
                
                // 切换当前菜单状态
                this.historySections.forEach(section => {
                    const item = section.items.find(item => item.id === chatId);
                    if (item) {
                        item.showMenu = !item.showMenu;
                        if (item.showMenu) {
                            this.$nextTick(() => {
                                const menuBtn = event.currentTarget;
                                const historyItem = menuBtn.closest('.history-item');
                                const menuDropdown = menuBtn.nextElementSibling;
                                
                                // 计算菜单位置
                                // 使用绝对定位，相对于历史记录项的右下角
                                menuDropdown.style.position = 'absolute';
                                menuDropdown.style.right = '0';
                                menuDropdown.style.top = '100%';
                                menuDropdown.style.marginTop = '5px';
                                menuDropdown.style.zIndex = '1000';
                            });
                        }
                    }
                });
            },
            
            // 点击其他位置隐藏菜单
            closeAllMenus() {
                this.historySections.forEach(section => {
                    section.items.forEach(item => {
                        item.showMenu = false;
                    });
                });
            },
            
            // 删除对话
            deleteChat(chatId) {
                // 关闭菜单
                this.historySections.forEach(section => {
                    const item = section.items.find(item => item.id === chatId);
                    if (item) {
                        item.showMenu = false;
                    }
                });
                
                // 从历史记录中删除
                this.historySections.forEach(section => {
                    section.items = section.items.filter(item => item.id !== chatId);
                });
                
                // 如果删除的是当前活跃的对话，则清空聊天记录
                const isActiveChat = this.historySections.some(section => 
                    section.items.some(item => item.id === chatId && item.active)
                );
                
                if (isActiveChat) {
                    this.clearChat();
                }
            }
        }
    });
}); 