<script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount, ShallowRef, shallowRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { debounce } from 'lodash-es'
import type { EChartsType } from 'echarts/types/dist/core'
import { echarts, type EChartsOption } from '@/utils/echarts'

interface Props {
  width?: string
  height?: string
  option: EChartsOption
}

const props = withDefaults(defineProps<Props>(), {
  width: '100%',
  height: '100%',
  option: () => ({}),
})

const { t } = useI18n()

const customChartRef = ref<HTMLDivElement>()

const customChart: ShallowRef<EChartsType | null | undefined> = shallowRef(null)

watch(
  () => props,
  () => {
    drawEChart()
  },
  {
    deep: true,
  },
)

const chartResizeHandler = debounce(() => {
  customChart.value?.resize()
}, 200)

onMounted(() => {
  drawEChart()
  window.addEventListener('resize', chartResizeHandler)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', chartResizeHandler)
  customChart.value?.dispose()
})

function drawEChart() {
  if (customChart.value) {
    customChart.value.dispose()
  }

  customChart.value = echarts.init(customChartRef.value as HTMLDivElement, null, { renderer: 'svg' })

  customChart.value?.setOption(props.option, true)
}

function echartShowLoading() {
  customChart.value?.showLoading({
    text: t('common_module.loading'),
    color: '#000DFF',
    textColor: '#333',
    lineWidth: 3,
  })
}

function echartHideLoading() {
  customChart.value?.hideLoading()
}

defineExpose({
  echartShowLoading,
  echartHideLoading,
})
</script>

<template>
  <div ref="customChartRef" :style="{ height: height, width: width }" :option="option" />
</template>
