<script setup lang="ts">
import { ref, nextTick, inject, onMounted, watch, computed } from 'vue'
import MessageBubble from '@/components/common/ai/MessageBubble.vue'
import TypingIndicator from '@/components/common/ai/TypingIndicator.vue'
import WelcomeContent from '@/components/AiChat/WelcomeContent.vue';
import { abortConversation, getConversationHistory, sendMessage, SSEData } from '@/api/conversation';
import useConversationStore from '@/stores/chatConversation';
import { useRoute, useRouter } from 'vue-router';
import formatDate from '@/utils/formatDate';
import { marked } from 'marked'
import * as echarts from 'echarts';
const router = useRouter()
const route = useRoute()
const conversationStore = useConversationStore()
const getConversationMessages = async (conversationId) => {
    const res = await getConversationHistory(conversationId)
    return res
}

/**
 * 监听路由会话ID的变化，获取会话消息
 */
let lastConversationId = null;

watch(() => route.query.conversationId, async (newVal) => {
    // 避免重复请求
    if (newVal === lastConversationId) return;
    localStorage.removeItem('currentMessages');

    lastConversationId = newVal ?? null;
    console.log('会话ID变化:', newVal);
    /**
     * 如果会话ID为-1，表示新建会话
     */
    if (newVal === '-1') {
        conversationStore.isReadyNewConversation = true;
        conversationStore.currentConversationMessages = [];
        return;
    }
    // 跳转到首页,展示欢迎内容
    else if (!newVal) {
        conversationStore.isReadyNewConversation = false;
        conversationStore.currentConversationMessages = [];
        return;
    }
    // 如果会话ID有效，加载已有会话的消息
    else if (newVal) {
        conversationStore.isReadyNewConversation = false;

        // 获取会话消息
        const messagesRes = await getConversationMessages(newVal) as Message1[];
        const filteredMessages = messagesRes.map((item) => ({
            text: item.content,
            sender: item.role === 1 ? "user":"ai",
            sentAt: item.timestamp
        }));
        // 更新会话消息
        conversationStore.currentConversationMessages = filteredMessages;

        // 存储到 localStorage (如果数据有更新)
        const currentMessages = localStorage.getItem('currentMessages');
        if (currentMessages !== JSON.stringify(filteredMessages)) {
            localStorage.setItem('currentMessages', JSON.stringify(filteredMessages));
        }
    }
}, { immediate: true });

// 消息类型
interface Message {
    text: string;
    sender: 'user' | 'ai'; // 消息发送者
    sentAt: string;  // ISO 8601 格式的字符串表示日期和时间

}
interface Message1 {
    id: number; // 消息ID
    sender:'user' | 'ai';// 消息发送者
    role: 1 | 2; // 消息发送者
    content: string; // 消息内容
    timestamp: string;  // ISO 8601 格式的字符串表示日期和时间
    conversationId: string;

}
interface ResultData{
            conclusion:string;//结论
            data:string;//数据代码,table的代码或者echarts的option配置对象代码
            status:1|2;//1:table的代码;2:echarts的option配置对象代码
        }


// 组件状态
const taskId = ref<string | null>(null)
const inputMessage = ref('')
const isTyping = ref(false)
const chatContainer = ref<HTMLElement | null>(null)
const newAiMessage = ref<Message>();
// 快速提示语
const quickPrompts = [
    "你能做什么？",
    "写一个冒泡排序",
    "解释一下 Vue 3 的响应式原理",
    "帮我优化一段代码",
]

const useQuickPrompt = (prompt: string) => {
    inputMessage.value = prompt
    handleSendClick()
}

const scrollToBottom = async () => {
    await nextTick()
    if (chatContainer.value) {
        const container = chatContainer.value
        // 使用 requestAnimationFrame 确保在下一帧渲染时滚动
        requestAnimationFrame(() => {
            container.scrollTop = container.scrollHeight
        })
    }
}

// 监听消息列表变化，自动滚动到底部
watch(() => conversationStore.currentConversationMessages.length, () => {
    scrollToBottom()
})

// 监听当前AI消息的变化，自动滚动到底部
watch(() => conversationStore.currentConversationMessages[conversationStore.currentConversationMessages.length - 1]?.text, () => {
    scrollToBottom()
})

const handleSendClick = async () => {
    if (inputMessage.value.trim()) {
        await handleSuggestionClick(inputMessage.value)
    }
}
// 初始化时加载历史记录
onMounted(() => {
    const messages = localStorage.getItem('currentMessages')
    if (messages) {
        try {
            const parsed = JSON.parse(messages)
            conversationStore.currentConversationMessages = parsed

        } catch (e) {
            console.error('Failed to parse chat history:', e)
        }
    }
})

