<template>
  <div ref="chartRef" class="echarts-base" :style="{ width, height }"></div>
</template>

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

const props = defineProps({
  option: {
    type: Object,
    required: true
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '400px'
  }
})

const emits = defineEmits(['chartReady', 'chartClick'])

const chartRef = ref<HTMLElement | null>(null)
let myChart: echarts.ECharts | null = null

const initChart = () => {
  nextTick(() => {
    if (chartRef.value) {
      myChart = echarts.init(chartRef.value)
      myChart.setOption(props.option)
      emits('chartReady', myChart)
      myChart.on('click', (params) => {
        emits('chartClick', params)
      })
    }
  })
}

const resizeChart = () => {
  myChart?.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeChart)
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart)
  myChart?.dispose()
  myChart = null
})

watch(
  () => props.option,
  () => {
    if (myChart) {
      myChart.setOption(props.option)
    }
  },
  { deep: true }
)
</script>

<style scoped>
.echarts-base {
  width: 100%;
  height: 100%;
}
</style>