<template>
  <div class="component_box" style="padding-top: 10px">
    <div class="header">{{ title }}</div>
    <div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane
          v-for="t in types"
          :key="t.value"
          :label="t.text"
          :name="t.value"
        ></el-tab-pane>
      </el-tabs>
    </div>
    <div
      ref="chart"
      style="width: 100%; height: calc(100% - 40px)"
      @mouseenter="handleMouseEnter"
      @mouseleave="handleMouseLeave"
    ></div>
  </div>
</template>
<script>
const types = [
  {
    text: "近七天",
    value: "0",
  },
  {
    text: "近七周",
    value: "1",
  },
  {
    text: "近半年",
    value: "2",
  },
];
import { alarmTrend } from "@/api/iot/board";
import * as echarts from "echarts";
import { getNextPeriod } from "@/views/board/utils.js";
export default {
  props: {
    orgId: {
      type: String,
      isRequired: true,
    },
  },
  data() {
    return {
      types,
      data: {
        date: [], //x轴的日期
        total: [], //报警总数
        countByType: [], //按分类统计的报警总数
      },
      title: "近七天告警趋势",
      isMouseOver: false,
      activeName: types[0].value,
    };
  },

  components: {},

  computed: {},

  watch: {
    orgId: {
      deep: true,
      handler(val) {
        this.resetTimer();
        this.getData();
      },
    },
    data: {
      deep: true,
      handler() {
        this.initMap();
      },
    },
  },

  created() {
    this.maxDisplay = 16;
    this.refreshTime = 1 * 60 * 1000;
    this.isMouseOver = false;
  },

  async mounted() {
    window.addEventListener("resize", this.windowResize);
  },
  beforeDestroy() {
    this.timer && clearInterval(this.timer);
    this.timer = null;

    window.removeEventListener("resize", this.windowResize);
  },

  methods: {
    handleClick() {
      this.title = types[this.activeName].text + "告警趋势";
      this.resetTimer();
      this.getData();
    },
    handleMouseEnter() {
      this.isMouseOver = true;
    },
    handleMouseLeave() {
      this.isMouseOver = false;
    },
    async getData() {
      let r = (await alarmTrend(this.orgId, this.activeName)).data;
      let data = {
        date: [], //x轴的日期
        total: [], //报警总数
        countByType: [], //按分类统计的报警总数
      };

      let monitorCount = [];
      let fireCount = [];
      let environmentCount = [];
      for (let item of r) {
        data.total.push(item.total);
        monitorCount.push(item.monitorCount);
        fireCount.push(item.fireCount);
        environmentCount.push(item.environmentCount);

        data.date.push(item.date);
      }

      data.countByType.push(monitorCount);
      data.countByType.push(fireCount);
      data.countByType.push(environmentCount);

      this.data = data;
    },

    windowResize() {
      this.myChart && this.myChart.resize();
    },
    initMap() {
      this.myChart && this.myChart.dispose();
      let c = this.$refs["chart"];

      // 基于准备好的dom，初始化echarts实例
      this.myChart = echarts.init(c);

      var data = {
        id: "multipleBarsLines",
        title: types[this.activeName].text + "告警趋势",
        legendBar: ["报警总数"],
        symbol: "", //数值是否带百分号        --默认为空 ''
        legendLine: ["监控设备", "消防设备", "环境监测"],
        // xAxis: ["9月19", "9月20", "9月21", "9月22", "9月23", "9月24", "9月25"],
        // yAxis: [[8, 10, 10, 11, 4, 13, 8]],
        // lines: [
        //     [4, 3, 2, 4, 2, 1, 1],
        //     [2, 1, 4, 2, 3, 2, 4],
        //     [1, 0, 2, 1, 1, 2, 1],
        // ],
        barColor: ["#3FA7DC", "#7091C4", "#5170A2"], //柱子颜色 必填参数
        lineColor: ["#D9523F"], // 折线颜色
      };
      /////////////end/////////

      var myData = (() => {
        var yAxis = [this.data.total] || [];
        var lines = this.data.countByType || [];
        var legendBar = data.legendBar || [];
        var legendLine = data.legendLine || [];
        var symbol = data.symbol || " ";
        var seriesArr = [];
        var legendArr = [];

        yAxis &&
          yAxis.forEach((item, index) => {
            legendArr.push({
              name: legendBar && legendBar.length > 0 && legendBar[index],
            });
            seriesArr.push({
              name: legendBar && legendBar.length > 0 && legendBar[index],
              type: "bar",
              barGap: "0.5px",
              data: item,
              barWidth: data.barWidth || 12,
              label: {
                show: true,
                formatter: "{c}" + symbol,
                position: "top",
                color: "#fff",
                fontStyle: "normal",
                fontFamily: "微软雅黑",
                textAlign: "left",
                fontSize: 11,
              },
              itemStyle: {
                borderRadius: 4,
                color: data.barColor[index],
              },
            });
          });

        lines &&
          lines.forEach((item, index) => {
            legendArr.push({
              name: legendLine && legendLine.length > 0 && legendLine[index],
            });
            seriesArr.push({
              name: legendLine && legendLine.length > 0 && legendLine[index],
              type: "line",
              data: item,
              itemStyle: {
                color: data.lineColor[index],
                lineStyle: {
                  width: 3,
                  type: "solid",
                },
              },
              label: {
                show: false, //折线上方label控制显示隐藏
                position: "top",
              },
              symbol: "circle",
              symbolSize: 10,
            });
          });

        return {
          seriesArr,
          legendArr,
        };
      })();
      //   console.info(myData);
      let option = {
        // title: {
        //   show: false,
        //   top: "5%",
        //   left: "3%",
        //   text: data.title,
        //   textStyle: {
        //     fontSize: 18,
        //     color: "#fff",
        //   },
        //   subtext: data.subTitle,
        //   link: "",
        // },
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            var time = "";
            var str = "";
            for (var i of params) {
              time = i.name.replace(/\n/g, "") + "<br/>";
              if (i.data == "null" || i.data == null) {
                str += i.seriesName + "：无数据" + "<br/>";
              } else {
                str += i.seriesName + "：" + i.data + data.symbol + "<br/>";
              }
            }
            return time + str;
          },
          axisPointer: {
            type: "none",
          },
        },
        legend: {
          right: data.legendRight || "30%",
          top: "3%",
          right: "5%",
          itemGap: 16,
          itemWidth: 10,
          itemHeight: 10,
          data: myData.legendArr,
          textStyle: {
            color: "#fff",
            fontStyle: "normal",
            fontFamily: "微软雅黑",
            fontSize: 12,
          },
        },
        grid: {
          x: 30,
          y: 60,
          x2: 30,
          y2: 60,
        },
        xAxis: {
          type: "category",
          data: this.data.date,
          axisTick: {
            show: false,
          },

          axisLine: {
            show: true,
            lineStyle: {
              color: "#1AA1FD",
            },
            symbol: ["none", "arrow"],
          },
          axisLabel: {
            show: true,
            interval: "0",
            lineHeight: 16,
            padding: [2, 2, 0, 2],
            height: 50,
            fontSize: 12,
            rich: {
              Sunny: {
                height: 50,
                // width: 60,
                padding: [0, 5, 0, 5],
                align: "center",
              },
            },
            formatter: function (params, index) {
              var newParamsName = "";
              var splitNumber = 6;
              var paramsNameNumber = params && params.length;
              //   if (paramsNameNumber && paramsNameNumber <= 4) {
              //     splitNumber = 4;
              //   } else if (paramsNameNumber >= 5 && paramsNameNumber <= 7) {
              //     splitNumber = 5;
              //   } else if (paramsNameNumber >= 8 && paramsNameNumber <= 9) {
              //     splitNumber = 5;
              //   } else if (paramsNameNumber >= 10 && paramsNameNumber <= 14) {
              //     splitNumber = 5;
              //   } else {
              //     params = params && params.slice(0, 15);
              //   }

              var provideNumber = splitNumber; //一行显示几个字
              var rowNumber = Math.ceil(paramsNameNumber / provideNumber) || 0;
              if (paramsNameNumber > provideNumber) {
                for (var p = 0; p < rowNumber; p++) {
                  var tempStr = "";
                  var start = p * provideNumber;
                  var end = start + provideNumber;
                  if (p == rowNumber - 1) {
                    tempStr = params.substring(start, paramsNameNumber);
                  } else {
                    tempStr = params.substring(start, end) + "\n";
                  }
                  newParamsName += tempStr;
                }
              } else {
                newParamsName = params;
              }
              params = newParamsName;
              return "{Sunny|" + params + "}";
            },
            color: "#1AA1FD",
          },
        },
        yAxis: {
          axisLine: {
            show: true,
            lineStyle: {
              color: "#1AA1FD",
            },
            symbol: ["none", "arrow"],
          },
          type: "value",
          axisTick: {
            show: false,
          },
          axisLabel: {
            show: false,
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: "#1AA1FD",
              type: "solid",
            },
          },
        },
        series: myData.seriesArr,
      };
      // 使用刚指定的配置项和数据显示图表。
      if (option && typeof option === "object") {
        this.myChart.setOption(option);
      }
    },

    resetTimer() {
      this.timer && clearInterval(this.timer);
      this.timer = setInterval(() => {
        if (this.isMouseOver) {
          return;
        }
        this.activeName = getNextPeriod(this.types, this.activeName);
        this.getData();
      }, this.refreshTime);
    },
  },
};
</script>
<style scoped src="./../css/index.css"></style>
<style lang="scss" scoped>
.header {
  position: absolute;
  top: calc(15px + 20px);
  left: calc(18px + 3%);
  font-size: 20px;
  // font-weight: 700;
}
.component_box {
  ::v-deep .el-tabs__nav-scroll {
    justify-content: right !important;
  }
}
</style>