const textareaRef = ref<HTMLTextAreaElement | null>(null)

// 处理键盘事件
const handleEnterPress = async (e: KeyboardEvent) => {
    if (e.shiftKey) {
        return // Shift + Enter 换行
    }
    // console.log(inputMessage.value.trim());
    console.log(e);

    //业务逻辑有问题：输入第二个字符后就发送了 :solved
    if (inputMessage.value.trim() && e.key === "Enter") {
        await handleSendClick()
    }
}

// 调整文本框高度
const adjustHeight = () => {
    const textarea = textareaRef.value
    if (textarea) {
        textarea.style.height = 'auto'
        textarea.style.height = textarea.scrollHeight + 'px'
    }
}

// 监听输入框内容变化
watch(inputMessage, () => {
    nextTick(() => {
        adjustHeight()
    })
})

// 初始化时设置高度
onMounted(() => {
    adjustHeight()
})

const loadingSuggestions = ref(false)
const refreshingSuggestion = ref<number | null>(null)
const suggestions = ref([
    '🤖 你好！让我来帮你解决问题',
    '💡 需要编程帮助吗？',
    '📚 有什么想学习的知识？',
    '🎨 需要创意灵感吗？'
])
const chipColors = ['#9C27B0', '#2196F3', '#4CAF50', '#FF9800', '#E91E63', '#00BCD4']

// 生成问题建议的提示语
const generateTipPrompt = () => {
    return `请生成一个简短的、有趣的问题示例，这个问题应该能展示AI助手的能力。
  要求：
  1. 不超过30个字
  2. 要包含emoji表情
  3. 直接返回问题文本，不要包含其他内容
  4. 每次都要生成不同的问题
  5. 问题类型可以包括：编程开发、知识解答、数学计算、创意写作等
  6. 不要带引号或其他标点符号`
}

// 获取单个问题建议
const getTip = async () => {
    return '🤖 让我来帮你解决问题吧'
}

// 获取所有问题建议
const getSuggestions = async () => {
    loadingSuggestions.value = true
    suggestions.value = []

    try {
        // 并行获取所有建议
        const promises = Array(4).fill(null).map(() => getTip())
        const results = await Promise.all(promises)

        // 过滤掉重复的建议
        // const uniqueSuggestions = [...new Set(results)]
        // 过滤掉重复的建议
        const uniqueSuggestions = results.filter((value, index, self) => self.indexOf(value) === index);

        // 如果有重复导致数量不足，补充获取
        while (uniqueSuggestions.length < 4) {
            const newTip = await getTip()
            if (!uniqueSuggestions.includes(newTip)) {
                uniqueSuggestions.push(newTip)
            }
        }

        suggestions.value = uniqueSuggestions
    } catch (error) {
        console.error('获取建议失败:', error)
    } finally {
        loadingSuggestions.value = false
    }
}

// 刷新单个建议
const refreshSuggestion = async (index: number) => {
    refreshingSuggestion.value = index
    try {
        const newSuggestion = await getTip()
        suggestions.value[index] = newSuggestion
    } finally {
        refreshingSuggestion.value = null
    }
}

// 组件加载时获取建议
// onMounted(async () => {
//     await getSuggestions()
// })

/**
 * 把问题推送到messages列表中
 * @param text 待发送的文本内容
 */
const handleSuggestionClick = async (text: string) => {
    conversationStore.currentConversationMessages.push({
        text,
        sender: 'user',
        sentAt: formatDate(new Date())

    })
    await handleUserMessage(text)
}

let eventSource = undefined;
// 处理用户消息
const handleUserMessage = async (text: string) => {
    isTyping.value = true
    inputMessage.value = ''
    // 创建一个新的消息对象来存储AI的回复
    newAiMessage.value = {
        text: '',
        sender: 'ai',
        sentAt: formatDate(new Date())
    }
    try {
        let currentConversationId = ''
        conversationStore.currentConversationMessages.push(newAiMessage.value)
        // 发送用户消息到后端
        // eventSource = new  EventSource(import.meta.env.VITE_API_BASE_URL + '/ai/stream');
        await sendMessage(conversationStore.isReadyNewConversation ? '' : conversationStore.conversationId, text,
            async (aiResText: string) => {
                console.log(aiResText,1);
                let sseData:SSEData = JSON.parse(aiResText);
                if(sseData.status != 0){
                    //进度提示信息
                    newAiMessage.value.text += sseData.content + '<br>'
                }else{
                    //最终结果
                let result:ResultData = JSON.parse(sseData.content);
                    let html = render(result);
                    newAiMessage.value.text = html;
                    // newAiMessage.value.text = result.conclusion;
                }
                
                await scrollToBottom()
            }, (paramTaskId, conversationId) => {
                taskId.value = paramTaskId
                currentConversationId = conversationId
            })

        // console.log(`output->1`, 1)
        // if (route.query.conversationId === '-1') {
        //     console.log(`output->2`, 2)

        //     await router.replace({ name: 'home', query: { conversationId: currentConversationId } })
        //     console.log(`output->3`, 3)

        // }
        // console.log(`output->4`, 4)


    } catch (error) {
        console.error('获取AI回复失败:', error)
        conversationStore.currentConversationMessages.push({
            text,
            sender: 'ai',
            sentAt: formatDate(new Date())
        })
    } finally {
        isTyping.value = false
    }
}

