<template>
  <view class="container">
    <!-- 聊天记录展示 -->
    <scroll-view scroll-y class="chat-list" :style="{ height: chatHeight + 'px' }">
      <view v-for="(msg, index) in messages" :key="index" class="message-item">
        <view :class="msg.isUser ? 'message-user' : 'message-other'">
          {{ msg.text }}
        </view>
      </view>
    </scroll-view>

    <!-- 输入框和发送按钮 -->
    <view class="input-area">
      <input
          v-model="newMessage"
          class="input-box"
          placeholder="请输入消息"
          @confirm="sendMessage"
      />
      <button class="send-btn" @click="sendMessage">发送</button>
    </view>
  </view>
</template>

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

export default {
  setup() {
    // 响应式数据
    const newMessage = ref(''); // 用户输入的消息
    const messages = reactive([]); // 消息数组
    const chatHeight = ref(0); // 动态调整聊天区域高度

    // 页面加载时加载历史消息
    onMounted(() => {
      loadMessages();
      setChatHeight();
    });

    // 发送消息
    const sendMessage = () => {
      if (newMessage.value.trim() === '') return;

      // 添加用户消息
      messages.push({ text: newMessage.value, isUser: true });
      saveMessages();

      // 模拟对方回复
      setTimeout(() => {
        const response = '这是一条自动回复消息';
        messages.push({ text: response, isUser: false });
        saveMessages();
      }, 1000);

      // 清空输入框
      newMessage.value = '';
    };

    // 加载历史消息
    const loadMessages = () => {
      const savedMessages = uni.getStorageSync('chatMessages');
      if (savedMessages) {
        messages.push(...JSON.parse(savedMessages));
      }
    };

    // 保存消息
    const saveMessages = () => {
      uni.setStorageSync('chatMessages', JSON.stringify(messages));
    };

    // 设置聊天区域高度
    const setChatHeight = () => {
      const systemInfo = uni.getSystemInfoSync();
      chatHeight.value = systemInfo.windowHeight - 150; // 留出底部输入框的位置
    };

    return {
      newMessage,
      messages,
      chatHeight,
      sendMessage
    };
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.chat-list {
  flex: 1;
  padding: 10px;
  background-color: #f0f0f0;
}

.message-item {
  margin-bottom: 10px;
}

.message-user {
  background-color: #007aff;
  color: white;
  padding: 10px;
  border-radius: 10px;
  text-align: right;
}

.message-other {
  background-color: #e5e5e5;
  color: black;
  padding: 10px;
  border-radius: 10px;
}

.input-area {
  display: flex;
  padding: 10px;
  background-color: #fff;
  align-items: center;
}

.input-box {
  flex: 1;
  height: 40px;
  padding: 0 10px;
  border-radius: 20px;
  border: 1px solid #ddd;
}

.send-btn {
  background-color: #007aff;
  color: white;
  padding: 10px 20px;
  border-radius: 20px;
  margin-left: 10px;
}
</style>
