<template>
  <div class="shop-value-analysis-page">
    <!-- 1. 页面主标题 -->
    <header class="page-header">
      <div>
        <h1 class="main-title">店铺价值分析</h1>
        <p class="subtitle">实时监控关键指标与趋势</p>
      </div>
    </header>

    <!-- 新增：Top 5 商品贡献分析 (移到顶部) -->
    <div class="chart-card">
      <div class="top-product-contribution-container">
        <!-- 顶部的三个指标卡片 -->
        <div class="kpi-card-grid">
          <div class="kpi-card">
            <span class="kpi-title">总销售额</span>
            <span class="kpi-value">¥{{ formatNumber(topProductData.totalSales) }}</span>
          </div>
          <div class="kpi-card">
            <span class="kpi-title">Top 5 商品总销售额</span>
            <span class="kpi-value">¥{{ formatNumber(topProductData.top5TotalSales) }}</span>
          </div>
          <div class="kpi-card">
            <span class="kpi-title">Top 5 贡献占比</span>
            <span class="kpi-value">{{ (topProductData.contributionRatio * 100).toFixed(2) }}%</span>
          </div>
        </div>
        
        <!-- 下方的环形图 -->
        <div class="chart-card">
          <h3 class="chart-title">Top 5 商品销售分布</h3>
          <div ref="donutChartRef" style="width: 100%; height: 400px;"></div>
        </div>
      </div>
    </div>

    <!-- 3. 筛选与操作栏 -->
    <div class="filter-bar">
      <div class="filters">
        <span>筛选:</span>
        <select><option>全部时间</option></select>
        <select><option>全部渠道</option></select>
        <select><option>全部区域</option></select>
      </div>
      <div class="actions">
        <button class="btn-secondary">导出数据</button>
        <button class="btn-primary" @click="fetchData">刷新</button>
      </div>
    </div>

    <!-- 4. 图表卡片区域 -->
    <div class="charts-container">
      <!-- 部门图表：销量 + 销售金额 -->
      <div class="chart-card">
        <div class="card-header">
          <h3 class="chart-title">各部门业绩分析（销量/金额）</h3>
        </div>
        <div class="chart-wrapper">
          <div ref="unitContributionChart" class="chart-instance"></div>
        </div>
      </div>

      <!-- 渠道图表：销量 + 销售金额 -->
      <div class="chart-card">
        <div class="card-header">
          <h3 class="chart-title">各渠道业绩分析（销量/金额）</h3>
        </div>
        <div class="chart-wrapper">
          <div ref="channelTotalChart" class="chart-instance"></div>
        </div>
      </div>

      <!-- 平台图表：销量 + 销售金额 -->
      <div class="chart-card">
        <div class="card-header">
          <h3 class="chart-title">各平台价值分析（销量/金额）</h3>
        </div>
        <div class="chart-wrapper">
          <div ref="platformChart" class="chart-instance"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  name: 'ShopValue',
  data() {
    return {
      topProductData: {
        totalSales: 0,
        top5TotalSales: 0,
        contributionRatio: 0,
        top5Products: []
      }
    };
  },
  mounted() {
    this.fetchData();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    formatNumber(num) {
      if (!num) return '0';
      return new Intl.NumberFormat().format(Number(num).toFixed(0));
    },
    handleResize() {
      const refs = this.$refs;
      if (refs.unitContributionChart) echarts.getInstanceByDom(refs.unitContributionChart)?.resize();
      if (refs.channelTotalChart) echarts.getInstanceByDom(refs.channelTotalChart)?.resize();
      if (refs.platformChart) echarts.getInstanceByDom(refs.platformChart)?.resize();
      if (refs.donutChartRef) echarts.getInstanceByDom(refs.donutChartRef)?.resize();
    },
    initDonutChart(chartData) {
      const chartEl = this.$refs.donutChartRef;
      if (!chartEl) return;
      const myChart = echarts.getInstanceByDom(chartEl) || echarts.init(chartEl);
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : ?{c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: '0%',
          left: 'center'
        },
        series: [
          {
            name: '???',
            type: 'pie',
            radius: ['60%', '80%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}: {d}%'
            },
            labelLine: {
              show: true,
              length: 15,
              length2: 10
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            data: chartData
          }
        ]
      };
      myChart.setOption(option, true);
      return myChart;
    },
    async fetchTopProductData() {
      try {
        const response = await axios.get('/api/shop/import/top-product-contribution');
        if (response.data.success) {
          const data = response.data.data;
          this.topProductData.totalSales = data.totalSales;
          this.topProductData.top5TotalSales = data.top5TotalSales;
          this.topProductData.contributionRatio = data.contributionRatio;
          this.topProductData.top5Products = data.top5Products;

          const chartData = data.top5Products.map(p => ({
            name: p.productCode,
            value: p.salesAmount
          }));
          this.initDonutChart(chartData);
        }
      } catch (error) {
        console.error('??Top 5??????:', error);
      }
    },
    initDualIndicatorBarChart(chartEl, data, categoryKey, seriesConfig) {
      if (!chartEl) return;
      const spacePerBar = 120;
      const containerWidth = Math.max(800, spacePerBar * data.length);
      chartEl.style.width = `${containerWidth}px`;

      let myChart = echarts.getInstanceByDom(chartEl);
      if (!myChart) myChart = echarts.init(chartEl);

      const categories = data.map(item => item[categoryKey]);
      const series = seriesConfig.map(({ key, name, color, formatter }) => ({
        name,
        type: 'bar',
        data: data.map(item => item[key]),
        barMaxWidth: '40px',
        itemStyle: { color, borderRadius: [4, 4, 0, 0] },
        yAxisIndex: seriesConfig.findIndex(c => c.key === key)
      }));

      const option = {
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        legend: { data: seriesConfig.map(c => c.name), top: 0 },
        grid: { left: '80px', right: '80px', top: '40px', bottom: '60px' },
        xAxis: {
          type: 'category',
          data: categories,
          axisLabel: { interval: 0, rotate: 45, color: '#666', margin: 20 },
          axisTick: { alignWithLabel: true }
        },
        yAxis: seriesConfig.map(({ name, formatter }, index) => ({
          type: 'value',
          name,
          nameTextStyle: { color: '#666' },
          axisLabel: {
            color: '#666',
            formatter: formatter || (value => {
              if (value >= 1000000) return (value / 1000000) + 'M';
              if (value >= 1000) return (value / 1000) + 'K';
              return value;
            })
          },
          position: index === 0 ? 'left' : 'right',
          offset: index === 1 ? 40 : 0
        })),
        series
      };

      myChart.setOption(option, true);
      return myChart;
    },
    initPlatformValueChart(chartEl, data) {
      if (!chartEl) return;
      const spacePerBar = 140;
      const containerWidth = Math.max(800, spacePerBar * data.length);
      chartEl.style.width = `${containerWidth}px`;

      let myChart = echarts.getInstanceByDom(chartEl);
      if (!myChart) myChart = echarts.init(chartEl);

      const categories = data.map(item => item.name);

      const option = {
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        legend: { data: ['??', '????'], top: 0 },
        grid: { left: '80px', right: '80px', top: '40px', bottom: '60px' },
        xAxis: {
          type: 'category',
          data: categories,
          axisLabel: { interval: 0, rotate: 45, color: '#666', margin: 20 },
          axisTick: { alignWithLabel: true }
        },
        yAxis: [
          {
            type: 'value',
            name: '??',
            nameTextStyle: { color: '#666' },
            axisLabel: {
              color: '#5470c6',
              formatter: value => {
                if (value >= 1000000) return (value / 1000000) + 'M';
                if (value >= 1000) return (value / 1000) + 'K';
                return value;
              }
            },
            position: 'left'
          },
          {
            type: 'value',
            name: '????(?)',
            nameTextStyle: { color: '#e9c46a' },
            axisLabel: {
              color: '#e9c46a',
              formatter: value => `?${value.toFixed(2)}`
            },
            position: 'right',
            offset: 40
          }
        ],
        series: [
          {
            name: '??',
            type: 'bar',
            data: data.map(item => item.totalVolume),
            barMaxWidth: '40px',
            itemStyle: { color: '#5470c6', borderRadius: [4, 4, 0, 0] },
            yAxisIndex: 0
          },
          {
            name: '????',
            type: 'bar',
            data: data.map(item => item.avgOrderValue),
            barMaxWidth: '40px',
            itemStyle: { color: '#e9c46a', borderRadius: [4, 4, 0, 0] },
            yAxisIndex: 1
          }
        ]
      };

      myChart.setOption(option, true);
      return myChart;
    },
    async fetchData() {
      try {
        const [
          unitRes,
          channelTotalRes,
          channelContributionRes,
          channelRoiValueRes
        ] = await Promise.all([
          axios.get('/api/shop/import/unit-contribution'),
          axios.get('/api/shop/import/channel-total-contribution'),
          axios.get('/api/shop/import/channel-contribution'),
          axios.get('/api/shop/import/channel-roi-value')
        ]);

        if (unitRes.data.success && unitRes.data.data) {
          const sortedData = [...unitRes.data.data].sort((a, b) => b.totalAmount - a.totalAmount);
          this.initDualIndicatorBarChart(
            this.$refs.unitContributionChart,
            sortedData,
            'name',
            [
              { key: 'totalVolume', name: '??', color: '#5470c6' },
              {
                key: 'totalAmount',
                name: '????(?)',
                color: '#91cc75',
                formatter: value => `?${(value >= 10000 ? (value / 10000) + 'w' : value)}`
              }
            ]
          );
        }

        if (channelTotalRes.data.success && channelTotalRes.data.data) {
          const sortedData = [...channelTotalRes.data.data].sort((a, b) => b.totalAmount - a.totalAmount);
          this.initDualIndicatorBarChart(
            this.$refs.channelTotalChart,
            sortedData,
            'name',
            [
              { key: 'totalVolume', name: '??', color: '#5470c6' },
              {
                key: 'totalAmount',
                name: '????(?)',
                color: '#e9c46a',
                formatter: value => `?${(value >= 10000 ? (value / 10000) + 'w' : value)}`
              }
            ]
          );
        }

        if (
          channelContributionRes.data.success &&
          channelRoiValueRes.data.success &&
          channelContributionRes.data.data &&
          channelRoiValueRes.data.data
        ) {
          const platformSales = Object.entries(channelContributionRes.data.data).map(([name, value]) => ({
            name,
            totalVolume: Number(value)
          }));

          const platformAvgOrder = Object.entries(channelRoiValueRes.data.data).map(([name, value]) => ({
            name,
            avgOrderValue: Number(value)
          }));

          const mergedData = platformSales
            .map(sale => ({
              ...sale,
              avgOrderValue: platformAvgOrder.find(avg => avg.name === sale.name)?.avgOrderValue || 0
            }))
            .sort((a, b) => b.totalVolume - a.totalVolume);

          this.initPlatformValueChart(this.$refs.platformChart, mergedData);
        }

        this.fetchTopProductData();
      } catch (error) {
        console.error('??????:', error);
      }
    }
  }
};
</script>


