<template>
	<div class="space-y-6">
		<div class="overflow-x-auto w-full">
			<el-table :data="scoreRanges" border style="width: 100%">
				<el-table-column prop="label" label="得分等级" align="center">
					<template #default="{ row }">
						<el-tag :color="row.color" style="color: aliceblue;">{{ row.labelName }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="分数区间" align="center">
					<template #default="{ row }">
						{{ row.min }} - {{ row.max }}分
					</template>
				</el-table-column>
				<el-table-column prop="total" label="提交数量" align="center" />
				<el-table-column prop="per" label="占比" align="center">
					<template #default="{ row }">
						{{ row.per }}
					</template>
				</el-table-column>
			</el-table>
		</div>
		<div ref="chartRef" class="h-[300px] w-[500px] mx-auto" ></div>
	</div>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue';
import { getPageListData } from '@/api/main/system/system'
import * as echarts from 'echarts';

const props = defineProps({
	surveyId: {
		type: Number,
		default: 0
	},
});

const chartRef = ref();
const scoreRanges = ref([
]);

const chart = ref(null);

const chartInit = () => {
	
	const option = {
		animation: false,
		tooltip: {
			trigger: 'item',
			formatter: '{b}: {c} ({d}%)'
		},
		legend: {
			orient: 'horizontal',
			bottom: 'bottom',
			data: scoreRanges.value.map(item => item.labelName)
		},
		series: [
			{
				name: '得分分布',
				type: 'pie',
				radius: ['40%', '70%'],
				center: ['50%', '45%'],
				avoidLabelOverlap: false,
				itemStyle: {
					borderRadius: 10,
					borderColor: '#fff',
					borderWidth: 2
				},
				label: {
					show: true,
					formatter: '{b}\n{c}份 ({d}%)'
				},
				labelLine: {
					show: true
				},
				data: scoreRanges.value.map(item => ({
					value: item.total,
					name: item.labelName,
					itemStyle: {
						color: item.color
					}
				}))
			}
		]
	};
	chart.value.setOption(option);
	// chart.resize();

	// 确保图表在容器尺寸变化时重新渲染
	window.addEventListener('resize', () => {
        chart.value.resize();
    });
}

const getData = () => {
	// const params = {};
	if (!props.surveyId) return;
	getPageListData(`/survey/survey/getstatisscorerange/${props.surveyId}`, {}).then(({ data }) => {
		console.log(data, 'getData-data');
		scoreRanges.value = data;
		chartInit();
	})
}

watch(props, (nweProps) => {
	getData()
});

onMounted(() => {
	if (chartRef.value) {
		chart.value = echarts.init(chartRef.value);
	}
	
	getData();
	// chartInit();
});
</script>
<style scoped lang="scss"></style>