<template>
	<div ref="stackedChart" class="chart-container"></div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount } from 'vue'

const stackedChart = ref(null)
let chartInstance = null

onMounted(() => {
	adminRequest.post("/api/mysql", { sql: "SELECT * FROM dim_total_count ORDER BY year, loan_status" }).then(res => {
		// 处理数据
		const years = [...new Set(res.map(item => item.year))].sort()
		const statusTypes = [...new Set(res.map(item => item.loan_status))]

		const seriesData = statusTypes.map(status => {
			return {
				name: status,
				type: 'bar',
				stack: 'total',
				emphasis: { focus: 'series' },
				data: years.map(year => {
					const item = res.find(d => d.year === year && d.loan_status === status)
					return item ? item.status_count : 0
				})
			}
		})

		chartInstance = echarts.init(stackedChart.value)
		chartInstance.setOption({
			title: {
				text: '年度贷款状态分布',
				left: 'center',
				textStyle: { fontSize: 18, fontWeight: 'bold', color: '#333' }
			},
			tooltip: {
				trigger: 'axis',
				axisPointer: { type: 'shadow' },
				formatter: function(params) {
					let result = `<div style="margin-bottom:5px;font-weight:bold">${params[0].axisValue}年</div>`
					params.forEach(param => {
						const total = res.find(d => d.year === param.axisValue)?.total_count || 1
						const percent = ((param.value / total) * 100).toFixed(1)
						result += `
              <div style="display:flex;justify-content:space-between;margin:3px 0">
                <span>${param.seriesName}:</span>
                <span style="margin-left:20px;font-weight:bold">${param.value} (${percent}%)</span>
              </div>
            `
					})
					return result
				}
			},
			legend: {
				data: statusTypes,
				bottom: 10
			},
			grid: {
				left: '3%',
				right: '4%',
				top: '15%',
				bottom: '15%',
				containLabel: true
			},
			xAxis: {
				type: 'category',
				data: years.map(y => `${y}年`),
				axisLabel: { rotate: 30 }
			},
			yAxis: {
				type: 'value',
				name: '贷款数量',
				axisLine: { show: true },
				axisLabel: { formatter: '{value}' }
			},
			series: seriesData,
			color: ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE']
		})

		window.addEventListener('resize', () => chartInstance.resize())
	})
})

onBeforeUnmount(() => {
	window.removeEventListener('resize', () => chartInstance.resize())
	chartInstance?.dispose()
})
</script>

<style scoped>
.chart-container {
	width: 100%;
	height: 500px;
	background: #fff;
	border-radius: 8px;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	padding: 20px;
}
</style>
