
<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:'TeaLivenessChart',

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 option = {
        tooltip: {
          trigger: 'axis',
          formatter: params => {
            return `日期: ${params[0].name}日<br/>数值: ${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',
           minInterval: 1,  // 关键配置
          axisLabel: {
            formatter: '{value}人',
            color: '#666'
          },
          axisLine: { show: true },
          splitLine: { show: true }
        },
        series: [{
          name: '数据量',
          type: 'line',
          data: yData,
          itemStyle: { 
            color: '#5470c6',
            borderWidth: 2
          },
          lineStyle: { 
            width: 3,
            shadowColor: 'rgba(0, 0, 0, 0.3)',
            shadowBlur: 10,
            shadowOffsetY: 5
          },
          symbol: 'circle',
          symbolSize: 8,
          smooth: true
        }]
      };

      this.chart.setOption(option);
      window.addEventListener('resize', this.chart.resize);
    },
    handleResize() {
      this.chart && this.chart.resize()
    },
    completeMonthData(data) {
        // console.log('data',data);
        
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1;
        const daysInMonth = new Date(year, month, 0).getDate();
        
        const result = [];
        const existingDays = new Set(data.map(item => item.lab));
        
        for (let day = 1; day <= daysInMonth; day++) {
            const dayStr = day.toString().padStart(2, '0');
            if (existingDays.has(dayStr)) {
            result.push(data.find(item => item.lab === dayStr));
            } else {
            result.push({ lab: dayStr, num: 0 });
            }
        }
        
        return result.sort((a, b) => a.lab.localeCompare(b.lab));
    },
  }
}
</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>
