<template>
  <div id="app">
    <!-- 顶部标题栏，新增刷新按钮 -->
    <div class="chat-header">
      <div class="header-title">
        <span class="bot-icon">AI</span>
        <span>智能助手</span>
      </div>
      <button class="refresh-btn" @click="refreshChat" :disabled="loading">
        <span class="refresh-icon">↻</span>
      </button>
    </div>

    <div class="chat-container">
      <div class="chatbox" ref="chatbox">
        <div class="message" v-for="(msg, index) in chatMessages" :key="index">
          <!-- 用户消息（右对齐） -->
          <div class="user-message" v-if="msg.type === 'user'">
            <div class="text">{{ msg.text }}</div>
            <div class="avatar user-avatar">你</div>
          </div>
          <!-- 机器人消息（左对齐） -->
          <div class="bot-message" v-if="msg.type === 'bot'">
            <div class="avatar bot-avatar">AI</div>
            <div class="text">
              <span v-if="msg.loading">思考中...</span>
              <span v-else>{{ msg.text }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="input-group">
        <input
          type="text"
          v-model="userInput"
          @keyup.enter="sendMessage"
          :disabled="loading"
          placeholder="请输入问题，例如：SKU PRD-001 库存风险如何？"
        />
        <button @click="sendMessage" :disabled="loading || !userInput.trim()">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'

const DEFAULT_MESSAGES = [
  {
    type: 'bot',
    text: '你好！我是你的智能助手，有什么可以帮到你的吗？'
  },
  {
    type: 'bot',
    text: '你可以输入产品SKU来查询对应单品的库存、销量和周转情况。'
  }
]

export default {
  data() {
    return {
      userInput: '',
      loading: false,
      chatMessages: DEFAULT_MESSAGES.map(item => ({ ...item }))
    }
  },
  methods: {
    async sendMessage() {
      const content = this.userInput.trim()
      if (!content || this.loading) return

      const history = this.buildHistory()
      const sku = this.extractSku(content)

      this.chatMessages.push({
        type: 'user',
        text: content
      })

      const botMessage = {
        type: 'bot',
        text: '',
        loading: true
      }
      this.chatMessages.push(botMessage)

      this.userInput = ''
      this.loading = true
      this.scrollToBottom()

      try {
        const res = await request({
          url: '/api/agent/chat',
          method: 'post',
          timeout: 35000,
          data: {
            message: content,
            history,
            sku
          }
        })
        const reply = res && res.data && res.data.reply ? res.data.reply : '未收到有效回复，请稍后再试。'
        botMessage.text = reply
      } catch (e) {
        botMessage.text = '调用后端失败，请稍后再试。'
      } finally {
        botMessage.loading = false
        this.loading = false
        this.scrollToBottom()
      }
    },

    buildHistory() {
      return this.chatMessages
        .filter(item => item && !item.loading && item.text)
        .slice(-6)
        .map(item => ({
          role: item.type === 'user' ? 'user' : 'assistant',
          content: item.text
        }))
    },

    extractSku(text) {
      if (!text) return ''
      const match = text.match(/(?:sku|SKU)[:：]?\s*([A-Za-z0-9_-]{3,})/)
      return match && match[1] ? match[1] : ''
    },

    refreshChat() {
      this.chatMessages = DEFAULT_MESSAGES.map(item => ({ ...item }))
      this.userInput = ''
      this.loading = false
      this.$nextTick(() => {
        const chatbox = this.$refs.chatbox
        if (chatbox) {
          chatbox.scrollTop = 0
        }
      })
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const chatbox = this.$refs.chatbox
        if (chatbox) {
          chatbox.scrollTop = chatbox.scrollHeight
        }
      })
    }
  }
}
</script>

<style scoped>
#app {
  font-family: "Microsoft YaHei", "PingFang SC", sans-serif;
  background-color: #f7f8fa;
  color: #333;
  margin: 0;
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

/* 顶部标题栏 */
.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: #fff;
  border-radius: 8px 8px 0 0;
  border-bottom: 1px solid #e5e7eb;
  margin-bottom: 0;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.bot-icon {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #409eff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.refresh-btn {
  background: transparent;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #909399;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s;
}

.refresh-btn:hover {
  background: #f5f7fa;
  color: #409eff;
}

.refresh-btn:disabled {
  cursor: not-allowed;
  color: #c0c4cc;
  background: transparent;
}

/* 对话容器 */
.chat-container {
  background: #ffffff;
  border-radius: 0 0 8px 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.chatbox {
  height: 450px;
  overflow-y: auto;
  padding: 20px;
  background: #fafbfc;
}

/* 滚动条美化 */
.chatbox::-webkit-scrollbar {
  width: 6px;
}

.chatbox::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.chatbox::-webkit-scrollbar-track {
  background: #f5f7fa;
}

.message {
  display: flex;
  margin: 16px 0;
  align-items: flex-start;
}

/* 用户消息样式 */
.user-message {
  margin-left: auto;
  display: flex;
  align-items: flex-end;
  gap: 8px;
}

.user-message .text {
  background: #409eff;
  color: #fff;
  padding: 10px 14px;
  border-radius: 14px 14px 0 14px;
  max-width: 70%;
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #67c23a;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

/* 机器人消息样式 */
.bot-message {
  margin-right: auto;
  display: flex;
  align-items: flex-end;
  gap: 8px;
}

.bot-message .text {
  background: #fff;
  color: #303133;
  padding: 10px 14px;
  border-radius: 14px 14px 14px 0;
  max-width: 70%;
  font-size: 14px;
  line-height: 1.5;
  border: 1px solid #ebeef5;
  white-space: pre-wrap;
}

.bot-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #409eff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

/* 输入区域 */
.input-group {
  display: flex;
  padding: 16px 20px;
  border-top: 1px solid #e5e7eb;
  background: #fff;
}

input[type="text"] {
  flex: 1;
  padding: 10px 14px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  margin-right: 12px;
  outline: none;
  transition: border-color 0.3s;
}

input[type="text"]:focus {
  border-color: #409eff;
}

input[type="text"]:disabled {
  background: #f5f7fa;
  color: #c0c4cc;
}

button {
  padding: 0 18px;
  border: none;
  background-color: #409eff;
  color: white;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #337ecc;
}

button:disabled {
  cursor: not-allowed;
  background-color: #a0cfff;
}
</style>
