<template>
  <div
    class="dragLineChart"
    :style="{ width: '100%', 'min-height': height + 'px' }"
  >
    <div
      id="dragLineChart"
      :style="{ width: '100%', 'min-height': height + 'px' }"
    ></div>
    <div
      v-if="page > 5"
      :style="btnPageStyle"
      class="btn_page btn_prev flex items-center justify-center"
      @click="handlePage('prev')"
    >
      <i class="iconfont icon-jiantou2"></i>
    </div>
    <div
      v-if="page !== pages && pages > 0"
      :style="btnPageStyle"
      class="btn_page btn_next flex items-center justify-center"
      @click="handlePage('next')"
    >
      <i class="iconfont icon-jiantou2"></i>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
import * as echarts from "echarts";
import Color from "@/utils/color.js";

export default {
  name: "DragLineChart",
  props: {
    maxSize: {
      type: Number,
      default: 0,
    },
    interval: {
      type: Number,
      default: 0,
    },
    intervalList: {
      type: Array,
      default: () => [],
    },
    splitNumber: {
      type: String,
      default: "",
    },
    yAxisData: {
      type: Array,
      default: () => [],
    },
    lineData: {
      type: Array,
      default: () => [],
    },
    typeList: {
      type: Array,
      default: () => [],
    },
    page: {
      type: Number,
      default: 0,
    },
    pages: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      maxlength: 2880,
      height: 300,
      chart: null,
      btnPageStyle: {
        top: "120px",
      },
    };
  },
  watch: {
    yAxisData() {
      this.drawLine();
      this.chart.resize();
    },
  },
  mounted() {
    this.drawLine();
    const dom = document.querySelector("#__layout");
    dom.onscroll = this.handleScroll;
  },
  beforeDestroy() {
    const vm = this;
    if (vm.chart && !vm.chart.isDisposed()) {
      //  判断图形已初始化,且未销毁
      vm.chart.clear(); // //释放图形资源
      vm.chart.dispose(); // //释放图形资源
      window.removeEventListener("resize", vm.resizeFn);
    }
  },
  methods: {
    handleScroll(e) {
      const { scrollTop } = e.target;
      const { top } = document
        .querySelector(".dragLineChart")
        .getBoundingClientRect();
      const clientHeight = document.documentElement.clientHeight;
      if (scrollTop < (clientHeight - Math.abs(top)) / 2) {
        this.btnPageStyle.top = "120px";
      } else {
        this.btnPageStyle.top = scrollTop - 120 + "px";
      }
    },
    resizeFn() {
      this.chart.resize();
    },
    handlePage(type) {
      let { page, pages } = this;
      switch (type) {
        case "prev":
          if (page === 1) {
            return;
          }
          const remainder = page % 5;
          page = page > 10 ? page - 4 - (remainder ? remainder : 5) : 1;
          document.getElementById("__layout").scrollTop = 0;
          this.$emit("handlePage", page);
          this.btnPageStyle.top = "120px";
          break;
        case "next":
          if (page === pages) {
            return;
          }
          page += 1;
          document.getElementById("__layout").scrollTop = 0;
          this.$emit("handlePage", page);
          this.btnPageStyle.top = "120px";
          break;
        default:
          break;
      }
    },
    drawLine() {
      const vm = this;
      vm.chart = echarts.init(document.getElementById("dragLineChart"));
      const data = [];
      const startTime = 0;
      const { yAxisData } = vm;
      const categoryLen = yAxisData.length;
      const { lineData } = vm;
      const iDays = vm.interval / 60;
      const trueXLabel = this.intervalList;
      const echartHeight =
        categoryLen > 1
          ? categoryLen > 10
            ? 30 + 52 * categoryLen
            : 30 + 52 * categoryLen
          : 180; // 根据数据数量判断画布高度
      vm.height = echartHeight;
      const zoomStart =
        vm.intervalList.length > 3
          ? (100 * (vm.intervalList.length - 3)) / (vm.intervalList.length - 1)
          : 0;
      const minSpanZoom = parseInt(100 / (vm.intervalList.length - 1));
      const endNum = categoryLen > 10 ? 100 : 100;
      // 绘制图表
      echarts.util.each(lineData, (item, index) => {
        let baseTime = startTime;
        if (item.statusChangeList && item.statusChangeList.length > 0) {
          for (let i = 0; i < item.statusChangeList.length; i++) {
            const duration = !item.statusChangeList[i].duration
              ? 0
              : parseFloat(parseFloat(item.statusChangeList[i].duration) / 60);
            const {
              id,
              eqpStatusId,
              eqpStatus,
              statusStartTime,
              statusEndTime,
              last,
            } = item.statusChangeList[i];
            data.push({
              id,
              eqpStatusId,
              eqpStatus,
              eqpId: item.id,
              statusStartTime,
              statusEndTime,
              last,
              name: item.statusChangeList[i].statusName,
              value: [index, baseTime, (baseTime += duration), duration],
              durationMin: item.statusChangeList[i].durationMin,
              durationSec: item.statusChangeList[i].durationSec,
              itemStyle: {
                color: item.statusChangeList[i].statusColor
                  ? new Color().fromString(
                      item.statusChangeList[i].statusColor,
                      "0.6"
                    )
                  : "rgba(190,190,190,0.26)",
                borderColor:
                  item.statusChangeList[i].statusColor ||
                  "rgba(190,190,190, 0.26)",
              },
            });
          }
        }
      });
      vm.chart.off("click");
      vm.chart.setOption({
        tooltip: {
          formatter: (params) => {
            const _name =
              vm.typeList.find((item) => item.name === params.name) || {};
            return (
              (params.name ? params.marker : "") +
              (params.data.eqpStatus !== "EMPTY"
                ? `${params.name}: `
                : `无状态: `) +
              (params.data.durationMin > 0
                ? `${params.data.durationMin} ${vm.$t("EPMS_MINUTES")}`
                : "") +
              (params.data.durationSec > 0
                ? ` ${params.data.durationSec} ${vm.$t("SECONDS")}`
                : "") +
              (params.name
                ? `<br/>${vm.$t("START_TIME")}: ${
                    params.data.statusStartTime
                  }<br/>${vm.$t("END_TIME")}: ${params.data.statusEndTime}`
                : "")
            );
          },
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        grid: [
          {
            left: "1%",
            right: "30",
            top: "15",
            bottom: "40",
            containLabel: true,
            backgroundColor: "rgba(255,0,0,1)",
            borderWidth: 1,
            borderColor: "#ccc",
          },
        ],
        xAxis: {
          // x轴数据，参数配置
          scale: false,
          boundaryGap: false,
          min: 0,
          max: parseInt(vm.maxSize),
          interval: parseInt(vm.interval), // parseInt(vm.interval),
          splitNumber: 48, // parseInt(vm.splitNumber),
          // data: trueXLabel,
          // type: 'category',
          axisLine: {
            show: true,
            lineStyle: {
              color: "#e4edf2",
            },
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "#e4edf2",
            },
          },
          splitArea: {
            show: true,
            areaStyle: {
              color: ["#f1f7fb", "#f9fbfd"],
            },
          },
          axisLabel: {
            interval: 0,
            textStyle: {
              color: "#999",
            },
            formatter: (value, index) => {
              if (isNaN(index)) {
                return;
              }
              let texts = value;
              if (index === trueXLabel.length) {
                // value += 14;
              }
              const num = Math.round(value / 60);
              texts = trueXLabel[num];
              return texts;
            },
          },
        },
        yAxis: {
          // y轴数据，参数配置
          type: "category",
          axisLine: {
            show: true,
            lineStyle: {
              color: "#e4edf2",
            },
          },
          axisLabel: {
            show: true,
            interval: 0,
            textStyle: {
              color: "#999",
            },
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "#e4edf2",
            },
          },
          data: yAxisData,
        },
        dataZoom: [
          {
            type: "slider",
            // xAxisIndex: [0],
            zoomLock: false,
            show: true,
            filterMode: "weakFilter",
            bottom: 10,
            height: 20,
            start: zoomStart,
            end: 100,
            minSpan: minSpanZoom,
            borderColor: "transparent",
            backgroundColor: "#f9fbfd",
            labelFormatter: "",
            zoomOnMouseWheel: false,
            moveOnMouseMove: true, //鼠标滚轮触发滚动
            moveOnMouseWheel: true,
            brushSelect: false,
          },
          {
            type: "slider",
            zoomLock: false,
            show: false, // 是否显示右侧拖拽控件
            yAxisIndex: [0],
            right: 5,
            width: 20,
            start: 0,
            end: endNum,
            borderColor: "transparent",
            backgroundColor: "#f1f7fb",
            labelFormatter: "",
            moveOnMouseMove: true,
            moveOnMouseWheel: true,
          },
          // {
          //   type: "slider",
          //   yAxisIndex: [0],
          //   start: 0,
          //   end: endNum,
          //   zoomOnMouseWheel: 'ctrl',
          //   moveOnMouseMove: 'ctrl',  //鼠标滚轮触发滚动
          //   moveOnMouseWheel: 'ctrl'
          // },
        ],
        series: [
          {
            type: "custom",
            renderItem: (params, api) => {
              const categoryIndex = api.value(0);
              const start = api.coord([api.value(1), categoryIndex]);
              const end = api.coord([api.value(2), categoryIndex]);
              const height = 22; // api.size([0, 1])[1] * 0.6;

              const rectShape = echarts.graphic.clipRectByRect(
                {
                  x: start[0],
                  y: start[1] - height / 2,
                  width: end[0] - start[0],
                  height,
                },
                {
                  x: params.coordSys.x,
                  y: params.coordSys.y,
                  width: params.coordSys.width,
                  height: params.coordSys.height,
                }
              );
              return (
                rectShape && {
                  type: "rect",
                  shape: rectShape,
                  style: api.style(),
                }
              );
            },
            label: {
              normal: {
                show: true,
                position: "inside",
                formatter: (params) => {
                  if (params.name !== "NONE") {
                    const labelText =
                      params.data.durationMin > 0
                        ? params.data.durationMin + "m"
                        : "";
                    return labelText;
                  }
                  return "";
                },
                fontSize: 12,
                color: "#fff",
              },
            },
            encode: {
              x: [1, 2],
              y: 0,
            },
            data,
          },
        ],
        animationEasing: 'elasticOut',
      });
      vm.chart.on("click", (params) => {
        if (params.data?.eqpStatus === "EMPTY") return;
        this.$emit("click", params.data);
      });
      window.addEventListener("resize", vm.resizeFn);
      setTimeout(() => {
        vm.chart.resize();
      }, 100);
    },
  },
};
/* eslint-enable */
</script>
<style lang="less" scoped>
.dragLineChart {
  position: relative;
  .btn_page {
    width: 55px;
    height: 55px;
    opacity: 1;
    background: rgba(0, 0, 0, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.6);
    border-radius: 50%;
    position: absolute;
    cursor: pointer;
    transition: all 0.35s ease-in-out;
    .iconfont {
      color: #fff;
    }
    &:hover {
      background: #0ea8d0;
    }
  }
  .btn_prev {
    left: 24px;
    transform: rotateY(180deg);
  }
  .btn_next {
    right: 24px;
  }
}
</style>
