/**
 * 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:[
                '引上光缆在维护下架里面是否能算距离。',
                '保险是否有雇主险要求。',
                '线路迁改列投资是否有统一规范的原则？',
                '短距离的管道的维护和整治费用，如何计取？'
            ],
            scrollOffset: 0,
            scrollInterval: null,
            transitioning: true,
            // 历史对话分类
            historySections: [
            ],

            // 消息列表
            messages: [
                // { role: 'ai', content: '您好！我是您的专家推荐助手，有什么可以帮助您的吗？' }
            ],
            showOrgSelection: false
        },
        computed: {
            isDarkTheme() {
                return this.theme === 'dark';
            },
            extendedGuides() {
                // 克隆前3项到末尾
                return [...this.guides, ...this.guides.slice(0, 3)];
            },
            scrollStyle() {
                return {
                    transform: `translateY(-${this.scrollOffset}px)`,
                    transition: this.transitioning ? 'transform 0.5s ease' : 'none',
                };
            }
        },
        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);
                }

                // 启动自动滚动
                this.startAutoScroll();

                // 添加鼠标悬停事件监听
                this.$watch('fistLoading', (newVal) => {
                    if (newVal) {
                        // 等待DOM更新
                        this.$nextTick(() => {
                            const guideItems = document.querySelectorAll('.expert-guide-item');
                            guideItems.forEach(item => {
                                item.addEventListener('mouseenter', this.pauseAutoScroll);
                                item.addEventListener('mouseleave', this.resumeAutoScroll);
                            });
                        });
                    }
                }, { immediate: true });
            });
        },
        beforeDestroy: function() {
            // 清除自动滚动定时器
            this.stopAutoScroll();

            // 移除事件监听器
            const guideItems = document.querySelectorAll('.expert-guide-item');
            guideItems.forEach(item => {
                item.removeEventListener('mouseenter', this.pauseAutoScroll);
                item.removeEventListener('mouseleave', this.resumeAutoScroll);
            });
        },
        methods: {
            // 自动滚动相关方法
            startAutoScroll: function() {
                const itemHeight = 80;
                const visibleItems = 3;
                const totalItems = this.guides.length;

                this.scrollInterval = setInterval(() => {
                    this.transitioning = true;
                    this.scrollOffset += itemHeight;

                    // 判断是否滚动到克隆项部分（即第 totalItems 行之后）
                    if (this.scrollOffset >= itemHeight * (totalItems)) {
                        // 短暂延迟后瞬间回到原始位置
                        setTimeout(() => {
                            this.transitioning = false;
                            this.scrollOffset = 0;
                        }, 500); // 等待动画结束
                    }
                }, 2000);
            },
            stopAutoScroll: function() {
                if (this.scrollInterval) {
                    clearInterval(this.scrollInterval);
                    this.scrollInterval = null;
                }
            },
            pauseAutoScroll: function() {
                this.stopAutoScroll();
            },
            resumeAutoScroll: function() {
                if (!this.scrollInterval && this.fistLoading) {
                    this.startAutoScroll();
                }
            },

            // 用户相关方法
            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() {
                // if (!this.selectedExpert) {
                //     this.showToast('请先选择专家类型（内部/外部专家）');
                //     return;
                // }
                const message = this.userInput.trim();
                if (!message) return;
                if (this.fistLoading) {
                    this.fistLoading = false;
                    // 停止自动滚动
                    this.stopAutoScroll();
                }
                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/sseTest?chatMessage='+chatMessage+"&dialogId="+this.sessionId
                    +"&selectedExpert="+this.selectedExpert+"&selectedOrg="+this.selectedOrg);//sseIntelligent

                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 = marked.parse(responseText);//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;
                // this.selectedExpert = '内部专家';
                // this.showOrgSelection =  this.selectedExpert  === '内部专家';
                // this.selectedOrg = '全部组织';

                // 重置滚动位置并重新启动自动滚动
                this.scrollOffset = 0;
                this.startAutoScroll();
            },

            loadChatHistory(chat) {
                var that=this
                var chatId=chat.id;
                // 关闭所有菜单
                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=[];

                // 如果正在显示初始推荐，停止自动滚动
                if (this.fistLoading) {
                    this.stopAutoScroll();
                }
                this.fistLoading = false;
                // this.selectedExpert = '内部专家';
                // this.showOrgSelection =  this.selectedExpert  === '内部专家';
                // this.selectedOrg = '全部组织';

                //这里添加加载对应对话历史的逻辑
                //实际实现时可以调用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;

                if (this.selectedExpert === expert) {
                    this.selectedExpert = '';
                } else {
                    this.selectedExpert = expert;
                }
                this.showOrgSelection = expert === '内部专家';
                this.selectedOrg = '全部组织';
                // 立即关闭下拉框
                this.showExpertDropdown = false;

            },
            //组织内外选择相关方法
            toggleOrgDropdown() {
                this.showOrgDropdown = !this.showOrgDropdown;
            },
            closeOrgDropdown() {
                this.showOrgDropdown = false;
            },
            selectOrg(org) {
                this.selectedOrg = org;
                // 立即关闭下拉框
                this.showOrgDropdown = false;
            },
            showToast(message) {
                // 使用你项目中已有的提示组件，或创建一个简单的提示
                const toast = document.createElement('div');
                toast.className = 'expert-toast';
                toast.textContent = message;
                document.body.appendChild(toast);

                setTimeout(() => {
                    toast.remove();
                }, 3000);
            },
            filterXSSText: function (value){
                return filterXSS(value);
            }
        }
    });
}); 