<template>
    <base-container>
        <h2 class="pt-5 pb-5">流式显示文本(需先启动node-local-server项目作为本地服务端)</h2>
        <div>
            <el-button
                type="primary"
                @click="handleSend"
                >问个问题</el-button
            >
            <el-button
                type="primary"
                @click="handleClose"
                >停止</el-button
            >
        </div>
        <div
            class="wordbox"
            ref="containerRef"
        >
            <span
                id="content"
                v-html="content"
            ></span>
        </div>
    </base-container>
</template>

<script setup>
import { onMounted, ref, nextTick } from 'vue';

const eventSource = ref(null);
const content = ref('');

const updateContent = (event) => {
    console.log(event);
    console.log('sse收到消息');
    content.value += event.data + '<br/>';
    console.log(content.value, 'content内容');
    if (event.data === 'End') {
        /** 浏览器原生EventSource，必须服务器主动告诉浏览器关闭连接，否则会进onerror事件，并一直重连 */
        handleClose();
    }
    nextTick(() => {
        scrollToBottom();
    });
};

const handleError = (event) => {
    console.log(event);
    console.log('sse连接出错');
};

const handleClose = () => {
    console.log('sse关闭');
    eventSource.value.close();
};

const containerRef = ref(null);
const scrollToBottom = () => {
    containerRef.value.scrollTop = containerRef.value.scrollHeight;
};

const handleSend = () => {
    eventSource.value = new EventSource('http://localhost:3000/events');
    eventSource.value.addEventListener('message', updateContent);
    eventSource.value.addEventListener('error', handleError);
};
</script>

<style lang="scss" scoped>
.wordbox {
    width: 100%;
    height: 100%;
    overflow: auto;
    padding: 20px;
    border: 1px solid #ccc;
    margin: 20px 0;
    border-radius: 5px;
}
</style>
