<template>
    <div class="chat-right-header-container">

      {{selectChatUser.userName}}

    </div>
    <div class="chat-core-container">
        <div v-for="chatMessage in chatMessageArr" 
        :class="['chat-message-card', 
        chatMessage.senderId === loginUser.userId ? 'my-message' : 'other-message']">
            <!-- 自己的消息，头像在右，消息在左 -->
            <template v-if="chatMessage.senderId === loginUser.userId">
                <div class="message-content my-message-content" :style="{ backgroundColor: '#a9ea7a' }">
                    {{ chatMessage.message }}
                </div>
                <div class="message-avatar my-avatar">
                    <img :src="loginUser.photo" alt="avatar" />
                </div>
            </template>
            <!-- 其他人的消息，头像在左，消息在右 -->
            <template v-else>
                <div class="message-avatar other-avatar">
                    <img :src="selectChatUser.photo" alt="avatar" />
                </div>
                <div class="message-content other-message-content" :style="{ backgroundColor: '#f5f5f5' }">
                    {{ chatMessage.message }}
                </div>
            </template>
        </div>
    </div>
    <div class="chat-editer-menu-container">
        <div class="chat-button-group">
            <a-button type="text" @click="handleClick('emoji')">
                <SmileOutlined style="font-size: 20px; color: black;" />
            </a-button>
            <a-button type="text" @click="handleClick('file')">
                <FolderOpenOutlined style="font-size: 20px; color: black;" />
            </a-button>
        </div>
    </div>
    <div class="chat-editer-container">
        <textarea
        ref="inputRef"
        v-model="inputValue"
        placeholder="请输入消息..."
        :auto-focus="true"
        @input="handleInput"
        @keydown="handleSendMessage"
        class="chat-input"
        ></textarea>
    </div>  
  </template>
  
  <script>
  import axios from 'axios';
  import { inject, defineComponent, ref, onMounted, onUnmounted, watch } from 'vue';
  export default defineComponent({
    props: {
        selectChatUserRef: Object
    },
    setup(props) {
        const inputValue = ref('');
        const socket = ref(null);
        const messageQueue = ref([]); // 存储未发送的消息队列
        const isConnected = ref(false);
        const loginUser = ref(inject('loginUser'));
        const selectChatUser = ref(props.selectChatUserRef);
        const reconnectInterval = ref(5000); // 重连间隔时间，单位：毫秒
        const heartbeatInterval = ref(30000); // 心跳间隔时间，单位：毫秒
        const chatMessageArr = ref([]);
        // 切换对话用户，父组件传递选中用户信息，监听选中用户变化
        watch(() => props.selectChatUserRef, (newValue) => {
          selectChatUser.value = newValue;
        });
        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);
                const messageType = socketMessage.type;
                if (messageType === 1) {
                    // 处理对话
                    chatMessageArr.value.push(socketMessage);
                }
            };

            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);
            }
        };

        const handleInput = (event) => {
            inputValue.value = event.target.value;
        };
        const handleSendMessage = () => {
            if (event.key === 'Enter') {
                event.preventDefault(); // 阻止默认的换行行为
                // 消息发送
                console.log("socket ====> " + socket);
                if (inputValue.value.trim() !== '') {
                    const chatMessage = JSON.stringify({
                        senderId: loginUser.value.userId,
                        receiverId: selectChatUser.value.userId,
                        type: 1,
                        time: new Date().getTime(),
                        message: inputValue.value.trim()
                    })
                    // 当前用户自己发送的消息直接提交到页面渲染
                    chatMessageArr.value.push(JSON.parse(chatMessage));
                    // ws发送消息
                    socket.value.send(chatMessage);
                    // 清空输入框
                    inputValue.value = ''; 
                }
            }
        }

        const handleClick = (type) => {
            switch (type) {
                case 'emoji':
                console.log('点击了表情按钮');
                // 在此添加表情按钮的逻辑，例如显示表情选择器等
                break;
                case 'redPacket':
                console.log('点击了红包按钮');
                // 在此添加红包按钮的逻辑，例如打开红包发送界面等
                break;
                case 'audioVideo':
                console.log('点击了音视频按钮');
                // 在此添加音视频按钮的逻辑，例如打开音视频通话界面等
                break;
                case 'file':
                console.log('点击了文件发送按钮');
                // 在此添加文件发送按钮的逻辑，例如打开文件选择器等
                break;
                default:
                break;
            }
        };
      onMounted(() => {
        
      });
      onUnmounted(() => {
       
      });
      
      return {
        inputValue,
        isConnected,
        selectChatUser,
        messageQueue,
        loginUser,
        reconnectInterval,
        heartbeatInterval,
        chatMessageArr,
        handleClick,
        handleSendMessage,
        handleInput,
        connectWebSocket,
      };
    }
  });
  </script>
  
  <style scoped>
    .chat-button-group {
        position: absolute;
        left: 0px;
        top: 0px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 10px;
    }
    .chat-button-group button {
        padding-top: 3px;
        margin-right: 15px;
        height: 30px;
        width: 30px;
        border-radius: 50%;
        background-color: transparent;
    }
    .chat-right-header-container {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 100%;
        height: 50px;
        line-height: 50px;
        padding: 0px 20px;
        border-bottom: 1px solid #e3e3e3;
    }
    .chat-editer-menu-container {
        position: absolute;
        bottom: 150px;
        left: 0px;
        width: 100%;
        height: 50px;
        border-top: 1px solid #e3e3e3;
    }
    .chat-editer-container {
        position: absolute;
        bottom: 0px;
        left: 0px;
        width: 100%;
        height: 150px;
    }
    .chat-core-container {
        position: absolute;
        top: 50px;
        left: 0px;
        width: 100%;
        height: calc(100% - 249px);
        padding: 10px 30px;
        overflow-y: scroll;
        overflow-x: hidden;
    }
    .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;
    }
    .chat-input {
        position: absolute;
        top: 0px;
        left: 0px;
        padding: 20px;
        width: 100%;
        height: 100%;
        line-height: normal;
        font-size: 15px;
        resize: none;
        border: none;
        outline: none;
        box-shadow: none;
    }
    .chat-message-card {
  display: flex;
  margin: 10px 0;
}
.my-message {
  justify-content: flex-end;
}
.other-message {
  justify-content: flex-start;
}
.message-avatar {
  margin-right: 10px;
}
.message-avatar img {
  width: 35px;
  height: 35px;
  border-radius: 5px;
}
.message-content {
  line-height: 35px;
  padding: 0px 10px;
  border-radius: 4px;
  max-width: 70%;
}
.my-avatar {
    float: right;
    margin-left: 10px;
}
/* 自己消息的小三角 */
.my-message-content::before {
    content: "";
    position: absolute;
    top: 10px;
    right: -10px;
    border-width: 5px;
    border-style: solid;
    border-color: transparent transparent transparent #a9ea7a;
}

/* 其他人消息的小三角 */
.other-message-content::before {
    content: "";
    position: absolute;
    top: 10px;
    left: -10px;
    border-width: 5px;
    border-style: solid;
    border-color: transparent #f5f5f5 transparent transparent;
}

  </style>