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

<script setup name="chartWarnPie">
	import * as echarts from 'echarts'
	const props = defineProps({
		id: {
			type: Number,
			default: 0
		},
		list: {
			type: Array,
			default: () => []
		}
	})

	let myChart = null

	const init = () => {
		let total = props.list.reduce(
			(prev, item) => prev + item.value,
			0
		);
		let clientLabels = []
		props.list.forEach((item) => {
			let percentStr = ""
			if (item.value !== 0) {
				percentStr = (parseFloat(item.value / total) * 100).toFixed(2) + "%, "
			} else {
				percentStr = '0%,'
			}
			clientLabels.push({
				name: item.name,
				percent: percentStr,
				number: item.value
			})
		})

		let options = {
			tooltip: {
				trigger: "item",
				formatter: function ({ name, value, percent }) {
					let per = percent ? percent : 0
					return (
						name + "：" + value + "条&nbsp;&nbsp;&nbsp;&nbsp;" + per + "%"
					);
				}
			},
			color: ['#1890FF', '#1EE7E7', '#2F54EB', '#BAE7FF', '#FFAC26'],
			legend: {
				top: "center",
				left: "65%",
				orient: "vertical",
				icon: "circle",
				selectedMode: false, // 取消右侧项选中
				itemGap: 20, // 各项间隔
				textStyle: {
					fontSize: 15,
					color: "#666"
				},
				formatter: function (name) {
					const item = clientLabels.find((item) => {
						return item.name === name
					})
					return name + " (" + item.percent + item.number + "条" + ") "
				}
			},
			series: [
				{
					name: "",
					type: "pie",
					radius: ["60%", "80%"], // 半径
					center: ["30%", "55%"],
					avoidLabelOverlap: false,
					data: props.list,
					label: {
						show: true,
						position: 'center',
						formatter: function () {
							var str = '本月预警总数' + '\n' + '\n' + total + '条'
							return str
						},
						textStyle: {
							color: '#000',
							fontSize: 18
						}
					},
					itemStyle: {
						borderColor: '#fff',
						borderWidth: 4
					},
				}
			]
		}

		myChart.setOption(options)
	}

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

	watch(() => props.list, () => {
		myChart.clear()
		init()
	}, { deep: true })

	onBeforeUnmount(() => {
		window.removeEventListener('resize', () => {
			myChart.resize()
		})

	})
</script>

<style scoped>

</style>
