<template>
  <div  style="display: flex;flex-direction: column;">
    <div class="top">
      <div>活跃用户分层</div>
      <div class="timeL">
        <div @click="cut(0)" :class="cutNum == 0 ? 'hov' : ''">日</div>
        <div @click="cut(1)" :class="cutNum == 1 ? 'hov' : ''">周</div>
        <div @click="cut(2)" :class="cutNum == 2 ? 'hov' : ''">月</div>
      </div>
    </div>
    <div ref="chartContainer" style="width: 100%; flex: 1;"></div>
  </div>
</template>

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

export default {
  props: ['alldata'],

  data() {
    return {
        chart: null,
        pageData: [],
        cutNum: 0,
        chartData: []
    };
  },
  // mounted() {
  //   this.initChart();
  //   window.addEventListener('resize', this.handleResize);
  // },
  watch: {
     alldata:{
            handler(val) {                
                if (val.length) {
                    this.startCom(val)
                }
            },
            deep:true,
            immediate: true  // 组件创建时立即执行
        }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    this.chart && this.chart.dispose();
  },
  methods: {
    startCom(val) {
        let data = JSON.parse(JSON.stringify(val));
        this.pageData.push(data[3]); // 得出每日数据
        this.pageData.push(data[4]);
        this.pageData.push(data[5]);
        // console.log('this.pageData', this.pageData);
        this.chartData = data[3];
        this.initChart();
    },
    handleResize() {
      this.chart && this.chart.resize();
    },
    cut(val) {
    //   console.log('val', val);
      this.cutNum = val;

      if (this.pageData[val]) {
        this.chartData = this.pageData[val];

        // 清空图表
        this.chart.clear();

        // 使用 nextTick 确保在设置选项之前 DOM 已更新
        this.$nextTick(() => {
          this.updateChart(); // 调用 updateChart 设置新选项
        });
      } else {
        console.error('提供的值无效，未找到对应数据:', val);
      }
    },
    initChart() {
      this.chart = echarts.init(this.$refs.chartContainer);
      this.updateChart();
    },
    updateChart() {
      const total = this.chartData[0].high + this.chartData[0].mid + this.chartData[0].low;

      const data = [
        { value: this.chartData[0].high, name: '高频' },
        { value: this.chartData[0].mid, name: '中频' },
        { value: this.chartData[0].low, name: '低频' },
      ];

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top:'10%',
          formatter: (name) => {
            const dataInfo = {
              '高频': `高频 ${((this.chartData[0].high / total) * 100).toFixed(2)}% (${this.chartData[0].high}人)`,
              '中频': `中频 ${((this.chartData[0].mid / total) * 100).toFixed(2)}% (${this.chartData[0].mid}人)`,
              '低频': `低频 ${((this.chartData[0].low / total) * 100).toFixed(2)}% (${this.chartData[0].low}人)`,
            };
            return dataInfo[name] || '';
          }
        },
        series: [
          {
            name: '用户数量',
            type: 'pie',
            radius: ['30%', '60%'], // 创建环形图
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 2
            }
          }
        ],
        graphic: {
          type: 'text',
          left: 'center',
          top: 'middle',
          style: {
            text: `总计\n ${total}人`,
            fill: '#000',
            font: '20px Arial',
            textAlign: 'center',
            transform: 'translate(-50%,-50%)'
          },
          silent: true
        }
      };

      this.chart.setOption(option);
      window.addEventListener('resize', this.chart.resize);
    }
  }
}
</script>

<style scoped>
.top {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
  box-sizing: border-box;
  align-items: center;
  
}
.timeL {
  display: flex;
  justify-content: space-between;
  gap: 10px;
  height: 25px;
}
.timeL div {
  width: 30px;
  text-align: center;
  box-sizing: border-box;
  background: #F5F7FA;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.hov {
  background: #0358D2 !important;
  color: #fff;
}
</style>