<template>
  <div class="capacity-management">
    <el-card class="setting-card">
      <div class="setting-bar">
        <div class="setting-item">
          <span class="setting-label">总库容边界</span>
          <el-input-number v-model="capacityLimit" :min="1" :step="1000" size="small" />
          <span class="setting-unit">件</span>
        </div>
        <div class="setting-item">
          <span class="setting-label">爆仓预警线</span>
          <el-input-number v-model="warningBoundary" :min="50" :max="100" :step="1" size="small" />
          <span class="setting-unit">%</span>
        </div>
        <el-button type="primary" size="small" @click="refreshData" :loading="loading">
          <i class="el-icon-refresh"></i> 刷新
        </el-button>
      </div>
    </el-card>

    <el-row :gutter="20" class="metrics-row">
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-icon blue"><i class="el-icon-data-analysis"></i></div>
            <div class="metric-info">
              <div class="metric-label">库容利用率</div>
              <div class="metric-value">{{ formatPercent(capacityUtilization) }}</div>
              <div class="metric-unit">当前库存 / 总库容</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-icon green"><i class="el-icon-box"></i></div>
            <div class="metric-info">
              <div class="metric-label">根据库容边界可存储量</div>
              <div class="metric-value">{{ formatInteger(availableByBoundary) }}</div>
              <div class="metric-unit">件</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-icon orange"><i class="el-icon-warning-outline"></i></div>
            <div class="metric-info">
              <div class="metric-label">爆仓预警</div>
              <div class="metric-value status-value" :class="overflowWarning.type">{{ overflowWarning.text }}</div>
              <div class="metric-unit">预警线 {{ warningBoundary }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-icon red"><i class="el-icon-s-grid"></i></div>
            <div class="metric-info">
              <div class="metric-label">当前库存占用</div>
              <div class="metric-value">{{ formatInteger(currentInventory) }}</div>
              <div class="metric-unit">件</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card>
          <template slot="header">
            <span>各品类库存库容占比</span>
          </template>
          <div ref="categoryCapacityChart" class="chart" />
          <el-empty v-if="!loading && categoryCapacityRows.length === 0" description="暂无品类库存数据" />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template slot="header">
            <span>库容边界结构</span>
          </template>
          <div ref="capacityGaugeChart" class="chart" />
        </el-card>
      </el-col>
    </el-row>

    <el-card class="table-card">
      <template slot="header">
        <div class="card-header">
          <span>品类库容明细</span>
          <el-tag :type="overflowWarning.tagType">{{ overflowWarning.text }}</el-tag>
        </div>
      </template>
      <el-table :data="categoryCapacityRows" stripe v-loading="loading">
        <el-table-column prop="category" label="品类" min-width="160" />
        <el-table-column label="库存量" width="140" align="right">
          <template slot-scope="scope">{{ formatInteger(scope.row.inventory) }}</template>
        </el-table-column>
        <el-table-column label="占总库容" width="140" align="right">
          <template slot-scope="scope">{{ formatPercent(scope.row.capacityRatio) }}</template>
        </el-table-column>
        <el-table-column label="占当前库存" width="140" align="right">
          <template slot-scope="scope">{{ formatPercent(scope.row.inventoryRatio) }}</template>
        </el-table-column>
        <el-table-column label="边界剩余可存" width="160" align="right">
          <template slot-scope="scope">{{ formatInteger(scope.row.availableByBoundary) }}</template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getCategoryStatus(scope.row).type">{{ getCategoryStatus(scope.row).text }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'
import * as echarts from 'echarts'
require('echarts/theme/macarons')

export default {
  name: 'StorageStock',
  data() {
    return {
      loading: false,
      capacityLimit: 100000,
      warningBoundary: 85,
      overviewData: {
        totalInventory: 0
      },
      skuRows: [],
      categoryCapacityChart: null,
      capacityGaugeChart: null
    }
  },
  computed: {
    currentInventory() {
      const totalFromSku = this.skuRows.reduce((sum, row) => sum + this.getRowInventory(row), 0)
      return totalFromSku > 0 ? totalFromSku : Number(this.overviewData.totalInventory || 0)
    },
    boundaryCapacity() {
      return Number(this.capacityLimit || 0) * Number(this.warningBoundary || 0) / 100
    },
    capacityUtilization() {
      if (!this.capacityLimit) return 0
      return this.currentInventory / this.capacityLimit * 100
    },
    availableByBoundary() {
      return Math.max(this.boundaryCapacity - this.currentInventory, 0)
    },
    overflowWarning() {
      if (this.currentInventory >= this.capacityLimit) {
        return { text: '已爆仓', type: 'danger', tagType: 'danger' }
      }
      if (this.currentInventory >= this.boundaryCapacity) {
        return { text: '接近爆仓', type: 'warning', tagType: 'warning' }
      }
      return { text: '库容正常', type: 'success', tagType: 'success' }
    },
    categoryCapacityRows() {
      const map = {}
      this.skuRows.forEach(row => {
        const category = row.category || row.productType || row.attribute || '未分类'
        if (!map[category]) map[category] = 0
        map[category] += this.getRowInventory(row)
      })
      return Object.keys(map)
        .map(category => {
          const inventory = map[category]
          return {
            category,
            inventory,
            capacityRatio: this.capacityLimit ? inventory / this.capacityLimit * 100 : 0,
            inventoryRatio: this.currentInventory ? inventory / this.currentInventory * 100 : 0,
            availableByBoundary: Math.max(this.boundaryCapacity * (inventory / Math.max(this.currentInventory, 1)) - inventory, 0)
          }
        })
        .sort((a, b) => b.inventory - a.inventory)
    }
  },
  mounted() {
    this.loadCapacitySettings()
    this.refreshData()
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts)
    if (this.categoryCapacityChart) this.categoryCapacityChart.dispose()
    if (this.capacityGaugeChart) this.capacityGaugeChart.dispose()
  },
  watch: {
    capacityLimit() {
      this.saveCapacitySettings()
      this.$nextTick(this.updateCharts)
    },
    warningBoundary() {
      this.saveCapacitySettings()
      this.$nextTick(this.updateCharts)
    },
    categoryCapacityRows() {
      this.$nextTick(this.updateCharts)
    }
  },
  methods: {
    normalizeResponse(res) {
      if (!res) return null
      if (res.code === 200) return res.data
      if (res.data) return res.data
      return null
    },
    loadCapacitySettings() {
      try {
        const raw = localStorage.getItem('storage-capacity-settings')
        if (!raw) return
        const data = JSON.parse(raw)
        if (data.capacityLimit) this.capacityLimit = Number(data.capacityLimit)
        if (data.warningBoundary) this.warningBoundary = Number(data.warningBoundary)
      } catch (e) {
        console.error('读取库容设置失败:', e)
      }
    },
    saveCapacitySettings() {
      localStorage.setItem('storage-capacity-settings', JSON.stringify({
        capacityLimit: this.capacityLimit,
        warningBoundary: this.warningBoundary
      }))
    },
    async refreshData() {
      this.loading = true
      try {
        await Promise.all([this.fetchOverview(), this.fetchSkuSummary()])
      } finally {
        this.loading = false
        this.$nextTick(() => {
          this.initCharts()
          this.updateCharts()
        })
      }
    },
    async fetchOverview() {
      try {
        const res = await request({ url: '/api/inventory/overview', method: 'get', timeout: 120000 })
        const data = this.normalizeResponse(res)
        if (data) this.overviewData = { ...this.overviewData, ...data }
      } catch (e) {
        console.error('获取库存概览失败:', e)
      }
    },
    async fetchSkuSummary() {
      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)
        this.skuRows = []
      }
    },
    getRowInventory(row) {
      return Number(row.inventory || row.currentInventory || row.remainingInventory || row.quantity || 0)
    },
    initCharts() {
      if (!this.categoryCapacityChart && this.$refs.categoryCapacityChart) {
        this.categoryCapacityChart = echarts.init(this.$refs.categoryCapacityChart, 'macarons')
      }
      if (!this.capacityGaugeChart && this.$refs.capacityGaugeChart) {
        this.capacityGaugeChart = echarts.init(this.$refs.capacityGaugeChart, 'macarons')
      }
    },
    updateCharts() {
      this.updateCategoryChart()
      this.updateGaugeChart()
    },
    updateCategoryChart() {
      if (!this.categoryCapacityChart) return
      const rows = this.categoryCapacityRows
      this.categoryCapacityChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: params => {
            const item = params && params.length ? params[0] : null
            const row = item ? rows[item.dataIndex] : null
            if (!row) return ''
            return `${row.category}<br/>库存: ${this.formatInteger(row.inventory)} 件<br/>占总库容: ${this.formatPercent(row.capacityRatio)}`
          }
        },
        grid: { left: '3%', right: '5%', bottom: '3%', containLabel: true },
        xAxis: { type: 'value', name: '%' },
        yAxis: {
          type: 'category',
          inverse: true,
          data: rows.map(item => item.category),
          axisLabel: { width: 110, overflow: 'truncate' }
        },
        series: [{
          name: '库容占比',
          type: 'bar',
          barMaxWidth: 18,
          data: rows.map(item => Number(item.capacityRatio.toFixed(2))),
          itemStyle: { color: '#409eff' },
          label: { show: true, position: 'right', formatter: '{c}%' }
        }]
      }, true)
    },
    updateGaugeChart() {
      if (!this.capacityGaugeChart) return
      this.capacityGaugeChart.setOption({
        tooltip: {
          formatter: `库容利用率<br/>${this.formatPercent(this.capacityUtilization)}`
        },
        series: [{
          name: '库容利用率',
          type: 'gauge',
          min: 0,
          max: 100,
          progress: { show: true, width: 14 },
          axisLine: { lineStyle: { width: 14 } },
          pointer: { width: 4 },
          detail: {
            formatter: value => `${Number(value || 0).toFixed(1)}%`,
            fontSize: 24
          },
          data: [{ value: Number(this.capacityUtilization.toFixed(1)), name: `预警线 ${this.warningBoundary}%` }]
        }]
      }, true)
    },
    resizeCharts() {
      if (this.categoryCapacityChart) this.categoryCapacityChart.resize()
      if (this.capacityGaugeChart) this.capacityGaugeChart.resize()
    },
    getCategoryStatus(row) {
      if (row.capacityRatio >= this.warningBoundary) return { text: '高占用', type: 'danger' }
      if (row.capacityRatio >= this.warningBoundary * 0.7) return { text: '偏高', type: 'warning' }
      return { text: '正常', type: 'success' }
    },
    formatInteger(value) {
      return Number(value || 0).toLocaleString()
    },
    formatPercent(value) {
      return `${Number(value || 0).toFixed(1)}%`
    }
  }
}
</script>

<style scoped>
.capacity-management {
  width: 100%;
}

.setting-card,
.metrics-row,
.charts-row,
.table-card {
  margin-bottom: 20px;
}

.setting-bar {
  display: flex;
  align-items: center;
  gap: 18px;
  flex-wrap: wrap;
}

.setting-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.setting-label {
  font-size: 14px;
  color: #606266;
}

.setting-unit,
.metric-unit {
  font-size: 12px;
  color: #909399;
}

.metric-card {
  transition: transform 0.3s;
}

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

.metric-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.metric-icon {
  width: 58px;
  height: 58px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 28px;
}

.metric-icon.blue {
  background: #409eff;
}

.metric-icon.green {
  background: #67c23a;
}

.metric-icon.orange {
  background: #e6a23c;
}

.metric-icon.red {
  background: #f56c6c;
}

.metric-info {
  min-width: 0;
  flex: 1;
}

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

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

.status-value {
  font-size: 24px;
}

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

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

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

.chart {
  height: 320px;
}

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