<template>
  <div class="home">
    <nav-bar/>
    
    <!-- 聊天容器 -->
    <div class="chat-container">
      <!-- 聊天记录区域 -->
      <div class="chat-messages" ref="chatMessages" @click="handleMessageClick">
        <!-- 欢迎消息 - AI的初始回复 -->
        <div class="message ai-message" v-if="messages.length === 0">
          <img src="../assets/yisheng.jpg" alt="AI客服头像" class="avatar ai-avatar">
          <div class="message-content">
            <p>我是宁夏武警总队医院的智能导诊客服，专门为您提供医疗服务和科室推荐。如果您有任何健康问题或症状，请随时告诉我，我会根据您提供的信息推荐合适的科室。</p>
          </div>
        </div>
        
        <!-- 循环展示聊天记录 -->
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message', message.isUser ? 'user-message' : 'ai-message']"
        >
          <img 
            :src="message.isUser ? require('@/assets/huanzhe.jpeg') : require('@/assets/yisheng.jpg')" 
            :alt="message.isUser ? '用户头像' : 'AI客服头像'" 
            class="avatar"
          >
          <div class="message-content">
            <!-- 用户消息直接展示，AI消息通过标记处理 -->
            <p v-if="message.isUser">{{ message.content }}</p>
            <p v-else v-html="formatDepartmentWithTags(message.content)"></p>
          </div>
        </div>
        
        <!-- 加载中状态 -->
        <div class="message ai-message" v-if="isLoading">
          <img src="../assets/yisheng.jpg" alt="AI客服头像" class="avatar ai-avatar">
          <div class="message-content loading">
            <div class="dot"></div>
            <div class="dot"></div>
            <div class="dot"></div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 输入区域 - 固定在底部 -->
    <div class="input-area" >
      <textarea 
        v-model="msg" 
        placeholder="请输入您的健康问题或症状..." 
        @keyup.enter="handleSend"
        :disabled="isLoading"
      ></textarea>
      <button @click="handleSend" :disabled="isLoading || !msg.trim()">
        <i class="icon-send"></i>
      </button>
    </div>
  </div>
</template>

<script>
import { apiGetMessage } from "@/request/api.js";
import { Toast } from 'vant';

export default {
  data() {
    return {
      msg: '',
      messages: [], // 存储聊天记录
      isLoading: false // 加载状态
    };
  },
  mounted() {
    this.scrollToBottom();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    handleResize() {
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    handleSend() {
      const content = this.msg.trim();
      if (!content) return;
      
      this.messages.push({
        content: content,
        isUser: true
      });
      
      this.msg = '';
      this.scrollToBottom();
      this.isLoading = true;
      this.getAiResponse(content);
    },
    
    getAiResponse(userInput) {
      let params = {
        userId: localStorage.getItem("userid") || 'guest',
        msg: userInput
      };
      
      apiGetMessage(params)
        .then(res => {
          try {
            console.log(res.data);
            const firstParse = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
            console.log(firstParse);
            let contentStr = firstParse.choices[0].message.content;
            console.log(contentStr);
            let finalContent = contentStr;
            
            if (typeof contentStr === 'string') {
              const trimmedStr = contentStr.trim();
              if (trimmedStr.startsWith('{') || trimmedStr.startsWith('[')) {
                try {
                  const parsedJson = JSON.parse(contentStr);
                  if (parsedJson.choices && parsedJson.choices[0] && parsedJson.choices[0].message) {
                    finalContent = parsedJson.choices[0].message.content;
                  }
                } catch (e) {
                  console.warn('JSON解析失败，使用原始内容');
                }
              }
            }

            this.isLoading = false;
            this.messages.push({
              content: finalContent,
              isUser: false
            });
            this.scrollToBottom();
          } catch (error) {
            console.error('解析错误:', error);
            this.isLoading = false;
            this.messages.push({
              content: '当前网络错误，请重试',
              isUser: false
            });
            this.scrollToBottom();
          }
        })
        .catch(error => {
          this.isLoading = false;
          this.messages.push({
            content: '当前网络错误，请重试',
            isUser: false
          });
          this.scrollToBottom();
        });
    },
    
    // 核心方法：识别[[科室]]标记，替换为带样式的链接
   formatDepartmentWithTags(content) {
  if (!content) return '';
  console.log("这里",content);
  const regex = /\[\[(.*?)\]\]/g;
  return content.replace(regex, (match, department) => {
    return `<a href="javascript:void(0)" data-route="/xzmz" class="department-link" style="color:#393cfb; text-decoration: underline;cursor: pointer;font-weight: 600; ">  ${department}  </a>`;
  });
},
     handleMessageClick(event) {
    // 检查点击的是否是科室链接
    if (event.target.classList.contains('department-link') && event.target.dataset.route) {
      this.$router.push(event.target.dataset.route);
    }
  },
    // 修改 scrollToBottom 方法
scrollToBottom() {
  this.$nextTick(() => {
    const chatContainer = this.$refs.chatMessages;
    if (chatContainer) {
      // 如果是初始加载且没有消息，滚动到顶部
      if (this.messages.length === 0) {
        chatContainer.scrollTop = 0;
      } else {
        chatContainer.scrollTop = chatContainer.scrollHeight;
      }
    }
  });
}
  }
};
</script>

<style scoped lang="scss">
.home {
  /* 确保页面占满整个视口 */
  min-height: 100vh;
  padding-bottom: 60px; /* 为固定的输入框预留空间 */
  box-sizing: border-box;
  background-color: #f5f5f7;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 60px); /* 减去输入框高度 */
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  padding-bottom: 30px; /* 避免最后一条消息被输入框遮挡 */
  overflow-y: auto;
  scroll-behavior: smooth;
  
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.2);
    border-radius: 3px;
  }
}

