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

<script setup name="chartWater">
	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) + "%, ";
			}
			clientLabels.push({
				name: item.name,
				percent: percentStr,
				number: item.value
			})
		})

		let options = {
			tooltip: {
				trigger: "item",
				formatter: function({ name, value, percent }) {
					return (
						name + "：" + value + "吨&nbsp;&nbsp;&nbsp;&nbsp;" + percent + "%"
					);
				},
			},
			legend: {
				top: "center",
				left: "55%",
				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,
					label: {
						show: false,
						// position: 'center'
					},
					emphasis: {
						label: {
							show: false,
							fontSize: "40",
							fontWeight: "bold",
						},
					},
					labelLine: {
						show: false,
					},
					itemStyle: {
						normal: {
							color: function(colors) {
								// 颜色设置
								var colorList = [
									"#3aa0ff",
									"#403DEA",
									"#226942",
									"#1AD06C",
									"#C03DEA",
									"#3B5CBB"
								];
								return colorList[colors.dataIndex];
							},
							borderWidth: 5, // 设置各项空隙
							borderColor: "#fff",
						},
					},
					data: props.list,
				},
			],
		}

		myChart.setOption(options)
	}

	onMounted(() => {
		myChart = echarts.init(document.getElementById('chart-water' + 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>
