<template>

  <div class="chart-card">

    <h3 class="chart-title">明星商品价值环图 (Top 5)</h3>

    <OrderLoadingPanel
      v-if="loading"
      title="正在加载 Top 5 商品数据"
      detail="正在汇总商品销售额与贡献占比"
    />

    <div ref="pieChart" style="width: 100%; height: 300px;"></div>

    

    <div class="legend-area">

      <div class="percentage-label">

        <span class="percent-value">{{ top5Percent }}%</span>

        <p class="percent-text">Top 5 商品贡献占比</p>

      </div>

    </div>

  </div>

</template>



<script>
import * as echarts from 'echarts';
import { getOrderTop5Percentage, getOrderTop5Products } from '@/api/order';
import OrderLoadingPanel from '../../components/OrderLoadingPanel.vue';



export default {

  name: 'Top5PieChart',
  components: {
    OrderLoadingPanel
  },

  props: {

    dateRange: {

      type: Object,

      default: () => ({ start: '', end: '' })

    }

  },

  data() {

    return {

      chartData: [],

      legendData: [],

      top5Percent: 0,

      loading: true,

      colors: ['#3366CC', '#4ECDC4', '#A5D8FF', '#FFB347', '#FF6347']

    };

  },

  watch: {

    dateRange: {

      handler(newRange) {

        this.fetchPieData(newRange);

      },

      deep: true

    }

  },

  mounted() {

    this.fetchPieData();

  },

  methods: {

    async fetchPieData(dateRange = null) {

      this.loading = true;

      try {
        const params = dateRange && dateRange.start && dateRange.end
          ? { startDate: dateRange.start, endDate: dateRange.end }
          : undefined;

        const rawProducts = await getOrderTop5Products(params) || [];



        this.chartData = rawProducts.map(product => ({

          value: parseFloat(product.totalSales),

          name: `${product.sku} (${product.name})`

        }));



        this.legendData = rawProducts.map(product => `${product.sku} (${product.name})`);



        const percentageResponse = await getOrderTop5Percentage(params);

        if (percentageResponse.success) {

          this.top5Percent = Math.round(percentageResponse.data.top5Percentage);

        }



        this.renderChart();

      } catch (error) {

        console.error('获取Top5商品数据失败:', error);

      } finally {

        this.loading = false;

      }

    },

    renderChart() {

      const chartEl = this.$refs.pieChart;

      if (!this.chartData.length || !chartEl) return;

      const myChart = echarts.getInstanceByDom(chartEl) || echarts.init(chartEl);

      const option = {

        color: this.colors,

        tooltip: {

          trigger: 'item',

          formatter: params => {

            const index = this.chartData.findIndex(item => item.name === params.name);

            const fullLabel = this.legendData[index] || params.name;

            return `${fullLabel}: ${params.value.toLocaleString()} (${params.percent}%)`;

          }

        },

        legend: {

          show: true,

          type: 'scroll',

          orient: 'horizontal',

          bottom: 10,

          data: this.legendData,

          itemGap: 20,

          itemWidth: 15,

          itemHeight: 10,

          textStyle: { fontSize: 12 },

          width: '90%',

          height: 'auto'

        },

        series: [

          {

            name: 'Top 5 ??',

            type: 'pie',

            radius: ['50%', '70%'],

            center: ['50%', '45%'],

            data: this.chartData,

            emphasis: {

              itemStyle: {

                shadowBlur: 10,

                shadowOffsetX: 0,

                shadowColor: 'rgba(0, 0, 0, 0.5)'

              }

            },

            label: {

              show: true,

              formatter: params => params.name.split(' (')[0],

              position: 'outside'

            },

            labelLine: { show: true }

          }

        ]

      };

      myChart.setOption(option);

      window.addEventListener('resize', () => myChart.resize());

    }

  }

};

</script>





<style scoped>

/* 样式部分和之前一样，不用修改 */

.chart-card {

  background-color: white;

  padding: 20px;

  border-radius: 8px;

  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

  position: relative;

}

.chart-title {

  text-align: center;

  font-size: 16px;

  font-weight: 600;

  color: #333;

  margin-bottom: 20px;

}

.percentage-label {

    position: absolute;

    top: 50%;

    left: 50%;

    transform: translate(-50%, -50%); 

    pointer-events: none; 

    z-index: 10;

    text-align: center;

}

.percent-value {

    font-size: 24px;

    font-weight: bold;

    color: #333;

}

.percent-text {

    font-size: 12px;

    color: #666;

    margin-top: 5px;

}

[ref="pieChart"] {

    position: relative;

}

</style>
