<template>
    <div class="chat-dialog" v-if="visible">
      <div class="chat-header">
        <span>AI 聊天助手</span>
        <button @click="closeDialog">关闭</button>
      </div>
      <div class="chat-body" ref="chatBody">
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message', message.role]"
        >
          {{ message.content }}
        </div>
        <div v-if="isLoading" class="message assistant">正在思考...</div>
      </div>
      <div class="chat-footer">
        <input
          v-model="inputMessage"
          @keyup.enter="sendMessage"
          placeholder="输入消息..."
          :disabled="isLoading"
        />
        <button @click="sendMessage" :disabled="isLoading">发送</button>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, nextTick } from 'vue';
  
  // 定义 props
  const props = defineProps({
    visible: Boolean
  });
  
  // 定义 emits
  const emit = defineEmits(['update:visible']);
  
  // 数据状态
  const messages = ref([
    { role: 'assistant', content: '你好！我是 AI 助手，如何帮你？' }
  ]);
  const inputMessage = ref('');
  const isLoading = ref(false);
  const chatBody = ref(null);
  
  // 关闭对话框
  const closeDialog = () => {
    emit('update:visible', false);
  };
  
  // 发送消息并获取 AI 回复
  const sendMessage = async () => {
    if (!inputMessage.value.trim() || isLoading.value) return;
  
    // 添加用户消息
    messages.value.push({ role: 'user', content: inputMessage.value });
    isLoading.value = true;
  
    // 模拟或调用 AI API
    const response = await getAIResponse(inputMessage.value);
    messages.value.push({ role: 'assistant', content: response });
  
    // 清空输入并滚动到底部
    inputMessage.value = '';
    isLoading.value = false;
    await nextTick();
    chatBody.value.scrollTop = chatBody.value.scrollHeight;
  };
  
  // 获取 AI 回复（模拟或真实 API）
  const getAIResponse = async (message) => {
    try {
      // 示例：调用 OpenAI API（需替换为真实后端接口）
      const res = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer YOUR_OPENAI_API_KEY' // 替换为你的 API 密钥
        },
        body: JSON.stringify({
          model: 'gpt-3.5-turbo',
          messages: [{ role: 'user', content: message }],
          max_tokens: 150
        })
      });
      const data = await res.json();
      return data.choices[0].message.content;
    } catch (error) {
      console.error('AI 请求失败:', error);
      return '抱歉，出了点问题，请稍后再试！';
    }
  };
  </script>
  
  <style scoped>
  .chat-dialog {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 400px;
    height: 500px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    display: flex;
    flex-direction: column;
  }
  .chat-header {
    padding: 10px 15px;
    background: #f7f7f7;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
  }
  .chat-body {
    flex: 1;
    padding: 15px;
    overflow-y: auto;
    background: #fafafa;
  }
  .message {
    margin: 10px 0;
    padding: 10px 15px;
    border-radius: 5px;
    max-width: 80%;
    word-wrap: break-word;
  }
  .message.user {
    background: #007bff;
    color: white;
    margin-left: auto;
  }
  .message.assistant {
    background: #e0e0e0;
    color: #333;
    margin-right: auto;
  }
  .chat-footer {
    padding: 10px;
    border-top: 1px solid #e0e0e0;
    display: flex;
    gap: 10px;
  }
  input {
    flex: 1;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    outline: none;
  }
  input:disabled {
    background: #f0f0f0;
  }
  button {
    padding: 8px 15px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }
  button:disabled {
    background: #ccc;
    cursor: not-allowed;
  }
  button:hover:not(:disabled) {
    background: #0056b3;
  }
  </style>