<template>
  <div ref="chartRef" class="chart-line" data-testid="chart-line-container"></div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref, watch } from "vue";
import * as echarts from "echarts";
import { getLineOption } from "@/utils/chart";

const props = defineProps({
  chartData: {
    type: Array,
    default: () => [],
  },
});



const chartRef = ref([]);
let chartInstance = null;

watch(
  () => props.chartData,
  () => {
    initChart();
  },
  { deep: true }
);

const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
    const xData = props.chartData.map((item) => item.date);
    const seriesData = props.chartData.map((item) => item.healthDegree);
    const option = getLineOption(xData, seriesData);
    chartInstance.setOption(option);
  }
};

onMounted(() => {
  if (props.chartData) {
    initChart();
  }
  window.addEventListener("resize", () => {
    chartInstance?.resize();
  });
});

onBeforeUnmount(() => {
  chartInstance?.dispose();
});
</script>

<style scoped>
.chart-line {
  width: 100%;
  height: calc(100% - 22px);
}
</style>
