<template>
  <div class="mod-demo-echarts">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <div id="lineChart" class="chart-box"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
export default {
  props: {
    title: {
      type: String,
    },
    dataList: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      //testdata
      lineChart: {},
    };
  },
  mounted() {
    this.initChartLine();
  },
  activated() {
    // 由于给echart添加了resize事件, 在组件激活时需要重新resize绘画一次, 否则出现空白bug
    if (this.lineChart) {
      this.lineChart.resize();
    }
  },
  methods: {
    // 折线图
    initChartLine() {
      var option = {
        title: {
          text: this.title,
          left: "left",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // Use axis to trigger tooltip
            type: "shadow", // 'shadow' as default; can also be 'line' or 'shadow'
          },
        },
        legend: {
          top: "6%",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: [
            ...new Set(
              this.dataList?.map((item) => {
                return item.month;
              })
            ),
          ],
        },
        yAxis: {
          type: "value",
        },
        series: [],
      };
      this.dataList.forEach((item) => {
        const i = option.series.findIndex((c) => c.id === item.productTypeId);
        if (i >= 0) {
          option.series[i].data.push(item.productTypeNumber);
        } else {
          console.log(item.productTypeName)
          const obj = {
            name: item.productTypeName,
            id: item.productTypeId,
            type: "bar",
            stack: "total",
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [],
          };
          obj.data.push(item.productTypeNumber);
          option.series.push(obj);
        }
      })
      console.log(option.series)
      this.lineChart = echarts.init(document.getElementById("lineChart"))
      this.lineChart.setOption(option);
      window.addEventListener("resize", () => {
        this.lineChart.resize();
      });
    },
  },
};
</script>

<style lang="scss">
.mod-demo-echarts {
  > .el-row {
    .el-col {
    }
  }
  .chart-box {
    min-height: 400px;
  }
}
</style>
