<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="decision-board" v-loading="decisionLoading">
      <el-row :gutter="16" class="decision-metrics">
        <el-col :span="6">
          <div class="decision-card">
            <div class="decision-label">安全库存阈值</div>
            <div class="decision-value">{{ safetyStockThreshold.days }}天</div>
            <div class="decision-sub">覆盖天数下限，单品不少于 {{ safetyStockThreshold.minQty }} 件</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="decision-card">
            <div class="decision-label">补货建议</div>
            <div class="decision-value">{{ replenishSuggestions.length }}</div>
            <div class="decision-sub">低库存或覆盖不足SKU</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="decision-card">
            <div class="decision-label">清仓建议</div>
            <div class="decision-value">{{ clearanceSuggestions.length }}</div>
            <div class="decision-sub">滞销、超储或低周转SKU</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="decision-card">
            <div class="decision-label">库存健康报告</div>
            <div class="decision-value" :class="healthReport.type">{{ healthReport.text }}</div>
            <div class="decision-sub">综合风险与周转表现</div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="16" class="decision-sections">
        <el-col :span="12">
          <div class="decision-panel">
            <div class="panel-title">补货建议</div>
            <div v-if="replenishSuggestions.length" class="suggestion-list">
              <div v-for="item in replenishSuggestions" :key="item.productCode || item.sku" class="suggestion-item">
                <div>
                  <div class="suggestion-title">{{ item.productName || item.productCode || item.sku }}</div>
                  <div class="suggestion-desc">现有库存 {{ formatInteger(item.inventory) }} 件，建议补至 {{ formatInteger(item.suggestQty) }} 件</div>
                </div>
                <el-tag type="danger" size="mini">补货</el-tag>
              </div>
            </div>
            <el-empty v-else description="暂无补货建议" :image-size="80" />
          </div>
        </el-col>
        <el-col :span="12">
          <div class="decision-panel">
            <div class="panel-title">清仓建议</div>
            <div v-if="clearanceSuggestions.length" class="suggestion-list">
              <div v-for="item in clearanceSuggestions" :key="item.productCode || item.sku" class="suggestion-item">
                <div>
                  <div class="suggestion-title">{{ item.productName || item.productCode || item.sku }}</div>
                  <div class="suggestion-desc">库存 {{ formatInteger(item.inventory) }} 件，周转率 {{ formatDecimal(item.turnoverRate) }} 次</div>
                </div>
                <el-tag type="warning" size="mini">清仓</el-tag>
              </div>
            </div>
            <el-empty v-else description="暂无清仓建议" :image-size="80" />
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="16" class="decision-sections">
        <el-col :span="12">
          <div class="decision-panel">
            <div class="panel-title">库存健康报告</div>
            <div class="health-summary">
              <div class="health-line"><span>高风险SKU</span><b>{{ riskStats.critical }}</b></div>
              <div class="health-line"><span>中风险SKU</span><b>{{ riskStats.warning }}</b></div>
              <div class="health-line"><span>低风险SKU</span><b>{{ riskStats.info }}</b></div>
              <div class="health-line"><span>健康SKU</span><b>{{ riskStats.safe }}</b></div>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="decision-panel">
            <div class="panel-title">库存周转分析</div>
            <div v-if="turnoverAnalysis.length" class="turnover-list">
              <div v-for="item in turnoverAnalysis" :key="item.sku || item.productCode" class="turnover-item">
                <span>{{ item.productName || item.sku || item.productCode }}</span>
                <b>{{ formatDecimal(item.turnoverRate) }} 次</b>
              </div>
            </div>
            <el-empty v-else description="暂无周转数据" :image-size="80" />
          </div>
        </el-col>
      </el-row>
    </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,
      decisionLoading: false,
      riskStats: {
        critical: 0,
        warning: 0,
        info: 0,
        safe: 0
      },
      riskRows: [],
      skuRows: [],
      safetyStockThreshold: {
        days: 15,
        minQty: 30
      },
      chatMessages: DEFAULT_MESSAGES.map(item => ({ ...item }))
    }
  },
  computed: {
    replenishSuggestions() {
      const fromRisk = this.riskRows
        .filter(item => item.riskType === 'stockout' || item.riskLevel === 'critical')
        .slice(0, 5)
        .map(item => ({
          ...item,
          inventory: this.getInventory(item),
          suggestQty: Math.max(this.getInventory(item), Math.ceil(Number(item.avgDailySales || 0) * this.safetyStockThreshold.days), this.safetyStockThreshold.minQty)
        }))
      if (fromRisk.length) return fromRisk
      return this.skuRows
        .filter(item => this.getInventory(item) < this.safetyStockThreshold.minQty)
        .slice(0, 5)
        .map(item => ({
          ...item,
          inventory: this.getInventory(item),
          suggestQty: this.safetyStockThreshold.minQty
        }))
    },
    clearanceSuggestions() {
      const fromRisk = this.riskRows
        .filter(item => item.riskType === 'overstock' || item.riskType === 'slow-moving' || Number(item.turnoverRate || 0) < 0.8)
        .slice(0, 5)
        .map(item => ({ ...item, inventory: this.getInventory(item) }))
      if (fromRisk.length) return fromRisk
      return this.skuRows
        .filter(item => this.getInventory(item) > 0 && Number(item.turnoverRate || 0) < 0.8)
        .slice(0, 5)
        .map(item => ({ ...item, inventory: this.getInventory(item) }))
    },
    healthReport() {
      if (this.riskStats.critical > 0) return { text: '高风险', type: 'danger' }
      if (this.riskStats.warning > 0) return { text: '需关注', type: 'warning' }
      return { text: '健康', type: 'success' }
    },
    turnoverAnalysis() {
      const source = this.skuRows.length ? this.skuRows : this.riskRows
      return [...source]
        .filter(item => item.turnoverRate !== undefined && item.turnoverRate !== null)
        .sort((a, b) => Number(a.turnoverRate || 0) - Number(b.turnoverRate || 0))
        .slice(0, 6)
    }
  },
  mounted() {
    this.loadDecisionData()
  },
  methods: {
    normalizeResponse(res) {
      if (!res) return null
      if (res.code === 200) return res.data
      if (res.data) return res.data
      return null
    },
    async loadDecisionData() {
      this.decisionLoading = true
      try {
        await Promise.all([
          this.fetchRiskStats(),
          this.fetchRiskRows(),
          this.fetchSkuRows()
        ])
      } finally {
        this.decisionLoading = false
      }
    },
    async fetchRiskStats() {
      try {
        const res = await request({ url: '/api/risk/statistics', method: 'get' })
        const data = this.normalizeResponse(res)
        if (data) this.riskStats = { ...this.riskStats, ...data }
      } catch (e) {
        console.error('获取风险统计失败:', e)
      }
    },
    async fetchRiskRows() {
      try {
        const res = await request({
          url: '/api/risk/list',
          method: 'get',
          params: { page: 1, pageSize: 50 }
        })
        const data = this.normalizeResponse(res)
        if (data && Array.isArray(data.list)) this.riskRows = data.list
        else if (data && Array.isArray(data.rows)) this.riskRows = data.rows
        else this.riskRows = Array.isArray(data) ? data : []
      } catch (e) {
        console.error('获取风险列表失败:', e)
      }
    },
    async fetchSkuRows() {
      try {
        const res = await request({ url: '/api/inventory/sku-summary', method: 'get', timeout: 120000 })
        const data = this.normalizeResponse(res)
        this.skuRows = Array.isArray(data) ? data : []
      } catch (e) {
        console.error('获取SKU汇总失败:', e)
      }
    },
    getInventory(item) {
      return Number(item.inventory || item.currentInventory || item.remainingInventory || item.quantity || 0)
    },
    formatInteger(value) {
      return Number(value || 0).toLocaleString()
    },
    formatDecimal(value) {
      return Number(value || 0).toFixed(2)
    },
    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.loadDecisionData()
      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: 1180px;
  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;
}

.decision-board {
  background: #ffffff;
  border-bottom: 1px solid #e5e7eb;
  padding: 16px 20px 20px;
}

.decision-metrics,
.decision-sections {
  margin-bottom: 16px;
}

.decision-sections:last-child {
  margin-bottom: 0;
}

.decision-card,
.decision-panel {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background: #fff;
}

.decision-card {
  min-height: 118px;
  padding: 16px;
}

.decision-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 10px;
}

.decision-value {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1.1;
}

.decision-value.success {
  color: #67c23a;
}

.decision-value.warning {
  color: #e6a23c;
}

.decision-value.danger {
  color: #f56c6c;
}

.decision-sub {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}

.decision-panel {
  min-height: 220px;
  padding: 16px;
}

.panel-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

.suggestion-list,
.turnover-list,
.health-summary {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.suggestion-item,
.turnover-item,
.health-line {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 10px 12px;
  background: #f7f8fa;
  border-radius: 6px;
}

.suggestion-title {
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.suggestion-desc {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

.turnover-item span,
.health-line span {
  color: #606266;
  font-size: 13px;
}

.turnover-item b,
.health-line b {
  color: #303133;
  font-size: 14px;
}

/* 对话容器 */
.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>
