<template>
  <div class="risk-warning">
    <el-row :gutter="20" class="risk-overview">
      <el-col :span="6">
        <el-card class="risk-card critical">
          <div class="risk-header">
            <i class="el-icon-warning" style="font-size: 32px; color: #f56c6c;"></i>
            <div class="risk-info">
              <div class="risk-label">高风险</div>
              <div class="risk-count">{{ riskStats.critical }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="risk-card warning">
          <div class="risk-header">
            <i class="el-icon-warning" style="font-size: 32px; color: #e6a23c;"></i>
            <div class="risk-info">
              <div class="risk-label">中风险</div>
              <div class="risk-count">{{ riskStats.warning }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="risk-card info">
          <div class="risk-header">
            <i class="el-icon-info" style="font-size: 32px; color: #409eff;"></i>
            <div class="risk-info">
              <div class="risk-label">低风险</div>
              <div class="risk-count">{{ riskStats.info }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="risk-card safe">
          <div class="risk-header">
            <i class="el-icon-success" style="font-size: 32px; color: #67c23a;"></i>
            <div class="risk-info">
              <div class="risk-label">正常</div>
              <div class="risk-count">{{ riskStats.safe }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="risk-list-card">
      <template slot="header">
        <div class="card-header">
          <span>风险预警列表</span>
          <div class="filter-group">
            <el-select v-model="filterRiskLevel" placeholder="风险等级" size="default" style="width: 120px">
              <el-option label="全部" value="" />
              <el-option label="高风险" value="critical" />
              <el-option label="中风险" value="warning" />
              <el-option label="低风险" value="info" />
            </el-select>
            <el-select v-model="filterRiskType" placeholder="风险类型" size="default" style="width: 140px">
              <el-option label="全部" value="" />
              <el-option label="缺货风险" value="stockout" />
              <el-option label="超储风险" value="overstock" />
              <el-option label="滞销风险" value="slow-moving" />
              <el-option label="周转风险" value="turnover" />
            </el-select>
            <el-button type="primary" @click="handleRefresh">
              <i class="el-icon-refresh"></i> 刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="riskTableData" stripe style="width: 100%" :loading="riskTableLoading">
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="productName" label="产品名称" width="200" />
        <el-table-column prop="productCode" label="产品编码" width="120" />
        <el-table-column label="风险等级" width="120">
          <template slot-scope="scope">
            <el-tag :type="getRiskLevelType(scope.row.riskLevel)" effect="dark">
              {{ getRiskLevelText(scope.row.riskLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="风险类型" width="140">
          <template slot-scope="scope">
            <el-tag :color="getRiskTypeColor(scope.row.riskType)" effect="dark">
              {{ getRiskTypeText(scope.row.riskType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="健康评分" width="150">
          <template slot-scope="scope">
            <el-popover placement="top" trigger="hover" width="260">
              <template slot="reference">
                <div class="health-cell">
                  <span class="health-value">{{ scope.row.healthScore !== undefined ? scope.row.healthScore : '-' }}</span>
                  <el-progress
                    v-if="scope.row.healthScore !== undefined"
                    :percentage="scope.row.healthScore"
                    :stroke-width="6"
                    :color="getHealthColor(scope.row.healthScore)"
                  />
                </div>
              </template>
              <div v-if="scope.row.scoreBreakdown" class="score-breakdown">
                <div class="score-line">
                  <span>覆盖天数</span>
                  <b>{{ scope.row.scoreBreakdown.coverage }}</b>
                </div>
                <div class="score-line">
                  <span>周转贡献</span>
                  <b>{{ scope.row.scoreBreakdown.turnover }}</b>
                </div>
                <div class="score-line">
                  <span>销量趋势</span>
                  <b>{{ scope.row.scoreBreakdown.trend }}</b>
                </div>
                <div class="score-line">
                  <span>资金占比</span>
                  <b>{{ scope.row.scoreBreakdown.capital }}</b>
                </div>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="周转率" width="100">
          <template slot-scope="scope">
            {{ scope.row.turnoverRate !== undefined ? scope.row.turnoverRate.toFixed(2) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="riskScore" label="风险评分" width="100" sortable>
          <template slot-scope="scope">
            <span :style="{ color: getRiskScoreColor(scope.row.riskScore) }">
              {{ scope.row.riskScore }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="覆盖天数" width="110">
          <template slot-scope="scope">
            {{ formatCoverage(scope.row.coverageDays) }}
          </template>
        </el-table-column>
        <el-table-column prop="inventory" label="当前库存" width="110" />
        <el-table-column label="日均销量" width="110">
          <template slot-scope="scope">
            {{ scope.row.avgDailySales !== undefined ? scope.row.avgDailySales.toFixed(1) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="风险描述" min-width="200" />
        <el-table-column prop="suggestion" label="建议措施" min-width="200" />
        <el-table-column prop="detectedTime" label="检测时间" width="180" />
      </el-table>

      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalRisks"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: flex-end;"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </el-card>

    <el-card class="rule-card">
      <template slot="header">
        <div class="card-header">
          <span>智能预警规则配置</span>
          <el-button type="primary" size="small" @click="handleAddRule">
            <i class="el-icon-plus"></i> 添加规则
          </el-button>
        </div>
      </template>

      <el-table :data="warningRules" stripe>
        <el-table-column prop="name" label="规则名称" width="200" />
        <el-table-column prop="condition" label="触发条件" min-width="300" />
        <el-table-column label="风险等级" width="120">
          <template slot-scope="scope">
            <el-tag :type="getRiskLevelType(scope.row.level)">
              {{ getRiskLevelText(scope.row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enabled" @change="handleRuleToggle(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="triggerCount" label="触发次数" width="100" />
      </el-table>
    </el-card>

    <el-card class="feedback-card">
      <template slot="header">
        <div class="card-header">
          <span>系统优化建议与反馈</span>
          <el-tag type="success">智能分析</el-tag>
        </div>
      </template>

      <el-timeline>
        <el-timeline-item
          v-for="(feedback, index) in optimizationFeedback"
          :key="index"
          :timestamp="feedback.time"
          :type="feedback.type"
          placement="top"
        >
          <el-card>
            <h4>{{ feedback.title }}</h4>
            <p class="feedback-content">{{ feedback.content }}</p>
            <div class="feedback-actions">
              <el-tag v-for="tag in feedback.tags" :key="tag" size="small" style="margin-right: 8px">
                {{ tag }}
              </el-tag>
              <el-button type="text" size="small">查看详情</el-button>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'
import { Message, MessageBox } from 'element-ui'

export default {
  name: 'StorageRiskWarning',
  data() {
    return {
      filterRiskLevel: '',
      filterRiskType: '',
      currentPage: 1,
      pageSize: 10,
      riskStats: {
        critical: 0,
        warning: 0,
        info: 0,
        safe: 0
      },
      riskTableData: [],
      totalRisks: 0,
      riskTableLoading: false,
      warningRules: [],
      optimizationFeedback: []
    }
  },
  mounted() {
    this.loadAll()
  },
  watch: {
    filterRiskLevel() {
      this.refreshList()
    },
    filterRiskType() {
      this.refreshList()
    }
  },
  methods: {
    normalizeResponse(res) {
      if (!res) return null
      if (res.code === 200) return res.data
      if (res.data) return res.data
      return null
    },
    async loadAll() {
      await Promise.all([
        this.fetchStats(),
        this.refreshList(),
        this.fetchWarningRules(),
        this.fetchFeedback()
      ])
    },
    async fetchStats() {
      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 refreshList() {
      this.riskTableLoading = true
      try {
        const res = await request({
          url: '/api/risk/list',
          method: 'get',
          params: {
            page: this.currentPage,
            pageSize: this.pageSize,
            riskLevel: this.filterRiskLevel,
            riskType: this.filterRiskType
          }
        })
        const data = this.normalizeResponse(res)
        if (data) {
          this.riskTableData = data.list || data.rows || []
          this.totalRisks = data.total || this.riskTableData.length
        }
      } catch (e) {
        console.error('获取风险列表失败:', e)
      } finally {
        this.riskTableLoading = false
      }
    },
    async fetchWarningRules() {
      try {
        const res = await request({ url: '/api/risk/rules', method: 'get' })
        const data = this.normalizeResponse(res)
        if (Array.isArray(data)) this.warningRules = data
      } catch (e) {
        console.error('获取预警规则失败:', e)
      }
    },
    async fetchFeedback() {
      try {
        const res = await request({ url: '/api/risk/feedback', method: 'get' })
        const data = this.normalizeResponse(res)
        if (Array.isArray(data)) this.optimizationFeedback = data
      } catch (e) {
        console.error('获取反馈失败:', e)
      }
    },
    handleRefresh() {
      this.currentPage = 1
      this.loadAll()
      Message.success('数据已刷新')
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.refreshList()
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.refreshList()
    },
    getRiskLevelType(level) {
      const map = { critical: 'danger', warning: 'warning', info: 'info', safe: 'success' }
      return map[level] || 'info'
    },
    getRiskLevelText(level) {
      const map = { critical: '高风险', warning: '中风险', info: '低风险', safe: '正常' }
      return map[level] || '未知'
    },
    getRiskTypeColor(type) {
      const map = {
        stockout: '#f56c6c',
        overstock: '#e6a23c',
        'slow-moving': '#909399',
        turnover: '#67c23a',
        balanced: '#409eff'
      }
      return map[type] || '#909399'
    },
    getRiskTypeText(type) {
      const map = {
        stockout: '缺货风险',
        overstock: '超储风险',
        'slow-moving': '滞销风险',
        turnover: '周转风险',
        balanced: '均衡'
      }
      return map[type] || '未知'
    },
    getRiskScoreColor(score) {
      if (score >= 80) return '#f56c6c'
      if (score >= 60) return '#e6a23c'
      return '#409eff'
    },
    getHealthColor(score) {
      if (score >= 80) return '#67c23a'
      if (score >= 60) return '#e6a23c'
      return '#f56c6c'
    },
    formatCoverage(value) {
      if (value === undefined || value === null) return '-'
      if (value >= 9000) return '∞'
      return `${Number(value).toFixed(1)} 天`
    },
    handleAddRule() {
      Message.info('添加预警规则')
    },
    handleRuleToggle(row) {
      const status = row.enabled ? '启用' : '禁用'
      Message.success(`规则已${status}`)
    },
    handleDetail(row) {
      Message.info(`查看风险详情: ${row.productCode}`)
    },
    handleResolve(row) {
      MessageBox.confirm('确认已处理该风险?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Message.success('已标记为已处理')
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.risk-warning {
  width: 100%;
}

.risk-overview {
  margin-bottom: 20px;
}

.risk-card {
  cursor: pointer;
  transition: all 0.3s;
}

.risk-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.risk-header {
  display: flex;
  align-items: center;
  gap: 15px;
}

.risk-info {
  flex: 1;
}

.risk-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.risk-count {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
}

.risk-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-group {
  display: flex;
  gap: 10px;
}

.rule-card,
.feedback-card {
  margin-bottom: 20px;
}

.feedback-content {
  color: #606266;
  font-size: 14px;
  margin: 10px 0;
  line-height: 1.6;
}

.feedback-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
}

.health-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.health-value {
  font-weight: 600;
  color: #303133;
}

.score-breakdown {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.score-line {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #606266;
}
</style>