const handleAbort = async () => {

    taskId.value && console.log('终止任务', taskId.value)
    await abortConversation(taskId.value)
    conversationStore.currentConversationMessages.pop()
    isTyping.value = false
}
const showInp = computed(() => {
    if (conversationStore.isReadyNewConversation || route.query.conversationId) {
        return true
    }
    else {
        return false
    }
})
//渲染markdown
const renderMarkDown = (text:string)=>{
    let html = marked.parse(text);
    return html;
}
//渲染echarts图表
const renderEcharts = (optionJson:string)=>{
    let option = JSON.parse(optionJson);
    let div = document.createElement('div');
    let echart = echarts.init(div);
    echart.dispose();
    echart.setOption(JSON.parse(option));
    //获取html代码
    let html = div;
    return html;
}
//渲染
const render = (result:ResultData)=>{
    let html = result.conclusion;
    if(result.status === 1){
        //表格
        let table = renderMarkDown(result.data);
        html += table;
    }else{
        let charts = renderEcharts(result.data);
        html += charts;
    }
    return html;
}
</script>

<template>
    <div class="container">
        <WelcomeContent v-if="!route.query.conversationId" />

        <div class="chat-container" ref="chatContainer">
            <div class="messages-wrapper">
                <MessageBubble v-for="(message, index) in conversationStore.currentConversationMessages" :key="index" :message="message" />
                <!-- <MessageBubble v-for="(message, index) in conversationStore.currentConversationMessages" :key="index" :message="message" /> -->
                <TypingIndicator v-if="isTyping && !newAiMessage.text" />
            </div>
        </div>

        <footer class="footer" v-if="showInp">
            <textarea ref="textareaRef" v-model="inputMessage" class="inp" placeholder="输入你的问题..."
                @keydown="handleEnterPress" @input="adjustHeight" rows="1"></textarea>
            <div class="right">
                <!-- <div class="img">
                    <img src="@/assets/tabBar/Picture.svg" alt="">
                </div> -->
                <div class="send">
                    <button type="submit" v-auth="() => handleSendClick()" v-show="!isTyping">发送</button>
                    <button type="button" v-show="isTyping" @click="handleAbort">终止</button>
                </div>
            </div>

        </footer>
    </div>
</template>

<style scoped>
.container {
    position: relative;
    height: 810px;
    width: 100%;
    overflow: hidden;



    .footer {

        position: fixed;
        bottom: 15px;
        left: 15%;
        width: 70%;
        min-height: 45px;
        align-self: center;
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1px solid #D1D5DB;
        border-radius: 10px;
        margin-bottom: 10px;

        .inp {
            min-width: 85%;
        }

        .right {
            width: 15%;
            height: 36px;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 20px;

            button {
                background-color: #000000;
                color: #FFFFFF;
            }

            .img {
                border: 1px solid #D1D5DB;
                width: 32px;
                height: 32px;
                display: flex;
                justify-content: center;
                align-items: center;
            }

            img {
                width: 14px;
                height: 14px;
            }

            .send {
                width: 60px;
                height: 36px;

                button {
                    width: 100%;
                    height: 100%;
                }
            }
        }
    }
}

.messages-wrapper {
    flex: 1 0 1;
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.chat-container {
    min-width: 100%;
    max-height: calc(100vh - 180px);
    /* 设置最大高度，留出输入框空间 */
    overflow-y: auto;
    scroll-behavior: smooth;
    padding: 20px;
    margin-bottom: 70px;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
}

.chat-container::-webkit-scrollbar {
    width: 4px;
}

.chat-container::-webkit-scrollbar-track {
    background: transparent;
}

.chat-container::-webkit-scrollbar-thumb {
    background: #e2e8f0;
    border-radius: 4px;
}

.chat-container::-webkit-scrollbar-thumb:hover {
    background: #cbd5e1;
}
</style>