.message {
  display: flex;
  margin-bottom: 16px;
  max-width: 100%;
  
  &.user-message {
    flex-direction: row-reverse;
  }
  
  .avatar {
    width: 1rem;
    height: 1rem;
    border-radius: 50%;
    object-fit: cover;
    margin: 0 10px;
    flex-shrink: 0;
  }
  
  .message-content {
    max-width: 70%;
    padding: 10px 15px;
    border-radius: 18px;
    line-height: 1.5;
    word-break: break-word;
    font-size: 0.4rem;
    
    p {
      margin: 0;
    }
    
  }
}

.ai-message .message-content {
  background-color: #ffffff;
  border: 1px solid #e5e5ea;
}

.user-message .message-content {
  background-color: #007aff;
  color: white;
}

/* 输入区域固定在底部 */
.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 10px;
  padding-bottom: calc(10px + env(safe-area-inset-bottom, 0)); /* 适配手机底部安全区 */
  background-color: white;
  border-top: 1px solid #e5e5ea;
  z-index: 10; /* 确保在其他内容上方 */
  box-sizing: border-box;
  
  textarea {
    flex: 1;
    border: 1px solid #e5e5ea;
    border-radius: 20px;
    padding: 10px 15px;
    resize: none;
    outline: none;
    font-size: 0.4rem;
    height: 40px;
    max-height: 120px;
    overflow-y: auto;
    
    &::-webkit-scrollbar {
      width: 4px;
    }
  }
  
  button {
    width: 0.8rem;
    height: 0.8rem;
    border-radius: 50%;
    background-color: #007aff;
    color: white;
    border: none;
    margin-left: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: background-color 0.2s;
    flex-shrink: 0;
    
    &:disabled {
      background-color: #cccccc;
      cursor: not-allowed;
    }
    
    &:not(:disabled):hover {
      background-color: #0066cc;
    }
    
    .icon-send::after {
      content: "→";
      font-size: 0.6rem;
    }
  }
}

// 加载动画保持不变
.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  
  .dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #999;
    animation: bounce 1.4s infinite ease-in-out both;
    
    &:nth-child(1) {
      animation-delay: -0.32s;
    }
    
    &:nth-child(2) {
      animation-delay: -0.16s;
    }
  }
}

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

/* 适配小屏幕设备 */
@media (max-width: 375px) {
  .message-content {
    max-width: 65%; /* 小屏幕适当减少消息宽度 */
  }
  
  .chat-messages {
    padding: 15px 10px;
  }
}
</style>