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

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

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

	let myChart = null

	const init = () => {
		let data = []
		if (props.list.length > 0) {
			data = props.list
		}
		let options = {
			legend: {
				data: ['男性', '女性']
			},
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'shadow'
				},
				formatter: function(params) {
					var tooltipText = params[0].name + '<br/>';
					tooltipText += '男性: ' + params[0].data +'人'  + '<br/>';
					tooltipText += '女性: ' + params[1].data+'人'  + '<br/>';
					tooltipText += '总人数: ' + (params[0].data + params[1].data) +'人';
					return tooltipText;
				}
			},
			xAxis: {
				type: 'category',
				data: data.map(function(item) {
					return item.ageRange
				})
			},
			yAxis: {
				type: 'value',
				name: '人数'
			},
			series: [
				{
					name: '男性',
					type: 'bar',
					data: data.map(function(item) {
						return item.maleCount;
					}),
					barWidth: 20,
					stack: '总人口' // 这里使用堆叠，使男女柱状图叠加
				},
				{
					name: '女性',
					type: 'bar',
					barWidth: 20,
					data: data.map(function(item) {
						return item.femaleCount;
					}),
					stack: '总人口' // 这里使用堆叠，使男女柱状图叠加
				}
			]
		}
		myChart.setOption(options);
	}

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

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

<style scoped>

</style>
