<template>
    <div class="flex flex-col box-border from-blue-100 to-white bg-gradient-to-b pt-4 flex-1 pb-4">
        <div class="mx-4 flex flex-col flex-1 rounded-xl shadow-lg">
            <!-- Chat Window -->
            <div class="w-full text-center py-2 text-slate-800 font-bold text-xl bg-white rounded-t-xl">AI律师</div>

            <div class="flex flex-col flex-1 p-4">
                <div class=" flex-1  overflow-y-auto">
                    <div v-for="(message, index) in messages" :key="index" class="mb-4">
                        <div v-if="message.sender === 'ai'" class="flex justify-start items-start">
                            <img class="w-10 h-10 rounded-xl mr-2" src="@/assets/images/ai_picture.webp" alt="AI律师">
                            <div
                                class="inline-block max-w-max rounded-xl bg-white p-2 text-left text-green-600 font-medium shadow-md">
                                <!-- If AI message, show loading or text -->
                                <div v-if="message.loading" class="flex justify-center items-center">
                                    <div class="loader"></div> <!-- Loading Spinner -->
                                </div>
                                <div v-else>
                                    {{ message.text }}
                                </div>
                            </div>
                        </div>
                        <div v-else class="flex justify-end">
                            <div class=" ml-auto inline-block max-w-max rounded-xl from-sky-300 via-sky-300 to-sky-300
                        bg-gradient-to-r p-2 text-right text-white font-medium shadow-md">
                                {{ message.text }}
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Input Area -->
                <div class="p-2 w-full input-area flex items-center gap-2">
                    <input v-model="userMessage" placeholder="请输入您的问题..." class="flex-1 p-2 border rounded-lg"
                        type="text" />
                    <button class="shadow p-2 bg-blue-500 text-white rounded-lg" @click="sendMessage">
                        发送
                    </button>
                </div>
            </div>


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

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import chatEncrypt from "@/utils/chatEncrypt"

const userMessage = ref('')  // 用户输入的消息
const messages = ref([       // 消息数组，存储用户和AI的消息
    { sender: 'ai', text: '欢迎！请问有什么可以帮助您的吗？' },
])
const sessionID = ref("")     // 存储 sessionID
let reader;

async function sendMessage() {
    if (userMessage.value.trim() === '') return;

    // 用户消息推入消息列表
    messages.value.push({ sender: 'user', text: userMessage.value });

    const t = Date.now();
    const x = chatEncrypt(String(t));

    // 在消息列表中添加一个 AI 消息并标记为加载状态
    const aiMessage = { sender: 'ai', text: '', loading: true };
    messages.value.push(aiMessage);

    // 发起请求
    fetch('/api/v1/chat/send', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            x,
            t,
        },
        body: JSON.stringify({
            prompt: userMessage.value,
            platform_id: 2,
            roleid: 1,
            openid: 'openid' + localStorage.getItem("token"),
            userid: 'userid' + localStorage.getItem("token"),
            sessionid: sessionID.value  // 可以在请求中添加 sessionID
        }),
    })
        .then((response) => {
            if (response.ok && response.body) {
                // 获取到响应的 ReadableStream
                reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                // 使用流的方式逐步读取数据
                const readStream = () => {
                    reader.read().then(({ done, value }) => {
                        if (done) {
                            return;
                        }
                        buffer += decoder.decode(value, { stream: true });

                        // 查找并处理完整的事件消息
                        let newLineIndex;
                        while ((newLineIndex = buffer.indexOf('\n')) !== -1) {
                            let message = buffer.slice(0, newLineIndex).trim();
                            if (message) {
                                aiMessage.loading = false;  // 关闭加载动画
                                if (message.startsWith('data:')) {
                                    message = message.replace('data:', '').trim(); // 去掉 'message data:' 前缀
                                }
                                try {
                                    // 解析消息数据
                                    const parsedMessage = JSON.parse(message);
                                    console.log("parsedMessage", parsedMessage)
                                    // 存储 session_id
                                    sessionID.value = parsedMessage.output.session_id;

                                    // 获取 AI 回复的文本
                                    const aiText = parsedMessage.output.text;

                                    // 逐字打印到 AI 消息
                                    aiMessage.text += aiText;
                                    messages.value = [...messages.value];  // 触发视图更新

                                } catch (e) {
                                    console.error('Failed to parse message:', e);
                                }
                            }
                            buffer = buffer.slice(newLineIndex + 1);
                        }

                        // 继续读取流
                        readStream();
                    });
                };
                readStream();
            } else {
                console.error('Failed to fetch stream');
            }
        })
        .catch((error) => {
            console.error('Request failed:', error);
        });

    userMessage.value = '';  // 清空输入框
}

onBeforeUnmount(() => {
    if (reader) {
        reader.cancel();  // 取消流读取
    }
});


</script>

<style scoped>
input {
    padding: 0.5rem;
    border: 1px solid #ddd;
    border-radius: 0.5rem;
}

button {
    padding: 0.5rem 1rem;
    background-color: #007bff;
    border: none;
    border-radius: 0.5rem;
    color: white;
}

button:hover {
    background-color: #0056b3;
}

.loader {
    border: 4px solid #f3f3f3;
    /* Light gray */
    border-top: 4px solid #3498db;
    /* Blue */
    border-radius: 50%;
    width: 24px;
    height: 24px;
    animation: spin 2s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}
</style>
