<script lang="ts" setup>
defineExpose({loadChart, carousel})

import * as echarts from "echarts";
import {waterQualitys} from "@/utils/unit.js";
import {nextTick, onMounted, onUnmounted, ref} from "vue";

const chartRef = ref(null)
let chart = null
let timer = undefined

async function loadChart(option) {
  if (!chart) {
    await nextTick(); // 确保DOM已经渲染完成
    chart = echarts.init(chartRef.value);
  }
  chart.setOption(option, true);
  setTimeout(() => chart.resize(), 1000)
}

function reloadChart() {
  const checkAndResize = () => {
    if (chart) {
      chart.resize();
    } else {
      setTimeout(checkAndResize, 1000);
    }
  };
  checkAndResize();
}

/* 轮播 */
function carousel(timeout = 5000, yAxisChange = false) {
  const checkAndCarousel = () => {
    if (chart) {
      // 获取legend的data
      const legendData = chart.getOption().legend[0].data
      // 首次总是从0开始的
      let i = 0
      // 开始轮播
      timer = setInterval(() => {
        // 激活
        chart.dispatchAction({
          type: 'legendToggleSelect',
          name: legendData[++i % legendData.length]
        })
      }, 10000)

      if (yAxisChange) {
        chart.on('legendselectchanged', function (params) {
          let selected = undefined;
          for (let key in params.selected) {
            if (params.selected[key] === true) {
              selected = key;
              break
            }
          }

          let field = waterQualitys.find(i => i.label === selected)
          if (field) {
            chart.setOption({yAxis: {name: field.unit,}});
          }
        });
      }
    } else {
      setTimeout(checkAndCarousel, 1000);
    }
  }
  checkAndCarousel();
}

onMounted(() => chartRef.value?.addEventListener("resize", reloadChart))
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }

  chartRef.value?.removeEventListener("resize", reloadChart)
  if (chart && chart.dispose) {
    chart.dispose();
  }
})
</script>

<template>
  <div ref="chartRef" class="chart-wrapper"></div>
</template>
<style lang="scss" scoped>
.chart-wrapper {
  width: 100%;
  height: 100%;
}
</style>


