<template>
  <div class="chat-container">
    <div class="chat-box" ref="chatBox">
      <!-- 消息列表 -->
      <div v-for="(message, index) in messages" :key="index" :class="[
          'chat-message',
          message.isUser ? 'user-message' : 'incoming-message',
        ]">
        <!-- 用户消息头部 -->
        <div class="header-user" v-if="message.isUser">
          <div class="avatar-wrapper user-avatar">
            <img src="@/assets/logo/logo.png" alt="用户头像" class="avatar" />
          </div>
          <div class="user-name">用户</div>
        </div>

        <!-- 系统消息头部 -->
        <div class="header" v-else>
          <div class="avatar-wrapper">
            <img src="@/assets/logo/logo.png" alt="系统头像" class="avatar" />
          </div>
          <div class="user-name">系统</div>
        </div>

        <!-- 普通文本消息内容 -->
        <div class="message-content">
          <div class="message-text">
            <span>{{ message.displayedText }}</span>
          </div>
          <div v-if="message.time" class="message-time">{{ message.time }}</div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-box">
      <input
        type="text"
        v-model="inputMessage"
        @keyup.enter="sendMessage"
        placeholder="输入您的消息..."
        :disabled="loading"
      />
      <el-button @click="sendMessage" :disabled="loading" class="send-btn">
        <i class="el-icon-s-promotion"></i>发送
      </el-button>
    </div>
  </div>
</template>

<script>
// 导入接口请求工具
import { aiforData } from "@/api/als/knowledgeExtraction"; // 需自行创建此接口文件

export default {
  name: 'ChatAssistant',
  components: {
    // 保持组件结构一致，如需文件预览等功能可在此导入
  },
  data() {
    return {
      inputMessage: "",       // 输入框内容
      messages: [],           // 消息列表
      loading: false,         // 加载状态
      userId: "admin"         // 用户ID，可根据实际情况从登录信息获取
    };
  },
  methods: {
    /**
     * 发送消息
     */
    sendMessage() {
      // 验证输入内容
      if (this.inputMessage.trim() === "" || this.loading) {
        return;
      }

      const currentTime = this.formatTime(new Date());

      // 添加用户消息到列表
      this.messages.push({
        isUser: true,
        displayedText: this.inputMessage.trim(),
        time: currentTime
      });

      // 清空输入框并滚动到底部
      this.inputMessage = "";
      this.scrollToBottom();

      // 调用接口获取回复
      this.getAssistantReply();
    },

    /**
     * 调用接口获取助手回复
     */
    getAssistantReply() {
      this.loading = true;

      // 构造请求参数
      const params = {
        question: this.messages[this.messages.length - 1].displayedText,
        userId: this.userId
      };

      // 调用聊天接口
      aiforData(params)
        .then(response => {
          // 处理接口返回
          if (response.code === 200 && response.data) {
            this.addSystemMessage(response.data.answer);
          } else {
            this.addSystemMessage("抱歉，未能获取到有效回复，请稍后再试");
          }
        })
        .catch(error => {
          console.error("请求失败:", error);
          this.addSystemMessage("请求失败，请检查网络连接");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /**
     * 添加系统回复消息
     * @param {string} content - 回复内容
     */
    addSystemMessage(content) {
      const currentTime = this.formatTime(new Date());

      this.messages.push({
        isUser: false,
        displayedText: content,
        time: currentTime
      });

      this.scrollToBottom();
    },

    /**
     * 滚动到最新消息位置
     */
    scrollToBottom() {
      this.$nextTick(() => {
        const chatBox = this.$refs.chatBox;
        if (chatBox) {
          chatBox.scrollTop = chatBox.scrollHeight;
        }
      });
    },

    /**
     * 格式化时间显示
     * @param {Date} date - 日期对象
     * @returns {string} 格式化后的时间字符串
     */
    formatTime(date) {
      return date.toLocaleTimeString([], {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    }
  }
};
</script>

<style lang="scss" scoped>
/* 保持原有样式不变，确保视觉一致性 */
.chat-container {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  position: relative;
  font-family: Arial, sans-serif;
}

.chat-box {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  margin-bottom: 100px;
  border-radius: 10px;
}

.chat-message {
  margin-bottom: 20px;
  display: flex;
  max-width: 70%;
  flex-direction: column;
}

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

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

.avatar-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg,
    #f09433,
    #e6683c,
    #dc2743,
    #cc2366,
    #bc1888,
    #e1306c);
  padding: 3px;
  margin-bottom: 5px;
}

.user-avatar {
  align-self: flex-end;
  margin-right: 0;
  margin-top: 5px;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #fff;
}

.message-content {
  background-color: #e0e0e0;
  padding: 12px;
  border-radius: 12px;
  max-width: 100%;
  word-wrap: break-word;
  position: relative;
  margin-top: 5px;
}

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

.message-time {
  font-size: 12px;
  color: #aaa;
  margin-top: 5px;
  text-align: right;
}

.input-box {
  position: fixed;
  bottom: 3%;
  left: 50%;
  transform: translateX(-50%);
  width: 60%;
  display: flex;
  align-items: center;
  padding: 30px;
  height: 100px;
  background-color: #ffffff;
  box-shadow: 0 -2px 15px rgba(0, 0, 0, 0.1);
  border-radius: 30px;
}

input[type="text"] {
  flex: 1;
  padding: 12px;
  font-size: 14px;
  border: none;
  border-radius: 20px;
  margin-right: 10px;
  background-color: #f0f0f0;
}

input[type="text"]:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.send-btn {
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 15%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn:hover:not(:disabled) {
  background-color: #0056b3;
}

.send-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.header, .header-user {
  display: flex;
  align-items: center;

  .user-name {
    margin-left: 10px;
    font-size: 14px;
    color: #313131;
  }
}
</style>