<style scoped>
/* 保持原有样式不变 */
.shop-value-analysis-page {
  padding: 24px;
  background-color: #f4f7f9;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
}

.page-header {
  margin-bottom: 20px;
}
.main-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
}
.subtitle {
  font-size: 14px;
  color: #86909c;
  margin-top: 4px;
}

.kpi-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}
.kpi-card {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  border: 1px solid #e5e6eb;
}
.kpi-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.kpi-title {
  font-size: 14px;
  color: #4e5969;
}
.kpi-value {
  font-size: 28px;
  font-weight: 700;
  color: #1d2129;
}
.kpi-comparison {
  font-size: 12px;
  margin-top: 8px;
}
.kpi-comparison.positive { color: #00b42a; }
.kpi-comparison.negative { color: #f53f3f; }

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 16px 20px;
  border-radius: 4px;
  border: 1px solid #e5e6eb;
  margin-bottom: 20px;
}
.filters { display: flex; align-items: center; gap: 16px; font-size: 14px; color: #4e5969; }
.filters select { padding: 4px 8px; border-radius: 4px; border: 1px solid #e5e6eb; }
.actions { display: flex; gap: 12px; }
.btn-primary { background-color: #1677ff; color: #fff; border: none; padding: 6px 16px; border-radius: 4px; cursor: pointer; }
.btn-secondary { background-color: #f2f3f5; color: #4e5969; border: 1px solid #e5e6eb; padding: 6px 16px; border-radius: 4px; cursor: pointer; }

.charts-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.chart-card {
  background: #fff;
  padding: 24px;
  border-radius: 4px;
  border: 1px solid #e5e6eb;
  display: grid;
  grid-template-rows: auto 1fr;
  overflow: hidden;
}
.card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.chart-title { font-size: 16px; font-weight: 600; color: #1d2129; }
.chart-wrapper { overflow-x: auto; overflow-y: hidden; min-width: 0; }
.chart-instance { height: 400px; }

.chart-wrapper::-webkit-scrollbar { height: 8px; }
.chart-wrapper::-webkit-scrollbar-track { background: #f1f1f1; }
.chart-wrapper::-webkit-scrollbar-thumb { background: #c9cdd4; border-radius: 4px; }

/* 新增的Top 5商品贡献分析样式 */
.top-product-contribution-container {
  display: flex;
  flex-direction: column;
  gap: 20px; /* 卡片和图表之间的间距 */
  width: 100%;
}

/* KPI卡片网格布局 */
.kpi-card-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 三个卡片平分宽度 */
  gap: 20px; /* 卡片之间的间距 */
}

/* 单个KPI卡片的样式 */
.kpi-card {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.kpi-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.kpi-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

/* 图表卡片的样式 */
.chart-card {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.chart-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 20px;
}
</style>