<template>
    <div class="chat-container">
      <el-card class="chat-card">
        <div class="chat-header">
          <h2>聊天室</h2>
        </div>
        <div class="chat-messages" ref="messagesContainer">
          <div v-for="(message, index) in messages" :key="index" class="chat-message">
            <span class="chat-user">{{ message.user }}:</span>
            <span class="chat-text">{{ message.text }}</span>
          </div>
        </div>
        <div class="chat-input">
          <el-input
            v-model="newMessage"
            placeholder="输入消息..."
            @keyup.enter="sendMessage"
            clearable
          />
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </div>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, nextTick } from 'vue';
  import { ElMessage } from 'element-plus';
  
  const messages = ref([]);
  const newMessage = ref('');
  const messagesContainer = ref(null);
  
  const sendMessage = () => {
    if (newMessage.value.trim() === '') {
      ElMessage.warning('消息不能为空');
      return;
    }
  
    messages.value.push({
      user: '用户',
      text: newMessage.value,
    });
  
    newMessage.value = '';
  
    nextTick(() => {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    });
  };
  
  onMounted(() => {
    // 模拟接收历史消息
    messages.value = [
      { user: '用户1', text: '你好' },
      { user: '用户2', text: '你好，有什么可以帮忙的吗？' },
    ];
  
    nextTick(() => {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    });
  });
  </script>
  
  <style lang="scss" scoped>
  .chat-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f2f5;
  }
  
  .chat-card {
    width: 400px;
    max-height: 600px;
    display: flex;
    flex-direction: column;
  }
  
  .chat-header {
    text-align: center;
    margin-bottom: 10px;
  }
  
  .chat-messages {
    flex-grow: 1;
    overflow-y: auto;
    padding: 10px;
    background-color: #fff;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    margin-bottom: 10px;
  }
  
  .chat-message {
    margin-bottom: 10px;
  }
  
  .chat-user {
    font-weight: bold;
    margin-right: 5px;
  }
  
  .chat-input {
    display: flex;
    align-items: center;
  }
  
  .chat-input .el-input {
    flex-grow: 1;
    margin-right: 10px;
  }
  </style>