<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import * as echarts from "echarts";

const chartData = defineProps<{
  xData: Array<string>;
  yData: Array<{ name: string; value: Array<number> }>;
  title?: string;
  per?: boolean;
  clickable?: boolean;
  smooth?: boolean;
  spanLimit?: number;
  setIndex?: (e: number) => void;
  defaultIndex?: boolean;
}>();
const chart = ref();
let myChart: echarts.EChartsType;
const setOption = () => {
  const option = {
    title: {
      text: chartData.title,
    },
    tooltip: {
      trigger: "axis",
    },
    grid: {
      left: "10%",
      right: "5%",
      top: "10%",
      bottom: "10%",
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: chartData.xData,
    },
    yAxis: {
      type: "value",
      max: chartData.per ? 100 : "dataMax",
      axisLabel: {
        formatter: chartData.per ? "{value}%" : "{value}",
      },
    },
    series: chartData.yData.map((e) => {
      return {
        name: e.name,
        data: e.value,
        smooth: chartData.smooth,
        type: "line",
      };
    }),
    dataZoom: {
      type: "inside",
      maxValueSpan: chartData.spanLimit || chartData.xData.length,
      minValueSpan: 5,
      startValue:
        chartData.spanLimit && chartData.xData.length > chartData.spanLimit
          ? chartData.xData.length - 1 - chartData.spanLimit
          : 0,
    },
  };
  myChart.setOption(option);
};
const init = () => {
  // const myChart = echarts.init(chart.value);
  window.onresize = () => myChart.resize();
  setOption();
  if (chartData.clickable) {
    myChart.off("click");
    myChart.getZr().on("click", function (params) {
      const pointInPixel = [params.offsetX, params.offsetY];
      if (myChart && myChart.containPixel("grid", pointInPixel)) {
        let xIndex = myChart.convertFromPixel({ seriesIndex: 0 }, [
          params.offsetX,
          params.offsetY,
        ])[0];
        if (chartData.setIndex) {
          chartData.setIndex(xIndex);
        }
      }
    });
    if (!chartData.defaultIndex) {
      chartData.setIndex?.(chartData.xData.length - 1);
    }
  }
};
onMounted(() => {
  myChart = echarts.init(chart.value);
  init();
});
watch(
  () => chartData.xData,
  () => setOption(),
);
</script>

<template>
  <div ref="chart" style="width: 100%; height: 100%" v-if="xData.length"></div>
  <el-empty v-else description="暂无数据"></el-empty>
</template>

<style scoped></style>
