<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 {
  name: 'TeaHoopChart',
  props: ['alldata'],
  data() {
    return {
      chart: null,
      pageData: [],
      cutNum: 0,
      chartData: []
    };
  },
  watch: {
    alldata: {
      handler(val) {
        // console.log('val', val);
        if (val.length) {
          this.startCom(val);
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.chart && this.chart.dispose();
  },
  methods: {
    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);
      }
    },
    startCom(val) {
      let data = JSON.parse(JSON.stringify(val));
      this.pageData.push(data[0]); // 得出每日数据
      this.pageData.push(data[1]);
      this.pageData.push(data[2]);
    //   console.log('this.pageData', this.pageData);
      this.chartData = data[0];
      this.initChart();
    },
    initChart() {
      this.chart = echarts.init(this.$refs.chartContainer);
      this.updateChart();
    },
    updateChart() {
      const xData = this.chartData.map(item => item.lab);
      const yData = this.chartData.map(item => item.num);

      // 计算环比增长率
      const growthRates = this.calculateGrowthRates(yData);

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: params => {
            return `日期: ${params[0].name}${this.cutNum == 0 ? '日' : this.cutNum == 1 ? '周' : '月'}<br/>环比增长率: ${Math.round(params[0].value)}%`;
          }
        },
        xAxis: {
          type: 'category',
          data: xData,
          axisLabel: {
            color: '#666',
            formatter: value => `${value}${this.cutNum == 0 ? '日' : this.cutNum == 1 ? '周' : '月'}`
          },
          axisLine: {
            lineStyle: { color: '#6FC6F3', width: 2 }
          }
        },
        yAxis: {
          type: 'value',
          min: -15, // 设置y轴的最小值
          max: 15, // 设置y轴的最大值
          axisLabel: {
            formatter: '{value}%',
            color: '#666'
          },
          axisLine: { show: true },
          splitLine: { show: true }
        },
        series: [{
          name: '环比增长率',
          type: 'bar', // 使用柱状图
          data: growthRates,
          itemStyle: {
            color: (params) => {
              return params.value >= 0 ? '#5470c6' : '#ef5350'; // 正值为蓝色，负值为红色
            }
          },
        }],
        label: {
            show: true, // 显示标签
            position: 'top', // 标签位置在柱子上方
             formatter: function(params) {
                return `${Math.round(params.value)}%`;  // 强制显示整数
            }
        },
      };

      this.chart.setOption(option);
      window.addEventListener('resize', this.chart.resize);
    },
    calculateGrowthRates(values) {
      return values.map((value, index) => {
        if (index === 0) return 0; // 第一个值没有增长率
        return ((value - values[index - 1]) / (values[index - 1] ? values[index - 1] : 1)) * 100;
      });
    },
    handleResize() {
      this.chart && 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;
}
.timeL div {
  height: 25px;
  width: 30px;
  text-align: center;
  line-height: 25px;
  box-sizing: border-box;
  background: #F5F7FA;
  border-radius: 5px;
  cursor: pointer;
}
.hov {
  background: #0358D2 !important;
  color: #fff;
}
</style>