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

type Props = {
	data: string
}

const prop = defineProps<Props>()

let instance: echarts.ECharts
const dom = ref<HTMLDivElement>()

const resizeHandler = () => {
	instance?.resize()
}

const showOrigin = ref(false)

const setOption = () => {
	let data: echarts.EChartsOption
	try {
		data = JSON.parse(decodeURIComponent(prop.data))
	} catch (e) {
		console.error(e)
		return
	}
	instance = echarts.init(dom.value)
	try {
		instance.setOption(data)
	} catch (e) {
		showOrigin.value = true
	}
}

watch(
	() => prop.data,
	() => {
		setOption()
	}
)

onMounted(() => {
	setOption()
	window.addEventListener('resize', resizeHandler)
})

onUnmounted(() => {
	window.removeEventListener('resize', resizeHandler)
	instance?.dispose()
})

defineExpose<{
	resize: () => void
}>({ resize: resizeHandler })
</script>

<template>
	<div ref="dom"></div>
</template>

<style scoped></style>
