/**
 * AI聊天页面Vue应用
 */
require(['jquery', 'vue', 'utils','marked','markdown', 'global'], function ($, Vue, utils, marked,markdown) {
    // 添加点击外部关闭指令
    Vue.directive('click-outside', {
        bind: function (el, binding, vnode) {
            el.clickOutsideEvent = function (event) {
                if (!(el == event.target || el.contains(event.target))) {
                    vnode.context[binding.expression](event);
                }
            };
            document.body.addEventListener('click', el.clickOutsideEvent);
        },
        unbind: function (el) {
            document.body.removeEventListener('click', el.clickOutsideEvent);
        }
    });

    const app = new Vue({
        el: '#app',
        data: {
            // 用户相关数据
            currentLoginUser: {},
            fistLoading: true,
            // 聊天相关数据
            chatHistory: [],
            sessionId: "",
            currentEventSource: null,
            
            // UI相关数据
            theme: localStorage.getItem('ai-chat-theme') || 'light',
            isResponding: false,
            userInput: "",
            
            // 专家选择相关数据
            selectedExpert: '内部专家',
            showExpertDropdown: false,
            // 组织内网选择相关数据
            selectedOrg:'全部组织',
            showOrgDropdown: false,
            questions:[],
            guides:['请帮我推荐5位南京地区的区块链外部专家','我需要找既懂通信又擅长软件开发的内部专家','我需要网络安全领域的专家，不确定选内部还是外部'],
            // 历史对话分类
            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: '您好！我是您的专家推荐助手，有什么可以帮助您的吗？' }
            ]
        },
        computed: {
            isDarkTheme() {
                return this.theme === 'dark';
            }
        },
        created: function () {
            this.currentUser();
            this.getSessionId();
            this.getConversationHistory();
        },
        mounted: function () {
            // 监听输入框的键盘事件
            this.$nextTick(() => {
                const textarea = document.getElementById('user-input');
                if (textarea) {
                    textarea.addEventListener('keypress', this.handleKeyPress);
                }
            });
        },
        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 response = await fetch('../../api/langchain/getDialogId');
                    const dataJson = await response.json();
                    this.sessionId = dataJson.data;
                } catch (error) {
                    console.error('会话ID获取失败', error);
                }
            },
            async getConversationHistory() {
                try {
                    //const response = await fetch('../../api/langchain/getSessionId');
                    const response = await fetch('../../api/langchain/conversationHistory');
                    const dataJson = await response.json();
                    this.historySections = dataJson.data;
                } catch (error) {
                    console.error('会话获取失败', error);
                }
            },
            
            // 聊天相关方法
            handleKeyPress(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    this.sendMessage();
                }
            },
            questionClick:function(message){
                this.userInput = message;
                this.sendMessage();
            },
            sendMessage() {
                const message = this.userInput.trim();
                if (!message) return;
                if (this.fistLoading)
                    this.fistLoading = false;
                this.questions= [];
                this.stopResponse();
                // 添加用户消息
                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];
                        lastAIMessage.typing = false;
                        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('scrollContainer');
                    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('scrollContainer');
                    if (messagesDiv) {
                        messagesDiv.scrollTop = messagesDiv.scrollHeight;
                    }
                });
                // 连接SSE
                this.currentEventSource = new EventSource('../../api/langchain/sseIntelligent?chatMessage='+chatMessage+"&dialogId="+this.sessionId
                    +"&selectedExpert="+this.selectedExpert+"&selectedOrg="+this.selectedOrg);

                let responseText = '';
                var md = new markdown({
                    html: true, // 允许解析 HTML 标签
                    linkify: true, // 自动识别链接
                    typographer: true, // 启用排版优化
                    breaks: true, // 将单个换行符视为换行
                });
                this.currentEventSource.onmessage = (event) => {
                    const data = JSON.parse(event.data);
                    const content = data.dataToSend[1].data;
                    if (content !== "stop") {
                        const match = content.match(/SUGGEST\[(.*?)\]SUGGEST/);
                        if (match) {
                            const suggestionsJson = `[${match[1]}]`;
                            const suggestions = JSON.parse(suggestionsJson);
                            if (Array.isArray(suggestions)) {
                                this.questions = suggestions;
                            }
                        }else{//提示词不展示
                            responseText += content;
                        }
                        this.messages[aiMessageIndex].content = md.render(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('scrollContainer');
                        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;
                }
                this.questions = [];
                // 获取新的会话ID并清空对话
                this.getSessionId().then(() => {
                    this.clearChat();
                    
                    // 这里可以添加将新对话添加到历史列表的逻辑
                    // this.addChatToHistory('新对话', new Date());
                });
                this.fistLoading=true;
            },
            
            loadChatHistory(chatId) {
                var that=this
                // 关闭所有菜单
                this.historySections.forEach(section => {
                    section.items.forEach(item => {
                        item.showMenu = false;
                    });
                });
                //this.addMessage('user', "123456");
                // 设置活跃状态
                this.historySections.forEach(section => {
                    section.items.forEach(item => {
                        item.active = (item.id === chatId);
                    });
                });
                //
                this.sessionId = chatId;
               // this.clearChat();
                this.questions= [];
                this.messages=[];
                //这里添加加载对应对话历史的逻辑
                //实际实现时可以调用API获取历史记录
                $.ajax({
                    url: "../../api/langchain/conversationMessages?sessionId="+chatId,
                    type: "get",
                    dataType: "json",
                    contentType: "application/json;charset=UTF-8",
                    async: false,
                    success: function (data) {
                        var conversationMessages = data.data;
                        if (conversationMessages && conversationMessages.length > 0){
                            that.fistLoading = false;
                            conversationMessages.forEach(section => {
                                that.addMessage(section.role, section.content);
                            });
                        }
                    }
                });
            },
            // 删除对话
            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();
                }
                $.ajax({
                    url: "../../api/langchain/deleteChat",
                    type: "post",
                    dataType: "json",
                    contentType: "application/json;charset=UTF-8",
                    data: chatId,
                    async: false,
                    success: function (data) {
                    }
                });
            },
            // 专家选择相关方法
            toggleExpertDropdown() {
                this.showExpertDropdown = !this.showExpertDropdown;
            },
            closeExpertDropdown() {
                this.showExpertDropdown = false;
            },
            selectExpert(expert) {
                this.selectedExpert = expert;
                // 立即关闭下拉框
                this.showExpertDropdown = false;
            },
            //组织内外选择相关方法
            toggleOrgDropdown() {
                this.showOrgDropdown = !this.showOrgDropdown;
            },
            closeOrgDropdown() {
                this.showOrgDropdown = false;
            },
            selectOrg(org) {
                this.selectedOrg = org;
                // 立即关闭下拉框
                this.showOrgDropdown = false;
            }
        }
    });
}); 