<template>
  <div class="hxPressInfo">
    <div ref="hxPressRef" id="hxPressEchart" class="hxPressEchart">
      暂无数据
    </div>
  </div>
</template>
<script setup>
import * as echarts from "echarts";
import { ref, onMounted, onUnmounted, watchEffect } from "vue";
import { getPressChart, getPressChartPolling } from "@/api/monitoring/visual";
import { debounce } from "@/utils/index";
import useCounter from "@/store/modules/date";
const counterStore = useCounter();
const hxPressRef = ref(null);
const hxPressEcharts = ref();
const currentEndTime = ref();
const timer = ref();
const isCurrentRoute = ref(true);
const mainInfoList = ref();
const deviceUuid = ref();

const colors = [
  "#5470c6",
  "#91cc75",
  "#fac858",
  "#1a94bc",
  "#f26b1f",
  "#5bae23",
];
const options = {
  color: colors,
  title: {
    text: "",
    top: 10,
    left: 20,
    textStyle: {
      fontSize: 14,
      fontWeight: "normal",
      color: "#D1E1FF",
    },
  },
  tooltip: {
    trigger: "axis",
    borderColor: "gray",
    backgroundColor: "rgba(36, 52, 78, 0.8)",
    backdropFilter: "blur(10px)",
    boxShadow: "0 0 80px rgba(0, 0, 0, 0.25)",
    textStyle: {
      color: "#fff",
    },
    axisPointer: {
      type: "cross",
      animation: false,
    },
  },
  legend: {
    data: [""],
    top: 10,
    right: 10,
    itemWidth: 11,
    itemHeight: 2,
    textStyle: {
      color: "#D1E1FF",
      fontSize: 14,
    },
  },
  grid: {
    top: "20%",
    left: "2%",
    right: "2%",
    bottom: "15%",
    containLabel: true,
  },
  dataZoom: [
    {
      type: "inside",
      start: 0,
      end: 100,
    },
    {
      start: 0,
      end: 100,
    },
  ],
  xAxis: {
    type: "time",
    splitLine: {
      show: false,
    },
    axisLabel: {
      show: true,
      color: "#D1E1FF",
    },
    axisLine: {
      lineStyle: {
        color: "#904FC5",
      },
    },
  },
  yAxis: [{}],
  series: [{}],
};

onMounted(() => {});
watchEffect(() => {
  const dataStr = counterStore.orgStr;
  if (dataStr.assetCode != "") {
    deviceUuid.value = dataStr.assetCode;
    getDeviceInfo();
  }
});
function getDeviceInfo() {
  //获取折线图数据
  const params = {
    assetCode: deviceUuid.value,
  };
  getPressChart(params).then((res) => {
    if (res.code === 200) {
      mainInfoList.value = res.data.mainInfos;
      if (res.data.additionalInfo != null) {
        currentEndTime.value = res.data.additionalInfo.endTime;
        debounceClick();
      }
      init(res.data);
    }
  });
}

const debounceClick = debounce(() => {
  getDevicePolling();
}, 10000);

function getDevicePolling() {
  //轮询获取折线图数据
  const params = {
    assetCode: deviceUuid.value,
  };
  getPressChartPolling(params).then((res) => {
    if (res.code === 200) {
      if (isCurrentRoute.value) {
        timer.value = setTimeout(async () => {
          await (timer.value && clearTimeout(timer.value));
          await getDevicePolling();
        }, 5000);
      }
      if (res.data.additionalInfo != null) {
        currentEndTime.value = res.data.additionalInfo.endTime;
        // console.log(currentEndTime.value, res.data.mainInfos);
      }
      options.series.forEach((originalObj) => {
        res.data.mainInfos.forEach((newObj) => {
          if (originalObj.name === newObj.name) {
            newObj.data.map((item) => {
              originalObj.data.shift();
              originalObj.data.push(item);
            });
          }
        });
      });
      // console.log(options.series);
      const chart = echarts.init(hxPressRef.value);
      chart.setOption(options);
      // mainInfoList.value = res.data.mainInfos;
      // init(res.data);
    } else {
      clearTimeout(timer.value);
    }
  });
}
function init(data) {
  //折线图实例化
  const chart = echarts.init(hxPressRef.value);
  hxPressEcharts.value = chart;
  options.yAxis = [];
  options.legend.data = [];
  options.series = [];
  if (data.mainInfos.length === 0) {
    options.title.text = "暂无数据";
    chart.clear();
    chart.resize();
    // console.log('options--', options);
    chart.setOption(options);
    return;
  }
  options.title.text = data.additionalInfo.name;
  data.units.map((item, index) => {
    const offsetData = index === 0 ? 0 : index === 1 ? 0 : (index - 1) * 100;
    // console.log('offsetData--', offsetData);
    options.yAxis.push({
      type: "value",
      name: `${item.name}(${item.unit})`,
      position: `${index === 0 ? "left" : "right"}`,
      alignTicks: true,
      offset: offsetData,
      scale: true, //自适应
      // minInterval: 1, //最小间距
      // min: item.unitMin, //最小值
      // max: item.unitMax, //最大值
      // interval: 10, //刻度间隔
      nameTextStyle: {
        color: "#D1E1FF",
        fontSize: 12,
        padding: [0, 0, 0, 0], //name文字位置 对应 上右下左
      },
      axisTick: {
        // 轴刻度
        show: false,
      },
      axisLabel: {
        show: true,
        color: "#D1E1FF",
      },
      splitLine: {
        // 网格线
        show: true,
        lineStyle: {
          //分割线
          color: "#D1E1FF",
          width: 1,
          opacity: 0.2,
        },
      },
    });
  });
  data.mainInfos.map((item, index) => {
    options.legend.data.push(item.name);
    options.series.push({
      name: item.name,
      type: "line",
      smooth: true,
      showSymbol: false,
      yAxisIndex: item.index,
      data: item.data,
      tooltip: {
        valueFormatter: function (value) {
          return value === null ? "--" : value + " " + item.paramUnit;
        },
      },
    });
  });
  chart.clear();
  chart.resize();
  window.addEventListener("resize", function () {
    chart.resize();
  });
  // console.log('options--', options);
  chart.setOption(options);
}
onUnmounted(() => {
  //组件注销前清除setTimeout
  if (timer.value !== null || timer.value !== undefined) {
    clearTimeout(timer.value);
  }
  if (hxPressEcharts.value) {
    //echarts销毁函数
    echarts.dispose(hxPressEcharts.value);
    hxPressEcharts.value = null;
  }
});
</script>
<style lang="scss" scoped>
.hxPressInfo {
  width: 100%;
  height: 318px;
  .hxPressEchart {
    width: 100%;
    height: 318px;
    line-height: 318px;
    text-align: center;
    font-size: 16px;
    color: #d2def6;
    z-index: 99999;
  }
}
</style>
