<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="flex border-blue-300 mx-4 p-1 bg-white rounded-xl">
            <div class="flex items-center flex-1 p-2 box-border rounded-xl cursor-pointer"
                :class="selectedRole === 'legal' ? 'bg-blue-300 text-white' : ''" @click="selectRole('legal')">
                <img src="@/assets/images/ai_lvshi.webp" class="w-10 h-10 rounded-xl mr-2" alt="AI律师">
                法律咨询
            </div>
            <div class="flex items-center flex-1 p-2 box-border rounded-xl cursor-pointer"
                :class="selectedRole === 'emotional' ? 'bg-blue-300 text-white' : ''" @click="selectRole('emotional')">
                <img src="@/assets/images/ai_qinggan.png" class="w-10 h-10 rounded-xl mr-2" alt="AI心理咨询师">
                情感咨询
            </div>
        </div>

        <!-- 聊天窗口 -->
        <div class="mx-4 flex flex-col flex-1 rounded-xl shadow-lg">
            <div class="flex flex-col flex-1 p-4">
                <div class="flex-1 overflow-y-auto">
                    <div v-for="(message, index) in currentMessages" :key="index" class="mb-4">
                        <div v-if="message.sender === 'ai'" class="flex justify-start items-start">
                            <!-- 可根据角色显示不同的AI形象 -->
                            <div class="inline-block max-w-max rounded-xl bg-white p-2 text-left"
                                :class="selectedRole === 'legal' ? 'text-green-600' : 'text-purple-600'">
                                <!-- 如果是AI消息，显示加载中或文本 -->
                                <div v-if="message.loading" class="flex justify-center items-center">
                                    <div class="loader"></div> <!-- 加载动画 -->
                                </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>
                <!-- 输入区域 -->
                <div class="p-2 w-full input-area flex items-center gap-2">
                    <input v-model="userMessage"
                        :placeholder="selectedRole === 'legal' ? '请输入您的法律问题...' : '请输入您的情感问题...'"
                        class="flex-1 p-2 border rounded-lg" type="text" @keyup.enter="sendMessage" />
                    <button class="shadow p-2 bg-blue-500 text-white rounded-lg" @click="sendMessage">
                        发送
                    </button>
                    <!-- <button class="shadow p-2 bg-blue-500 text-white rounded-lg" @click="handleService">
                        服务
                    </button> -->
                </div>
            </div>
        </div>
    </div>
</template>

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

// 当前选中的角色，默认是法律咨询
const selectedRole = ref('legal')

// 用户输入的消息
const userMessage = ref('')

// 存储每个角色的消息记录
const messages = ref({
    legal: [
        { sender: 'ai', text: '欢迎！请问有什么法律问题需要帮助？' },
    ],
    emotional: [
        { sender: 'ai', text: '欢迎！请问有什么情感问题需要帮助？' },
    ]
})

// 存储每个角色的 sessionID
const sessionID = ref({
    legal: "",
    emotional: ""
})

let reader = {
    legal: null,
    emotional: null
}

// 计算当前选中的角色的消息
const currentMessages = computed(() => messages.value[selectedRole.value])

// 选择角色
function selectRole(role) {
    if (selectedRole.value !== role) {
        selectedRole.value = role
        // 如果该角色还没有消息记录，初始化欢迎消息
        if (!messages.value[role]) {
            messages.value[role] = [
                { sender: 'ai', text: role === 'legal' ? '欢迎！请问有什么法律问题需要帮助？' : '欢迎！请问有什么情感问题需要帮助？' },
            ]
            sessionID.value[role] = ""
        }
    }
}

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

    // 获取当前角色
    const role = selectedRole.value

    // 用户消息推入对应角色的消息列表
    messages.value[role].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[role].push(aiMessage)

    // 发起请求
    fetch('/api/v1/chat/send', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'x': x,
            't': t,
        },
        body: JSON.stringify({
            prompt: userMessage.value,
            platform_id: 2,
            role_id: 1, // 根据角色选择不同的 roleid
            openid: 'openid' + localStorage.getItem("token"),
            userid: 'userid' + localStorage.getItem("token"),
            sessionid: sessionID.value[role]  // 使用对应角色的 sessionID
        }),
    })
        .then((response) => {
            if (response.ok && response.body) {
                // 获取到响应的 ReadableStream
                reader[role] = response.body.getReader()
                const decoder = new TextDecoder()
                let buffer = ''

                // 使用流的方式逐步读取数据
                const readStream = () => {
                    reader[role].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() // 去掉 'data:' 前缀
                                }
                                try {
                                    // 解析消息数据
                                    const parsedMessage = JSON.parse(message)
                                    console.log("parsedMessage", parsedMessage)
                                    // 存储 session_id
                                    sessionID.value[role] = parsedMessage.output.session_id

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

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

                                } 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(() => {
    // 取消所有角色的流读取
    Object.keys(reader).forEach(role => {
        if (reader[role]) {
            reader[role].cancel()
        }
    })
})
const handleService = () => {
    showConfirmDialog({
        title: '更多服务',
        message:
            '更多服务请访问全能查官网: https://www.quannengcha.com 或关注全能查公众号',
    })
        .then(() => {
            // // 复制链接到剪贴板
            // const url = 'https://www.quannengcha.com';
            // navigator.clipboard.writeText(url)
            //     .then(() => {
            //         showToast('复制成功');

            //     })
            //     .catch(err => {
            //         // 复制失败时的错误处理
            //         console.error('复制失败:', err);
            //     });

        })
        .catch(() => {
            // on 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);
    }
}

/* Tab Styles */
.flex.border-blue-300>div {
    transition: all 0.3s;
}
</style>
