<template>
    <div class="app-layout">
        <div class="side-bar">
            <div class="logo-section">
                <img src="@/assets/images/common/ai/logo.png" alt="新基础 小新" width="160" height="160" />
                <span class="logo-text">新基础 小新</span>
            </div>
            <div>
                <ul>
                    <li><el-text>我的学习压力大，每天睡不好怎么办？</el-text></li>
                    <li><el-text>帮我查一下2024年清华大学在四川省录取分数线</el-text></li>
                </ul>
            </div>
        </div>
        <div class="main-content">
            <div class="chat-container">
                <div class="message-list">
                    <div v-for="item in chatRecordList" :key="item.id">
                        <!-- 会话图标 -->
                        <!--<div :class="item.isUser == 1? 'user-image' : 'system-image' "></div>-->
                        <div v-if="item.isUser == 1" class="user-message">
                            <img src="@/assets/images/common/ai/user.png" alt="icon"/>
                            <span class="user-message-content">{{item.content}}</span>
                        </div>
                        <div v-else class="message bot-message">
                            <img src="@/assets/images/common/ai/system.png" alt="icon"/>
                            <div class="bot-message-content" v-html="item.content"></div>
                        </div>
                    </div>
                </div>
                <div class="message-box">
                    <div class="typing-message">
                        <span>
                            <span v-html="streamHtmlData"></span>
                            <span class="loading-dots">
                                <span class="dot"></span>
                                <span class="dot"></span>
                            </span>
                        </span>
                    </div>
                </div>
                <el-button @click="stopMessage">停止回答</el-button>
            </div>
            <div class="input-container">
                <el-input
                        v-model="inputMessage"
                        placeholder="请输入消息"
                        @keyup.enter="sendMessage"
                ></el-input>
                <el-button @click="sendMessage" :disabled="isSending" type="primary">发送</el-button>
            </div>
        </div>
        <div class="control-bar">
            <div class="control-button-box">
                <div class="control-button">
                    <el-button style="width:140px">退出</el-button>
                </div>
                <div class="control-button">
                    <el-button style="width:140px">静音</el-button>
                </div>
                <div class="control-button">
                    <el-button style="width:140px">新会话</el-button>
                </div>
            </div>
            <div class="session-list-box">

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

<script setup>
    import {aiChatRecordList} from '@/api/xjc-integratedmachine/common/aiChat.js'
    import { getToken } from '@/utils/auth'
    import { marked } from 'marked'

    // 聊天记录
    let chatRecordList = ref([])
    // md流式数据
    const streamMarkdownData = ref('');
    // html流式数据
    let streamHtmlData = ref('');
    // 流式加载状态
    const isLoading = ref(false);
    // 读取器实例
    let reader = null;
    // AbortController用于中止请求
    let controller = null;
    // 输入的问题
    let inputMessage = ref('')
    // 发送标识
    let isSending = ref(false)
    // 查看所有聊天记录
    list();
    function list() {
        let queryForm = {

        }
        aiChatRecordList(queryForm).then(resp =>{
            console.log(resp)
            chatRecordList.value = resp.rows;
        })
    }

    const sendMessage = () => {
/*        if (inputMessage.value.trim()) {
            sendRequest(inputMessage.value.trim())
            inputMessage.value = ''
        }*/
    }

    const sendRequest = async(message) => {
        // 用户信息
        const userMessage = {
            isUser: true,
            content: message,
            isTyping: false
        }
        // 消息加入聊天记录
        // chatRecordList.value.push(userMessage)
        try{
            isLoading.value = true;
            streamMarkdownData.value = ''; // 清空之前的数据

            // 创建AbortController以便可以中止请求
            controller = new AbortController();

            // 请求体
            let form = {
                "content": message? message: "你是谁？"
            }
            // 发送fetch请求
            const response = await fetch('/dev-api/ai/chat/record/stream', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + getToken()
                },
                body: JSON.stringify(form)
            });

            // 获取可读流的读取器
            reader = response.body.getReader();
            const decoder = new TextDecoder('utf-8');

            // 循环读取流数据
            while (true) {
                const { done, value } = await reader.read();
                if (done) break; // 如果流读取完成则退出循环

                // 解码并追加数据
                let chunk = decoder.decode(value, { stream: true });
                chunk = chunk.replace(/\n\n/g, '').replace(/data:/g, '')
                streamMarkdownData.value += chunk;
                streamHtmlData.value = marked(streamMarkdownData.value)
            }
        }catch (error) {
            // 如果是手动中止，不显示错误
            if (error.name !== 'AbortError') {
                console.error('流式读取失败:', error);
                streamMarkdownData.value = 'Error: ' + error.message;
            }
        } finally {
            streamHtmlData.value = marked(streamMarkdownData.value)
            isLoading.value = false;
            console.log("==============");
        }
    }

    const stopMessage = () => {
        if (reader) {
            // 取消读取
            reader.cancel().catch(() => {});
            reader = null;
        }
        if (controller) {
            // 中止请求
            controller.abort();
            controller = null;
        }
        isLoading.value = false;
    }

    onMounted(()=>{
        sendMessage()
    })

