<template>
    <div class="chat-right-header-container" style="text-align: center; height: 49px; line-height: 49px;">

        {{selectChatUser.userName}} (服务号)

    </div>
    <div class="chat-core-container" id="chatContainer" style="background-color: white; height: 660px; text-align: center; padding-top: 20px;">
        <div class="message-card-item" v-for="messageCard in messageCardArr" @click="viewArticle(messageCard.messageExt?.redirectUrl)">
            <div class="message-avatar other-avatar">
                    <img :src="selectChatUser.photo" alt="avatar" />
                </div>
            <div class="message-card">
                <div class="message-card-title">
                    <img :src="messageCard.messageExt?.logo" v-if="messageCard.messageExt?.logo" style="width: 20px; height: 20px;">
                    {{messageCard.messageExt?.title}}
                </div>
                <div class="message-card-template" style="background-color: white; padding-top: 15px;" v-html="messageCard.messageExt?.content"></div>
                <div v-if="messageCard.messageExt?.redirectName && messageCard.messageExt?.redirectUrl" class="message-card-redirect">
                    {{ messageCard.messageExt?.redirectName }}
                    <RightOutlined />
                </div>
            </div>

        </div>
        <div id="chatLastElement"></div>
    </div>
  </template>
  
  <script>
  import { useRouter } from 'vue-router';
  import axios from 'axios';
  import { inject, defineComponent, ref, onMounted, onUnmounted, watch } from 'vue';
  export default defineComponent({
    props: {
        selectChatUserRef: Object
    },
    setup(props) {

        const router = useRouter();

        const selectChatUser = ref(props.selectChatUserRef);

        const socket = ref(null);
        const messageQueue = ref([]); // 存储未发送的消息队列
        const isConnected = ref(false);
        const loginUser = ref(inject('loginUser'));
        const reconnectInterval = ref(5000); // 重连间隔时间，单位：毫秒
        const heartbeatInterval = ref(30000); // 心跳间隔时间，单位：毫秒
        const messageCardArr = ref([]);

        const loadChatMessages = (chatUserId) => {
            // 先清空
            axios.get(`/client-service/chat/message/list/`+chatUserId, {})
            .then(function (response) {
                if (response.data.code === 40001) {
                    // 未登录
                    window.location.href = response.data.redirect_url;
                } else if (response.data.code === 200) {
                    if (response.data.data.length > 0) {
                        messageCardArr.value = response.data.data;
                    }
                }
                scrollToBottom();
            }).catch(function (error) {
                // 处理错误
                console.error(error);
            });
        }
        loadChatMessages( selectChatUser.value.userId);

        const redirect = (redirectUrl) => {
            


        }

        const connectWebSocket = () => {
            socket.value = new WebSocket(`/connect-service/ws/chat/PC_WEB_CHAT/` + loginUser.value.userId);
            socket.value.onopen = () => {
                console.log('WebSocket 已连接');
                isConnected.value = true;
                // 发送队列中的消息
                messageQueue.value.forEach(message => socket.value.send(message));
                messageQueue.value = [];
                startHeartbeat();
            };

            socket.value.onmessage = (event) => {
                console.log('收到WS消息:', event.data);
                // 在此处理收到的消息
                const socketMessage = JSON.parse(event.data);
                if(socketMessage.senderId != selectChatUser.value.userId) {
                    return;
                }
                const messageType = socketMessage.type;
                if (messageType === 11) {
                    // 处理对话
                    messageCardArr.value.push(socketMessage);
                }
                scrollToBottom();
            };

            socket.value.onerror = (error) => {
                console.error('WebSocket 错误:', error);
                isConnected.value = false;
                // 关闭当前连接
                socket.value.close();
                // 尝试重连
                setTimeout(connectWebSocket, reconnectInterval.value);
            };

            socket.value.onclose = () => {
                console.log('WebSocket 已关闭');
                isConnected.value = false;
                // 尝试重连
                setTimeout(connectWebSocket, reconnectInterval.value);
            };
        };

        const startHeartbeat = () => {
            const heartbeat = () => {
                if (isConnected.value) {
                socket.value.send('ping'); // 发送心跳包
                }
            };
            setInterval(heartbeat, heartbeatInterval.value);
        };
        // 链接ws
        connectWebSocket();

        const sendMessage = (message) => {
            if (isConnected.value) {
                socket.value.send(message);
            } else {
                messageQueue.value.push(message);
            }
            scrollToBottom();
        };

        // 切换对话用户，父组件传递选中用户信息，监听选中用户变化
        watch(() => props.selectChatUserRef, (newValue) => {
          selectChatUser.value = newValue;
        });

            // 定义滚动到底部函数
    function scrollToBottom() {
        const container = document.getElementById("chatContainer"); // 获取滚动容器
        const lastChild = document.getElementById("chatLastElement");
        if (container && lastChild) {
            // 计算子元素在容器内的相对位置
            const scrollPosition = lastChild.offsetTop - container.offsetTop;
            container.scrollTop = scrollPosition; // 直接设置滚动位置
            // 平滑滚动（可选）
            container.scrollTo({ top: scrollPosition, behavior: 'smooth' });
        }
    }

        onMounted(() => {
            
        });
        onUnmounted(() => {
        
        });
        
        return {
            selectChatUser,
            isConnected,
            messageQueue,
            loginUser,
            reconnectInterval,
            heartbeatInterval,
            messageCardArr,
            scrollToBottom,
            connectWebSocket,
            sendMessage,
            startHeartbeat,
            loadChatMessages,
            redirect
        };
    }
  });
  </script>
  
  <style scoped>
  .message-card-item {
    margin-bottom: 30px;
  }
  .message-card {
        position: relative;
        margin-left: 50px;
        width: 310px;
        height: auto;
        padding: 0px 20px;
        background-color: white;
        border: 1px solid #e5e5e5;   
        border-radius: 8px;    
        background: linear-gradient(180deg, #fbf8f7 0%, #ffffff 50%);
  }
  .message-card-title {
    position: relative;
    width: 100%;
    height: 50px;
    line-height: 50px;
    text-align: left;
  }
  .message-card-redirect {
    position: relative;
    width: 100%;
    height: 50px;
    font-size: 13px;
    line-height: 50px;
    text-align: left;
    margin-top: 15px;
    border-top: 1px solid #e5e5e5;   
  }
  .chat-core-container::-webkit-scrollbar {/*滚动条整体样式*/
        width: 0px;     /*高宽分别对应横竖滚动条的尺寸*/
        height: 0px;
    }
    .chat-core-container::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
        border-radius: 10px;
        background-color: transparent;
        background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%, transparent 75%, transparent);
    }
    .chat-core-container::-webkit-scrollbar-track {/*滚动条里面轨道*/
        -webkit-box-shadow: inset 0 0 1px rgba(0,0,0,0.2);
        /*border-radius: 10px;*/
        background: #EDEDED;
    }
    .message-card-item {
        position: relative;
        width: 370px;
        height: auto;
    }
    .message-avatar {
        position: absolute;
        top: 0px;
        left: 0px;
    }
    .message-avatar img {
        width: 35px;
        height: 35px;
        border-radius: 5px;
    }
  </style>