<template>
  <div class="product-analysis">
    <el-card class="search-card">
      <el-row :gutter="20" align="middle">
        <el-col :span="12">
          <el-input
            v-model="skuInput"
            placeholder="请输入产品SKU（如：E06D01AS1）"
            size="medium"
            clearable
            @keyup.enter.native="searchProduct"
          >
            <template slot="prepend">
              <i class="el-icon-search"></i>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="medium" @click="searchProduct" :loading="loading">
            查询分析
          </el-button>
        </el-col>
        <el-col :span="8">
          <div class="product-info" v-if="productData">
            <el-tag>SKU: {{ skuInput }}</el-tag>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <div v-if="productData">
      <el-row :gutter="20" class="metrics-row">
        <el-col :span="6">
          <el-card class="metric-card">
            <div class="metric-item">
              <div class="metric-label">入库总量</div>
              <div class="metric-value">{{ formatInteger(productData.purchaseQty) }}</div>
              <div class="metric-unit">件</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="metric-card">
            <div class="metric-item">
              <div class="metric-label">销售总量</div>
              <div class="metric-value">{{ formatInteger(productData.salesQty) }}</div>
              <div class="metric-unit">件</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="metric-card">
            <div class="metric-item">
              <div class="metric-label">当前库存</div>
              <div class="metric-value">{{ formatInteger(productData.currentInventory) }}</div>
              <div class="metric-unit">件</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="metric-card">
            <div class="metric-item">
              <div class="metric-label">周转率</div>
              <div class="metric-value">{{ productData.turnoverRate }}</div>
              <div class="metric-unit">次</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="turnover-row" v-if="turnoverBreakdown.length">
        <el-col :span="24">
          <el-card>
            <template slot="header">
              <div class="card-header">
                <span>分段周转率</span>
              </div>
            </template>
            <el-table :data="turnoverBreakdown" border size="small">
              <el-table-column label="统计区间" width="220">
                <template slot-scope="scope">
                  <div class="turnover-period-label">近{{ scope.row.windowDays }}天</div>
                  <div class="turnover-period-range">{{ scope.row.start }} ~ {{ scope.row.end }}</div>
                </template>
              </el-table-column>
              <el-table-column label="销售出库(件)" width="160">
                <template slot-scope="scope">
                  {{ formatInteger(scope.row.salesSum) }}
                </template>
              </el-table-column>
              <el-table-column label="时间加权平均库存(件)" width="220">
                <template slot-scope="scope">
                  {{ formatInventory(scope.row.avgInventory) }}
                </template>
              </el-table-column>
              <el-table-column label="周转率(次)">
                <template slot-scope="scope">
                  {{ formatTurnover(scope.row.turnover) }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="charts-row">
        <el-col :span="24">
          <el-card>
            <template slot="header">
              <div class="card-header">
                <span>单品库存变化趋势（入库/销售/库存）</span>
              </div>
            </template>
            <div ref="trendChart" class="trend-chart" />
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="insights-row">
        <el-col :span="12">
          <el-card>
            <template slot="header">
              <div class="card-header">
                <span>30天预测摘要</span>
              </div>
            </template>
            <div v-if="forecastEnding !== null" class="forecast-meta">
              <div class="forecast-value">{{ Math.round(forecastEnding).toLocaleString() }} 件</div>
              <div class="forecast-delta" :class="{ positive: (forecastDelta || 0) >= 0, negative: (forecastDelta || 0) < 0 }">
                {{ forecastDelta >= 0 ? '+' : '' }}{{ Math.round(forecastDelta || 0).toLocaleString() }} 件 vs 当前库存
              </div>
            </div>
            <el-empty v-else description="暂无预测数据" :image-size="120" />
          </el-card>
        </el-col>
        <el-col :span="12" v-if="lifecycleSegments.length">
          <el-card>
            <template slot="header">
              <div class="card-header">
                <span>生命周期分段</span>
              </div>
            </template>
            <div class="segment-timeline">
              <div
                v-for="seg in lifecycleSegments"
                :key="seg.start + seg.end"
                class="segment-chip"
                :style="{ background: seg.color || stageColorMap[seg.name] || 'rgba(160,160,160,0.18)' }"
              >
                <div class="segment-name">{{ seg.name }}</div>
                <div class="segment-range">{{ seg.start }} ~ {{ seg.end }}</div>
                <div class="segment-score">阶段指数 {{ formatTurnover(seg.score) }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-empty v-else description="请输入产品SKU进行查询分析" :image-size="200" />
  </div>
</template>

<script>
import request from '@/utils/request'
import { Message } from 'element-ui'
import * as echarts from 'echarts'
require('echarts/theme/macarons')

export default {
  name: 'StorageEfficiency',
  data() {
    return {
      skuInput: '',
      productData: null,
      loading: false,
      trendChartInstance: null,
      stageColorMap: {
        '引入期': 'rgba(64, 158, 255, 0.12)',
        '成长期': 'rgba(103, 194, 58, 0.18)',
        '成熟期': 'rgba(250, 200, 88, 0.18)',
        '衰退期': 'rgba(245, 108, 108, 0.18)'
      }
    }
  },
  computed: {
    lifecycleSegments() {
      return (this.productData && this.productData.lifecycleSegments) || []
    },
    turnoverBreakdown() {
      return (this.productData && this.productData.turnoverBreakdown) || []
    },
    forecastEnding() {
      if (!this.productData || !Array.isArray(this.productData.forecastInventory)) return null
      const future = this.productData.forecastInventory.filter(v => v !== null && v !== undefined)
      if (!future.length) return null
      return future[future.length - 1]
    },
    forecastDelta() {
      if (this.forecastEnding === null) return null
      const current = (this.productData && this.productData.currentInventory) || 0
      return this.forecastEnding - current
    }
  },
  mounted() {
    window.addEventListener('resize', this.resizeChart)
  },
  activated() {
    if (this.productData) {
      this.$nextTick(() => {
        this.initTrendChart()
        this.updateTrendChart()
      })
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart)
    if (this.trendChartInstance) {
      this.trendChartInstance.dispose()
      this.trendChartInstance = null
    }
  },
  methods: {
    formatInteger(value) {
      return Number(value || 0).toLocaleString()
    },
    formatInventory(value) {
      return Number(value || 0).toLocaleString(undefined, { maximumFractionDigits: 1 })
    },
    formatTurnover(value) {
      return Number(value || 0).toFixed(2)
    },
    initTrendChart() {
      if (this.trendChartInstance || !this.$refs.trendChart) return
      this.trendChartInstance = echarts.init(this.$refs.trendChart, 'macarons')
    },
    resizeChart() {
      if (this.trendChartInstance) this.trendChartInstance.resize()
    },
    buildMarkAreas(segments) {
      return segments.map(seg => {
        const label = seg.score !== undefined ? `${seg.name} (${Number(seg.score).toFixed(2)})` : seg.name
        return [
          {
            xAxis: seg.start,
            name: label,
            itemStyle: { color: seg.color || this.stageColorMap[seg.name] || 'rgba(160,160,160,0.25)' },
            label: { color: '#606266' }
          },
          { xAxis: seg.end || seg.start }
        ]
      })
    },
    updateTrendChart() {
      if (!this.trendChartInstance || !this.productData) return
      const segments = this.lifecycleSegments
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' }
        },
        legend: {
          data: ['入库', '销售', '当前库存', '稳定库存', '预测库存(30天)']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: { type: 'category', data: this.productData.dates || [] },
        yAxis: { type: 'value', name: '数量 (件)' },
        series: [
          {
            name: '入库',
            type: 'bar',
            data: this.productData.purchaseByDay || [],
            itemStyle: { color: '#5470c6' }
          },
          {
            name: '销售',
            type: 'bar',
            data: this.productData.salesByDay || [],
            itemStyle: { color: '#91cc75' }
          },
          {
            name: '当前库存',
            type: 'line',
            data: this.productData.inventoryByDay || [],
            itemStyle: { color: '#fac858' },
            lineStyle: { width: 3 },
            smooth: true,
            markArea: {
              itemStyle: { color: 'rgba(160,160,160,0.25)' },
              label: { show: true, color: '#606266' },
              silent: false,
              data: this.buildMarkAreas(segments)
            }
          },
          {
            name: '稳定库存',
            type: 'line',
            data: this.productData.stableInventory || [],
            itemStyle: { color: '#73c0de' },
            lineStyle: { width: 2, type: 'dashed' },
            smooth: true
          },
          {
            name: '预测库存(30天)',
            type: 'line',
            data: this.productData.forecastInventory || [],
            itemStyle: { color: '#ee6666' },
            lineStyle: { width: 2 },
            smooth: true
          }
        ]
      }
      this.trendChartInstance.setOption(option, true)
    },
    normalizeResponse(res) {
      if (!res) return null
      if (res.code === 200) return res.data
      if (res.data) return res.data
      return null
    },
    async fetchProductTrend(sku) {
      try {
        const res = await request({ url: `/api/product/trend/${sku}`, method: 'get' })
        return this.normalizeResponse(res)
      } catch (e) {
        try {
          const res = await request({
            url: '/api/inventory/product-trend',
            method: 'get',
            params: { sku }
          })
          return this.normalizeResponse(res)
        } catch (err) {
          throw err
        }
      }
    },
    async searchProduct() {
      const sku = this.skuInput.trim()
      if (!sku) {
        Message.warning('请输入产品SKU')
        return
      }

      this.loading = true
      try {
        const data = await this.fetchProductTrend(sku)
        if (data) {
          this.productData = data
          this.$nextTick(() => {
            this.initTrendChart()
            this.updateTrendChart()
            this.resizeChart()
          })
          if (data.purchaseQty === 0 && data.salesQty === 0) {
            Message.info(`SKU "${sku}" 没有找到相关数据`)
          }
        } else {
          this.productData = null
        }
      } catch (error) {
        console.error('查询产品失败:', error)
        Message.error('查询失败，请稍后重试')
        this.productData = null
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.product-analysis {
  width: 100%;
}

.search-card {
  margin-bottom: 20px;
}

.product-info {
  display: flex;
  gap: 10px;
  align-items: center;
}

.metrics-row {
  margin-bottom: 20px;
}

.turnover-row {
  margin-bottom: 20px;
}

.turnover-period-label {
  font-weight: 600;
  color: #303133;
}

.turnover-period-range {
  font-size: 12px;
  color: #909399;
}

.metric-card {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

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

.metric-item {
  padding: 10px;
}

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

.metric-value {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

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

.charts-row {
  margin-bottom: 20px;
}

.insights-row {
  margin-bottom: 20px;
}

.forecast-meta {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 10px 0;
}

.forecast-value {
  font-size: 34px;
  font-weight: 600;
  color: #303133;
}

.forecast-delta {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.forecast-delta.positive {
  color: #67c23a;
}

.forecast-delta.negative {
  color: #f56c6c;
}

.segment-timeline {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.segment-chip {
  padding: 12px 14px;
  border-radius: 10px;
  color: #303133;
  min-width: 180px;
  box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.05);
}

.segment-name {
  font-size: 16px;
  font-weight: 600;
}

.segment-range {
  font-size: 12px;
  color: #606266;
  margin: 6px 0;
}

.segment-score {
  font-size: 12px;
  color: #909399;
}

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

.trend-chart {
  height: 400px;
}
</style>
