AttributePieChart.vue 8.68 KB
<template>
  <div class="attribute-pie-chart">
    <!-- 图表展示区 -->
    <div class="section-container">
      <div class="section-title">图表展示区</div>

      <div class="chart-content">
        <!-- 左侧 ECharts -->
        <div class="chart-wrapper">
          <div ref="pieChart" style="width: 100%; height: 400px;"></div>
        </div>
        <!-- 右侧自定义图例列表 -->
        <div class="legend-list-wrapper">
          <div class="legend-header">
            <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
            <span class="count-info">{{ selectedItems.length }} / {{ chartData.length }} 项</span>
          </div>
          <div class="legend-list">
            <div v-for="(item, index) in chartData" :key="index" class="legend-item">
              <el-checkbox v-model="item.checked" @change="handleCheckedChange"></el-checkbox>
              <span class="color-dot" :style="{ backgroundColor: getColor(index) }"></span>
              <span class="item-name" :title="item.name">{{ item.name }}</span>
              <span class="item-value">{{ item.value }}</span>
              <span class="item-percent">{{ item.percent }}%</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

export default {
  name: 'AttributePieChart',
  data() {
    return {
      currentDimension: '基金类型偏好',
      displayCount: 10,
      chart: null,
      checkAll: true,
      isIndeterminate: false,
      colors: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
      // Mock Data
      chartData: [
        { name: '新客户', value: 0, percent: 0, checked: true },
        { name: '首购客户', value: 0, percent: 0, checked: true },
        { name: '复购客户', value: 0, percent: 0, checked: true },
        { name: '未购买客户', value: 0, percent: 0, checked: true }
      ]
    };
  },
  computed: {
    selectedItems() {
      return this.chartData.filter(item => item.checked);
    }
  },
  props: {
    dateFilter: {
      type: String,
      default: ''
    }
  },
  watch: {
    dateFilter: {
      handler(newVal) {
        this.generateRandomData(newVal);
        this.updateChart();
      },
      immediate: true
    }
  },
  mounted() {
    // Initial generation is handled by immediate watch
    this.initChart();
    window.addEventListener('resize', this.handleResize);
  },
  methods: {
    generateRandomData(seed) {
      // Reset values
      this.chartData.forEach(item => item.value = 0);
      
      let baseDate = new Date();
      if (seed) {
        // Try to parse the seed date
        const parsed = new Date(seed);
        if (!isNaN(parsed.getTime())) {
          baseDate = parsed;
        }
      }
      
      // Calculate data only for the current week of baseDate
      const d = new Date(baseDate);
      
      // Construct a unique key for this week to ensure deterministic "random" data
      const year = d.getFullYear();
      // Simple week identifier
      const oneJan = new Date(year, 0, 1);
      const dayOfYear = Math.floor((d - oneJan) / (24 * 60 * 60 * 1000));
      const weekNum = Math.ceil((d.getDay() + 1 + dayOfYear) / 7);
      const weekKey = `${year}-W${weekNum}`;

      this.chartData.forEach(item => {
        // Generate value for this specific week and item
        // range: 10 - 200 per week
        const weeklySeed = item.name + weekKey;
        const weeklyValue = this.getPseudoRandom(weeklySeed, 10, 200);
        item.value = weeklyValue;
      });
      
      // Recalculate percentages
      const total = this.chartData.reduce((sum, item) => sum + item.value, 0);
      this.chartData.forEach(item => {
        item.percent = total === 0 ? 0 : ((item.value / total) * 100).toFixed(2);
      });
    },
    getPseudoRandom(seed, min = 100, max = 8000) {
      let value = 0;
      for (let i = 0; i < seed.length; i++) {
        value += seed.charCodeAt(i);
      }
      const sinValue = Math.sin(value) * 10000;
      return Math.floor((sinValue - Math.floor(sinValue)) * (max - min) + min);
    },
    getColor(index) {
      return this.colors[index % this.colors.length];
    },
    handleResize() {
      if (this.chart) this.chart.resize();
    },
    initChart() {
      this.chart = echarts.init(this.$refs.pieChart);
      this.updateChart();
    },
    updateChart() {
      if (!this.chart) return;

      const data = this.chartData.filter(item => item.checked).map((item, index) => ({
        value: item.value,
        name: item.name,
        itemStyle: { color: this.getColor(index) } // Keep color consistent with list index if possible, or dynamic
      }));

      // To maintain color consistency between list and chart, we should assign colors based on original index
      // However, for simplicity here, we'll let echarts handle or map manually.
      // Better approach: Assign color to data item first.
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          show: false // We use custom legend
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['40%', '70%'], // Donut chart
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 2,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c} ({d}%)'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 14,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: this.chartData.filter(item => item.checked).map((item, index) => ({
                value: item.value,
                name: item.name,
                itemStyle: { color: this.getColor(this.chartData.indexOf(item)) }
            }))
          }
        ]
      };

      this.chart.setOption(option);
    },
    handleCheckAllChange(val) {
      this.chartData.forEach(item => item.checked = val);
      this.isIndeterminate = false;
      this.updateChart();
    },
    handleCheckedChange(value) {
      let checkedCount = this.chartData.filter(item => item.checked).length;
      this.checkAll = checkedCount === this.chartData.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.chartData.length;
      this.updateChart();
    }
  }
};
</script>

<style scoped lang="scss">
.attribute-pie-chart {
  background-color: #f5f7fa; // Match page background if needed, or white
  padding: 0;
}

.section-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  
  .section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #333;
  }
}

.config-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  
  .label {
    margin-right: 10px;
    color: #606266;
    font-size: 14px;
  }
  
  .filter-tags, .group-tags {
    margin-left: 10px;
    .el-tag {
      margin-right: 10px;
    }
  }
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

.chart-content {
  display: flex;
  align-items: flex-start;
  
  .chart-wrapper {
    flex: 2;
    min-width: 400px;
  }
  
  .legend-list-wrapper {
    flex: 1;
    min-width: 300px;
    margin-left: 20px;
    border: 1px solid #eee;
    border-radius: 4px;
    padding: 10px;
    background: #fff;
    max-height: 400px;
    overflow-y: auto;
    
    .legend-header {
      display: flex;
      justify-content: space-between;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;
      margin-bottom: 10px;
      
      .count-info {
        color: #909399;
        font-size: 12px;
      }
    }
    
    .legend-item {
      display: flex;
      align-items: center;
      padding: 8px 0;
      font-size: 13px;
      
      .color-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        margin: 0 8px;
        display: inline-block;
      }
      
      .item-name {
        flex: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-right: 10px;
        color: #606266;
      }
      
      .item-value {
        width: 60px;
        text-align: right;
        margin-right: 10px;
        color: #333;
      }
      
      .item-percent {
        width: 50px;
        text-align: right;
        color: #909399;
      }
    }
  }
}
</style>