<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 {
  name: "multiple-bar-chart",
  componentName: "multiple-bar-chart",
  props: {
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "800px",
    },
    lineData: {
      type: Array,
      default: () => [],
    },
    areaData: {
      type: Array,
      default: () => [],
    },
    // 单位
    units: {
      type: Array,
      default: () => ["健康趋势", "风机健康状态数量"],
    },
    // 显示 legend
    showLegend: {
      type: Boolean,
      default: true,
    },
    // 颜色
    color: {
      type: Array,
      default: () => ["#1c99ff", "#3d54be", "#f8de5b"],
    },
  },
  data() {
    return {
      id: "",
      chart: null,
    };
  },
  computed: {
    legend() {
      let data = [];
      this.lineData.forEach((value, index) => {
        data.push(value.text);
      });
      return data;
    },
    xAxisData() {
      let data = [];
      if (this.lineData.length > 0)
        this.lineData[0].value.forEach((value, index) => {
          data.push(value.text);
        });
      return data;
    },
    areaChartData() {
      let data = [];
      if (this.areaData && this.areaData.length) {
        for (var i = 0; i < this.areaData.length; i++) {
          let item = this.areaData[i];
          var color = item.color;
          data.push({
            name: item.name,
            value: [item.start, item.end, item.end - item.start],
            itemStyle: {
              normal: {
                color: color,
              },
            },
            exData: item,
          });
        }
      }
      return data;
    },
    areaMax() {
      let max = 0;
      this.areaData.forEach((value) => {
        if (max < value.end) max = value.end;
      });
      return max;
    },
  },
  methods: {
    renderItem(params, api) {
      var start = api.coord([api.value(0)]);
      var end = api.coord([api.value(1)]);
      var height = api.size([0, 1])[1];

      var rectShape = echarts.graphic.clipRectByRect(
        {
          x: start[0],
          y: start[1] - height / 2,
          width: end[0] - start[0],
          height: height,
        },
        {
          x: params.coordSys.x,
          y: params.coordSys.y,
          width: params.coordSys.width,
          height: params.coordSys.height,
        }
      );
      return (
        rectShape && {
          type: "rect",
          transition: ["shape"],
          shape: rectShape,
          style: api.style(),
        }
      );
    },
    initChart() {
      let that = this;
      let chart = echarts.init(this.$el);

      let option = {
        color: this.color,
        grid: {
          left: 40,
          right: 40,
          bottom: 40,
          top: 32,
          containLabel: true,
        },
        tooltip: {
          show: true,
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
          backgroundColor:
            this.$store.state.themeName === "dark"
              ? "rgba(0,0,0,0.4)"
              : "rgba(255,255,255,0.5)",
          borderColor:
            this.$store.state.themeName === "dark"
              ? partten.getColor("gray")
              : "#000",
          textStyle: {
            color: this.$store.state.themeName === "dark" ? "#fff" : "#000",
            fontSize: 14,
          },
          formatter: function (params) {
            var htmlStr = `<div style='margin-bottom:5px'>${params[0].axisValue}</div>`;
            for (var i = 0; i < params.length; i++) {
              htmlStr += `<div style='margin-bottom:2px'>`;
              var param = params[i];
              var seriesName = param.seriesName; //图例名称
              var value = param.value; //y轴值
              var mark = param.marker; //点
              var unit = `<span style='font-size:12px'>${
                seriesName === "风速" ? "m/s" : "MW"
              }</span>`;

              htmlStr += mark; //一个点
              htmlStr += `${seriesName} : ${
                value != null ? value + unit : "--"
              }`; //圆点后面显示的文本
              htmlStr += "</div>";
            }
            return htmlStr;
          },
        },
        legend: {
          show: this.showLegend,
          data: this.legend,
          right: 120,
          icon: "ract",
          itemWidth: 8,
          itemHeight: 8,
          inactiveColor:
            this.$store.state.themeName === "dark"
              ? partten.getColor("gray")
              : "#000",
          textStyle: {
            color:
              this.$store.state.themeName === "dark"
                ? partten.getColor("grayl")
                : "#000",
            fontSize: 12,
          },
        },
        xAxis: [
          {
            type: "category",
            axisLabel: {
              color:
                this.$store.state.themeName === "dark"
                  ? partten.getColor("gray")
                  : "#000",
            },
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            data: this.xAxisData,
          },
          {
            show: false,
            min: 0,
            max: this.areaMax,
            axisLabel: {
              show: false,
              formatter: function (val) {
                return Math.max(0, val - 0) + " ms";
              },
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: this.units[0],
            axisLabel: {
              formatter: "{value} ",
              color:
                this.$store.state.themeName === "dark"
                  ? partten.getColor("gray")
                  : "#000",
            },
            axisLine: {
              type: "dashed",
              lineStyle: {
                color:
                  this.$store.state.themeName === "dark"
                    ? partten.getColor("gray")
                    : "#000",
              },
              width: 5,
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              lineStyle: {
                type: "dashed",
                dashOffset: 10,
                color:
                  this.$store.state.themeName === "dark"
                    ? partten.getColor("gray")
                    : "#000" + 80,
              },
            },
          },
          {
            data: [
              this.areaData && this.areaData.length
                ? this.areaData[0].name
                : "",
            ],
            axisLabel: { show: false },
          },
        ],
        series: [],
      };

      // line data
      if (this.lineData.length > 0) {
        this.lineData.forEach((value, index) => {
          option.series.push({
            name: value.text,
            type: "line",
            data: value.value,
            smooth: true, //平滑展示
            yAxisIndex: 0,
          });
        });
      }

      // 区域
      if (this.areaData && this.areaData.length > 0) {
        option.series.push({
          type: "custom",
          renderItem: this.renderItem,
          yAxisIndex: 1,
          xAxisIndex: 1,
          itemStyle: {
            opacity: 0.2,
          },
          tooltip: {
            show: false,
            formatter: function (params) {
              return params.marker + params.name + ": " + params.value[2] + "s";
            },
          },
          encode: {
            x: [1, 2],
            y: 0,
          },
          data: this.areaChartData,
        });
      }
      chart.setOption(option);

      return chart;
    },
  },
  emits: {
    areaClick: null,
  },
  created() {
    this.id = "pie-chart-" + util.newGUID();
  },
  mounted() {
    this.$nextTick(() => {
      this.$el.style.width = this.width;
      this.$el.style.height = this.height;
      let that = this;
      let chart = this.initChart();
      chart.on("click", function (e, p) {
        console.log(e);
        if (e.seriesType == "custom") {
          that.$emit("areaClick", { data: e.data.exData });
        }
      });
    });
  },
  updated() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  watch: {
    "$store.state.themeName"() {
      this.initChart();
    },
  },
};
</script>

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