</script>

<script>
    export default {
        name: "chat"
    }
</script>

<style scoped>
    .app-layout {
        display: flex;
        height: 100vh;
        width: 100vw;
    }

    .side-bar {
        width: 20vw;
        background-color: #f4f4f9;
        padding: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .main-content {
        width: 70vw;
        height: 100vh;
        flex: 1;
        padding: 20px;
        overflow-y: auto;
    }
    .chat-container {
        display: flex;
        flex-direction: column;
        height: 90vh;
        /*overflow-y: auto;*/
    }

    .logo-section {
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    /*控制区*/
    .control-bar{
        width: 10vw;
        background-color: #f4f4f9;
        padding: 20px;
    }

    .control-button-box {

    }
    .control-button {
        display: flex;
        justify-content: center;
        margin: 4px 0;
    }

    .session-list-box{

    }

    /*聊天列表*/
    .message-list{
        flex: 1;
        overflow-y: auto;
        padding: 10px;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        background-color: #fff;
        margin-bottom: 10px;
        display: flex;
        flex-direction: column;
    }

    .every-message {
        margin-bottom: 10px;
        padding: 10px;
        border-radius: 4px;
        display: flex;
        align-items: center;
        width: 40vw;
        /* align-items: center; */
    }

    .user-message {
        display: flex;
        align-self: flex-end;
        flex-direction: row-reverse;
        align-items: center;
        margin: 4px;
    }
    .user-message-content {
        background-color: #e1f5fe;
        padding: 10px;
        border-radius: 4px;
    }

    .bot-message {
        max-width: 70%;
        display: flex;
        align-self: flex-start;
        align-items: flex-start;
        margin: 4px;
    }

    .bot-message-content {
        background-color: #f1f8e9;
        padding: 10px;
        border-radius: 4px;
    }

    .system-image {
        width: 32px;
        height:32px;
        background-image: url('@/assets/images/common/ai/system.png');
    }

    .user-image {
        width: 32px;
        height:32px;
        background-image: url('@/assets/images/common/ai/user.png');
    }

    /* 每个消息的区域 */
    .message-box {
        /*max-height: 300px;*/
        width: 60vw;
        /*height: 30vh;*/
        overflow-y: auto;
        border: 1px solid #eee;
        padding: 10px;
        margin-top: 10px;
        background: #f9f9f9;
    }

    pre {
        white-space: pre-wrap;
        word-wrap: break-word;
    }
    .loading-dots {
        padding-left: 5px;
    }
    .dot {
        display: inline-block;
        margin-left: 5px;
        width: 8px;
        height: 8px;
        background-color: #000000;
        border-radius: 50%;
        animation: pulse 1.2s infinite ease-in-out both;
    }
    .dot:nth-child(2) {
        animation-delay: -0.6s;
    }

    @keyframes pulse {
        0%,
        100% {
            transform: scale(0.6);
            opacity: 0.4;
        }

        50% {
            transform: scale(1);
            opacity: 1;
        }
    }

    /*输入框*/
    .input-container {
        display: flex;
    }

    .input-container .el-input {
        flex: 1;
        margin-right: 10px;
    }
</style>