<template>
  <div style="height: 100%;width: 100%;">
    <div v-if="chartData.length" ref="chartContainer" style="width: 100%; height: 100%;"></div>
    <div v-else style="display: flex;justify-content: center;
    align-items: center;height: 100%;width: 100%;">暂无数据</div>
  </div>
</template>

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

export default {
  //   name: 'SubjectScatterChart',
  props: ["alldata", "subject"],

  data() {
    return {
      chart: null,
      chartData: []
    };
  },
  // mounted() {
  //   this.startCom(this.alldata);
  //   // window.addEventListener('resize', this.handleResize);
  // },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    this.chart && this.chart.dispose();
  },
  watch: {
    alldata: {
      handler(val) {
        if (val && val.length) {
          this.startCom(val);
        }
      },
      deep: true,
      immediate: true // 组件创建时立即执行
    }
  },
  methods: {
    startCom(val) {
      let data = JSON.parse(JSON.stringify(val)).filter(e=> e.typeids).filter(e => e.state != 7);
      
      let subject = JSON.parse(JSON.stringify(this.subject));

      data.forEach(e => {
        e.aitool = 0;
        e.chapters = JSON.parse(e.chapters);
        let kop = [];
        kop = e.chapters.map(i => i.chapterInfo[0].taskJson);
        let op = kop.map(k => k.map(l => l.toolChoose).flat()).flat();
        e.aitool = op
          .map(m => {
            if (m && m.tool && m.tool.length) {
              return m.tool[0];
            }
          })
          .filter(num => num === 72).length;
      });
      // console.log('data',data);


      subject.forEach(e => {
        let course = [];
        let work = [];
        e.aitoolsum = 0;
        e.worksum = 0;
        data.forEach(k => {
          if (k.typeids && k.typeids.includes(e.id)) {
            course.push(k.aitool);
            work.push(k.num);
          }
        });

        e.worksum = work.reduce((acc, curr) => acc + curr, 0);
        e.aitoolsum = course.reduce((acc, curr) => acc + curr, 0);
      });

      this.chartData = subject.map(e => ({
        subject: e.name,
        value: [e.aitoolsum, e.worksum]
      }));
      this.chartData = this.chartData.filter(e=> e.value[0])
      // console.log("this.chartData", this.chartData);

      this.initChart();
    },

    initChart() {
      this.$nextTick(() => {
        this.chart = echarts.init(this.$refs.chartContainer);
        this.updateChart();
      })
    },
    generateSeries() {
      // 按学科分组数据
      const subjects = [...new Set(this.chartData.map(d => d.subject))];
      return subjects.map(subject => ({
        name: subject,
        type: "scatter",
        data: this.chartData
          .filter(d => d.subject === subject)
          .map(d => d.value)
        // itemStyle: {
        //   color: this.colors[subject] || '#999'
        // },
        // symbolSize: this.symbolSize
      }));
    },
    updateChart() {
      const option = {
        tooltip: {
          trigger: "item",
          formatter: params => {
            return `${params.seriesName}<br/>
                    单节课AI嵌入数量: ${params.value[0]}<br/>
                    学生交互量: ${params.value[1]}`;
          }
        },
        legend: {
          data: [...new Set(this.chartData.map(d => d.subject))],
          // orient: "horizontal", // 水平布局
          left: "center", // 水平居中
          top: "0%", // 距离顶部10%
          padding: [10, 10] // 内边距
        },
        grid: {
          top: '15%',      // 上边距，给图表留出空间
          left: 50
        },
        xAxis: {
          name: "单节课程AI迁入数量",
          type: "value",
          scale: true,
          nameLocation: "middle", // 将名称放在轴的中间
          nameGap: 30, // 设置名称与轴之间的间距
          nameTextStyle: {
            align: "middle", // 使名称居中对齐
            fontSize: 16 // 设置字体大小
          }
        },
        yAxis: {
          name: "学生交互量",
          type: "value",
          scale: true,
          nameLocation: "middle", // 将名称放在轴的中间
          nameGap: 30, // 设置名称与轴之间的间距
          nameTextStyle: {
            align: "middle", // 使名称居中对齐
            fontSize: 16 // 设置字体大小
          }
        },
        series: this.generateSeries()
      };
      this.chart.setOption(option, true);
      window.addEventListener("resize", this.chart.resize);
    },
    handleResize() {
      this.chart && this.chart.resize();
    }
  }
};
</script>
