<template>
  <div class="chart" :id="id"></div>
</template>

<script>
import util from "@/helper/util.js";
import partten from "@/helper/partten.js";
import * as echarts from "echarts";

export default {
  props: {
    // 图表宽度
    width: {
      type: String,
      default: "100%",
    },
    // 图表高度
    height: {
      type: String,
      default: "350px",
    },
    // 图表主标题
    chartTitle: {
      type: String,
      default: "自定义图表组件",
    },
    // X 轴配置项
    xAxisData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    // Y 轴配置项
    yAxisData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    // 图表核心数据
    seriesData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    // 是否显示图表图例
    showLegend: {
      type: Boolean,
      default: true,
    },
    // 是否默认采用笔刷模式
    brushSelected: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      id: "",
      chart: null,
      color: [
        "#05bb4c",
        "#4b55ae",
        "#fa8c16",
        "#f8de5b",
        "#1a93cf",
        "#c531c7",
        "#bd3338",
      ],
    };
  },
  methods: {
    resize() {},
    initChart() {
      const that = this;
      let myChart = echarts.init(document.getElementById(this.id));

      //指定图表的配置项和数据
      const option = {
        //标题
        title: {
          text: that.chartTitle,
          textStyle: {
            fontSize: util.vh(16),
            color: that.$store.state.themeName === "dark" ? "#fff" : "#000",
          },
        },
        backgroundColor:
          that.$store.state.themeName === "dark"
            ? "rgba(0,0,0,0.4)"
            : "rgba(255,255,255,0.5)",
        //工具箱
        toolbox: {
          show: true,
          x: "right",
          position: [10, 10],
          backgroundColor:
            that.$store.state.themeName === "dark"
              ? "rgba(0,0,0,0.4)"
              : "rgba(255,255,255,0.5)",
          borderColor:
            that.$store.state.themeName === "dark"
              ? partten.getColor("gray")
              : "#000",
          textStyle: {
            fontSize: util.vh(16),
            color: that.$store.state.themeName === "dark" ? "#fff" : "#000",
          },
          iconStyle: {
            borderColor:
              that.$store.state.themeName === "dark" ? "#fff" : "#000",
          },
          emphasis: {
            iconStyle: {
              borderColor:
                that.$store.state.themeName === "dark" ? "#fff" : "#000",
            },
          },
          // feature: {
          //   dataZoom: {
          //     yAxisIndex: "none",
          //   },
          //   dataView: { readOnly: false },
          //   magicType: { type: ["line", "bar"] },
          //   restore: {},
          //   saveAsImage: {},
          // },
        },
        tooltip: {
          trigger: "item",
          axisPointer: {
            type: "cross",
          },
          backgroundColor:
            that.$store.state.themeName === "dark"
              ? "rgba(0,0,0,0.4)"
              : "rgba(255,255,255,0.5)",
          borderColor:
            that.$store.state.themeName === "dark"
              ? partten.getColor("gray")
              : "#000",
          textStyle: {
            fontSize: util.vh(16),
            color: that.$store.state.themeName === "dark" ? "#fff" : "#000",
          },
          formatter(params) {
            return params.name
              ? `${params.seriesName}<br />风速：${params.name}米/s<br />功率：${params.value}kW`
              : `${params.seriesName}<br />风速：${params.data[0]}米/s<br />功率：${params.data[1]}kW`;
          },
        },
        brush: {
          // xAxisIndex: "all",
          // yAxisIndex: "all",
          transformable: true,
          throttleType: "debounce",
          throttleDelay: 600,
          removeOnClick: false,
          brushType: "polygon",
          brushMode: "multiple",
          brushStyle: {
            borderWidth: 1,
            color: "rgba(255,36,36,0.2)",
            borderColor: "#ff2424",
          },
          // outOfBrush: {
          //   colorAlpha: 0.5,
          // },
        },
        dataZoom: [
          {
            type: "inside", //图表下方的伸缩条
            show: true, //是否显示
            realtime: true, //拖动时，是否实时更新系列的视图
            start: 0, //伸缩条开始位置（1-100），可以随时更改
            end: 100, //伸缩条结束位置（1-100），可以随时更改
          },
          {
            type: "slider", //图表下方的伸缩条
            show: true, //是否显示
            realtime: true, //拖动时，是否实时更新系列的视图
            start: 0, //伸缩条开始位置（1-100），可以随时更改
            end: 100, //伸缩条结束位置（1-100），可以随时更改
          },
        ],
        textStyle: {
          fontSize: util.vh(16),
          color: that.$store.state.themeName === "dark" ? "#fff" : "#000",
        },
        //图例-每一条数据的名字
        legend: {
          show: that.showLegend,
          data: ["风速功率", "实际功率", "最优功率"],
          right: "120",
          top: "5",
          icon: "circle",
          itemWidth: 6,
          inactiveColor:
            that.$store.state.themeName === "dark"
              ? partten.getColor("gray")
              : "#000",
          textStyle: {
            color:
              that.$store.state.themeName === "dark"
                ? partten.getColor("grayl")
                : "#000",
            fontSize: 12,
          },
        },
        grid: {
          top: 32,
          left: 40,
          right: 40,
          bottom: 24,
        },
        //x轴
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            data: that.xAxisData || [
              "0",
              "1",
              "2",
              "3",
              "4",
              "5",
              "6",
              "7",
              "8",
              "9",
              "10",
              "11",
              "12",
              "13",
              "14",
              "15",
              "16",
              "17",
              "18",
              "19",
              "20",
              "21",
              "22",
              "23",
              "24",
              "25",
            ],
            min: 0,
            axisLabel: {
              formatter: "{value}",
              fontSize: util.vh(14),
            },
            textStyle: {
              color:
                this.$store.state.themeName === "dark"
                  ? partten.getColor("gray")
                  : "#000",
            },
          },
          {
            // name: this.xTitle,
            show: false,
            type: "value",
            boundaryGap: false,
            // min: that?.xAxisData[0],
            min: 0,
            max: that?.xAxisData[that?.xAxisData?.length - 1],
            scale: true,
            axisLabel: {
              formatter: "{value}",
            },
            splitLine: {
              show: false,
            },
          },
        ],
        //y轴没有显式设置，根据值自动生成y轴
        yAxis: {
          splitLine: { show: false },
        },
        //数据-data是最终要显示的数据
        series: that.seriesData,
      };

      that.resize = function () {
        myChart.resize();
      };

      window.addEventListener("resize", that.resize);

      myChart.setOption(option);

      if (that.brushSelected) {
        myChart.off("brushSelected");
        myChart.on("brushSelected", (params) => {
          that.$emit("getSelected", params.batch || []);
        });
        myChart.dispatchAction({
          type: "takeGlobalCursor",
          // 如果想变为“可刷选状态”，必须设置。不设置则会关闭“可刷选状态”。
          key: "brush",
          brushOption: {
            // 参见 brush 组件的 brushType。如果设置为 false 则关闭“可刷选状态”。
            brushType: "polygon",
            // 参见 brush 组件的 brushMode。如果不设置，则取 brush 组件的 brushMode 设置。
            brushMode: "multiple",
          },
        });
      }
    },
  },
  created() {
    this.id = "chart-" + util.newGUID();
  },
  mounted() {
    this.$nextTick(() => {
      this.$el.style.width = this.width;
      this.$el.style.height = this.height;
      this.initChart();
    });
  },
  updated() {
    let myChart = echarts.init(document.getElementById(this.id));
    myChart.dispose();
    this.$nextTick(() => {
      this.initChart();
    });
  },
  unmounted() {
    window.removeEventListener("resize", this.resize);
  },
};
</script>

<style lang="scss">
.chart {
  width: 100%;
  height: 100%;
  display: inline-block;
}
</style>
