<template>
  <div class="container-echart">
    <div :id="'echart' + timeId" class="interface-echart"></div>
  </div>
</template>
<script lang="ts" setup>
import * as echarts from "echarts";
import { EChartsType } from "echarts";
import { onMounted, ref, watch, onBeforeUnmount, nextTick } from "vue";

const props = defineProps({
  NamechartData: {
    // 柱形图x轴数据
    type: Array,
    default: true,
  },
  ArrOneData: {
    // 柱形图x轴数据
    type: Array,
    default: true,
  },
  ArrTwoData: {
    // 柱形图x轴数据
    type: Array,
    default: true,
  },
});

let myEchart: EChartsType;
const timeId = ref(Math.floor(new Date().getTime() * Math.random())); // 使该图表保持唯id
const myEchartData = () => {
  const option = {
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["翻转", "水浸", "水位"],
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: ["一月", "二月", "三月", "四月", "五月", "六月", "七月"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "翻转",
        type: "line",
        stack: "Total",
        data: [120, 132, 101, 134, 90, 230, 210],
      },
      {
        name: "水浸",
        type: "line",
        stack: "Total",
        data: [220, 182, 191, 234, 290, 330, 310],
      },
      {
        name: "水位",
        type: "line",
        stack: "Total",
        data: [150, 232, 201, 154, 190, 330, 410],
      },
    ],
  };
  // { notMerge: true } 解决删除数据时,数据不刷新的问题
  myEchart.setOption(option, { notMerge: true });
};

watch(
  //监控数据变化
  () => props.NamechartData,
  () => {
    setTimeout(() => {
      myEchartData();
    }, 500);
  },
  { deep: true }
);

watch(
  //监控数据变化
  () => props.ArrOneData,
  () => {
    setTimeout(() => {
      myEchartData();
    }, 500);
  },
  { deep: true }
);

watch(
  //监控数据变化
  () => props.ArrTwoData,
  () => {
    setTimeout(() => {
      myEchartData();
    }, 500);
  },
  { deep: true }
);

onMounted(() => {
  setTimeout(() => {
    const dom = document.getElementById(`echart${timeId.value}`) as any;
    myEchart = echarts.init(dom);
    myEchartData();
  }, 500);

  // 当窗口发生变化时
  window.addEventListener("resize", () => {
    myEchart.resize();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", () => {
    myEchart.resize();
  });
});
</script>
<style scoped lang="scss">
.container-echart {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.interface-echart {
  width: 100%;
  height: 100%;
}
</style>
