<template>
	<div :id="'chart-type' + id" style="width: 100%; height: 100%"></div>
</template>

<script setup name="chartType">
	import * as echarts from 'echarts'

	const props = defineProps({
		id: {
			type: Number,
			default: 0
		},
		list: {
			type: Array,
			default: () => []
		}
	})

	let myChart = null

	const init = () => {
		let data = []
		let total = 0
		if (props.list.length > 0) {
			props.list.forEach(item => {
				item.name = item.type
				item.value = item.count
				total += item.value
			})
			data = props.list
		}
		let options = {
			tooltip: {
				trigger: 'item',
				formatter: '{b}: {c} ({d}%)'
			},
			legend: {
				orient: 'vertical',
				left: '70%', // 控制图例的位置，调整为右侧
				top: 'middle',
				align: 'left',
				textStyle: {
					fontSize: 12
				},
				formatter: function(name) {
					var dataItem = data.find(function(item) {
						return item.name === name
					});
					if (dataItem) {
						var percentage = ((dataItem.value / total) * 100).toFixed(2) + '%'
						return name + ' ' + dataItem.value + ' (' + percentage + ')'
					}
					return name
				},
				data: data.map(function(item) {
					return item.name
				})
			},
			series: [
				{
					name: '饼图',
					type: 'pie',
					radius: ['60%', '80%'], // 调整内外圆的半径，实现更大的镂空和整个饼图
					center: ['30%', '50%'],  // 控制图表的位置
					avoidLabelOverlap: false,
					label: {
						show: false,
						position: 'center'
					},
					emphasis: {
						label: {
							show: true,
							fontSize: '20',
							fontWeight: 'bold'
						}
					},
					labelLine: {
						show: false
					},
					data: data
				}
			]
		}
		myChart.setOption(options)
	}

	onMounted(() => {
		myChart = echarts.init(document.getElementById('chart-type' + props.id))
		init()
		window.addEventListener('resize', () => {
			myChart.resize()
		})
	})

	watch(() => props.list, () => {
		myChart.clear()
		init()
	})
</script>

<style scoped>

</style>
