<template>
	<div class="container-echart">
		<div :id="'echart' + timeId" class="interface-echart"></div>
	</div>
</template>
<script lang="ts" setup>
	import * as echarts from 'echarts'
	import { EChartsType } from 'echarts'
	import { onMounted, ref, watch, onBeforeUnmount, nextTick } from 'vue'

	const props = defineProps({
		message: {
			type: Array,
			default: true
		}
	})

	let myEchart : EChartsType
	const timeId = ref(Math.floor(new Date().getTime() * Math.random())); // 使该图表保持唯id
	const myEchartData = () => {
		const option = {
			tooltip: {
				show: true,
				trigger: 'item',
				formatter: "{b}: {c}台   ({d}%)"
			},
			title: {
				text: '设备数量',
				subtext: '451',
				x: 'center',
				y: '100',
				textStyle: {
					fontWeight: 'bold',
					fontSize: 20,
					color: 'white'
				},
				subtextStyle:{
					fontSize: 22,
					color: 'white'
				}
			},
			series: [
				{
					name: 'Access From',
					type: 'pie',
					radius: ['60%', '80%'],
					avoidLabelOverlap: false,
					itemStyle: {
						borderRadius: 10,
						borderWidth: 2
					},
					label: {
						show: false,
						position: 'center'
					},
					labelLine: {
						show: false
					},
					data: props.message
				}
			]
		};
		// { notMerge: true } 解决删除数据时,数据不刷新的问题
		myEchart.setOption(option, { notMerge: true })
	}
	watch(
		//监控数据变化
		() => props.message,
		() => {
			setTimeout(() => {
				myEchartData()
			}, 500)
		},
		{ deep: true }
	)
	onMounted(() => {
		setTimeout(() => {
			const dom = document.getElementById(`echart${timeId.value}`) as any
			myEchart = echarts.init(dom)
			myEchartData()
		}, 500)

		// 当窗口发生变化时
		window.addEventListener('resize', () => {
			myEchart.resize()
		})
	})
	onBeforeUnmount(() => {
		window.removeEventListener('resize', () => {
			myEchart.resize()
		})
	})
</script>
<style scoped lang="scss">
	.container-echart {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		overflow: hidden;
	}

	.interface-echart {
		width: 100%;
		height: 100%;
	}
</style>