<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>智能问答助手</h2>
      <p class="chat-hint">您可以询问任何关于心理健康、治疗方法或医学知识的问题</p>
    </div>
    
    <div class="chat-body" ref="chatBody">
      <div v-if="!messages.length" class="empty-chat">
        <el-empty description="开始您的对话吧！" />
        <div class="example-questions">
          <h4>示例问题：</h4>
          <div class="question-list">
            <div class="question-item" @click="askQuestion('什么是焦虑症？')">什么是焦虑症？</div>
            <div class="question-item" @click="askQuestion('如何帮助抑郁症患者？')">如何帮助抑郁症患者？</div>
            <div class="question-item" @click="askQuestion('认知行为疗法有什么作用？')">认知行为疗法有什么作用？</div>
            <div class="question-item" @click="askQuestion('如何改善睡眠质量？')">如何改善睡眠质量？</div>
          </div>
        </div>
      </div>
      
      <div v-else class="message-list">
        <div v-for="(message, index) in messages" :key="index"
             :class="['message-item', message.messageType === 'user' ? 'user-message' : 'ai-message']">
          <div class="message-avatar">
            <el-avatar :icon="message.messageType === 'user' ? UserFilled : Service" 
                      :size="36" 
                      :class="message.messageType === 'user' ? 'user-avatar' : 'ai-avatar'" />
          </div>
          <div class="message-content">
            <div class="message-text" v-html="formatMessage(message.content)"></div>
            <div class="message-time">{{ formatTime(message.createTime) }}</div>
          </div>
        </div>
      </div>
      
      <div v-if="loading" class="ai-typing">
        <div class="typing-indicator">
          <span></span>
          <span></span>
          <span></span>
        </div>
      </div>
    </div>
    
    <div class="chat-footer">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="2"
        placeholder="请输入您的问题..."
        resize="none"
        @keydown.enter.prevent="sendMessage"
      />
      <el-button type="primary" :disabled="!inputMessage.trim() || loading" @click="sendMessage">
        <el-icon><Position /></el-icon>发送
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue';
import { UserFilled, Service, Position } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import request from '@/utils/request';

// 消息列表
const messages = reactive([]);
// 输入消息
const inputMessage = ref('');
// 加载状态
const loading = ref(false);
// 聊天容器引用
const chatBody = ref(null);

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value) return;
  
  const userMessage = {
    content: inputMessage.value,
    messageType: 'user',
    createTime: new Date()
  };
  
  // 添加用户消息
  messages.push(userMessage);
  
  // 清空输入框
  const tempMessage = inputMessage.value;
  inputMessage.value = '';
  
  // 滚动到底部
  await scrollToBottom();
  
  // 显示加载状态
  loading.value = true;
  
  try {
    console.log('发送消息到后端:', tempMessage);
    
    // 调用后端API
    const res = await request.post('/aiChat/sendMessage', {
      message: tempMessage
    });
    
    console.log('收到后端响应:', res);
    
    if (res.code === '200') {
      // 检查响应数据结构
      if (res.data && res.data.aiMessage && res.data.aiMessage.content) {
        // 添加AI回复
        messages.push({
          content: res.data.aiMessage.content,
          messageType: 'ai',
          createTime: new Date()
        });
      } else {
        console.error('响应格式不正确:', res);
        messages.push({
          content: '抱歉，系统返回了不正确的格式。请稍后再试。',
          messageType: 'ai',
          createTime: new Date()
        });
      }
    } else {
      // 显示具体错误信息
      const errorMsg = res.msg || '消息发送失败';
      console.error('API错误:', errorMsg);
      ElMessage.error(errorMsg);
      
      // 添加错误消息
      messages.push({
        content: `抱歉，我遇到了一点问题: ${errorMsg}`,
        messageType: 'ai',
        createTime: new Date()
      });
    }
  } catch (error) {
    console.error('发送消息失败', error);
    
    // 提取更详细的错误信息
    let errorMsg = '网络错误，请稍后再试';
    if (error.response) {
      console.error('错误响应:', error.response);
      if (error.response.data) {
        errorMsg = `错误: ${error.response.data.msg || JSON.stringify(error.response.data)}`;
      } else {
        errorMsg = `错误状态码: ${error.response.status}`;
      }
    } else if (error.message) {
      errorMsg = `错误: ${error.message}`;
    }
    
    ElMessage.error(errorMsg);
    
    // 添加错误消息
    messages.push({
      content: '抱歉，我遇到了问题: ' + errorMsg,
      messageType: 'ai',
      createTime: new Date()
    });
  } finally {
    loading.value = false;
    // 滚动到底部
    await scrollToBottom();
  }
};

// 预设问题
const askQuestion = (question) => {
  inputMessage.value = question;
  sendMessage();
};

// 格式化消息内容（支持简单的Markdown）
const formatMessage = (content) => {
  if (!content) return '';
  
  // 替换换行符为<br>
  let formatted = content.replace(/\n/g, '<br>');
  
  // 处理加粗
  formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
  
  // 处理斜体
  formatted = formatted.replace(/\*(.*?)\*/g, '<em>$1</em>');
  
  // 处理链接
  formatted = formatted.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>');
  
  return formatted;
};

// 格式化时间
const formatTime = (dateString) => {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  
  return `${hours}:${minutes}`;
};

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (chatBody.value) {
    chatBody.value.scrollTop = chatBody.value.scrollHeight;
  }
};

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  scrollToBottom();
});

onMounted(() => {
  // 初始化时滚动到底部
  scrollToBottom();
});
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px);
  background-color: #f5f7fa;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chat-header {
  padding: 16px 20px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.chat-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.chat-hint {
  margin: 5px 0 0;
  font-size: 12px;
  color: #909399;
}

.chat-body {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.empty-chat {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.example-questions {
  margin-top: 30px;
  width: 100%;
  max-width: 600px;
}

.example-questions h4 {
  margin-bottom: 12px;
  text-align: center;
  color: #606266;
}

.question-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 12px;
}

.question-item {
  padding: 10px 15px;
  background-color: #ecf5ff;
  color: #409eff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.question-item:hover {
  background-color: #409eff;
  color: #fff;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message-item {
  display: flex;
  max-width: 80%;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.ai-message {
  align-self: flex-start;
}

.message-avatar {
  flex-shrink: 0;
  margin: 0 10px;
}

.user-avatar {
  background-color: #409eff;
}

.ai-avatar {
  background-color: #67c23a;
}

.message-content {
  padding: 12px 16px;
  border-radius: 8px;
  position: relative;
}

.user-message .message-content {
  background-color: #409eff;
  color: #fff;
  border-top-right-radius: 0;
}

.ai-message .message-content {
  background-color: #fff;
  color: #303133;
  border-top-left-radius: 0;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.message-text {
  line-height: 1.5;
  word-break: break-word;
}

.message-time {
  font-size: 10px;
  margin-top: 5px;
  text-align: right;
  opacity: 0.8;
}

.ai-typing {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

.typing-indicator {
  display: flex;
  padding: 12px 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  margin: 0 2px;
  background-color: #a3a3a3;
  border-radius: 50%;
  display: inline-block;
  animation: typing 1.4s infinite ease-in-out both;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.6);
    opacity: 0.6;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-footer {
  display: flex;
  align-items: flex-end;
  gap: 10px;
  padding: 16px 20px;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
}

.chat-footer .el-input {
  flex: 1;
}

.chat-footer .el-button {
  margin-left: 10px;
  height: 50px;
}
</style> 