<template>
	<el-row v-loading="loading">
		<!-- 折线图 -->
		<el-col :span="12">
			<v-chart class="chart" :option="demandByRegionOption" autoresize />
		</el-col>
		<!-- 饼图 -->
		<el-col :span="12">
			<v-chart class="chart" :option="pieChartOption" autoresize />
		</el-col>
	</el-row>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import VChart from 'vue-echarts'
import { BarChart, PieChart, LineChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { use } from 'echarts/core'


// 引入并使用图表组件
use([CanvasRenderer, BarChart, PieChart, LineChart, TitleComponent, TooltipComponent, LegendComponent, GridComponent])

// 定义折线图配置
const demandByRegionOption = ref({
	title: { text: '交易地区占比（折线图）' },
	tooltip: { trigger: 'axis' },
	legend: { data: ['交易量'] },
	xAxis: {
		type: 'category',
		data: [] // 初始为空，等待接口数据
	},
	yAxis: { type: 'value' },
	series: [
		{
			name: '交易量',
			type: 'line',
			data: [] // 初始为空，等待接口数据
		}
	]
})

// 定义饼图配置
const pieChartOption = ref({
	title: { text: '交易地区占比（饼图）' },
	tooltip: { trigger: 'item' },
	legend: { bottom: '10%', left: 'center' },
	series: [
		{
			name: '交易量',
			type: 'pie',
			radius: '50%',
			data: [], // 初始为空，等待接口数据
			emphasis: {
				itemStyle: {
					shadowBlur: 10,
					shadowOffsetX: 0,
					shadowColor: 'rgba(0, 0, 0, 0.5)'
				}
			}
		}
	]
})

// 加载状态
const loading = ref(true)

// 在 onMounted 中获取数据并更新图表
onMounted(async () => {
	try {
		// 调用接口获取数据
		const response = await adminRequest.post('/api/mysql', {
			sql: "SELECT transaction_location name, count(*) value FROM fraud_detection_ml.tb_financial_transactions GROUP BY transaction_location"
		})

		// 更新折线图配置
		demandByRegionOption.value.xAxis.data = response.map(item => item.name)
		demandByRegionOption.value.series[0].data = response.map(item => item.value)

		// 更新饼图配置
		pieChartOption.value.series[0].data = response.map(item => ({
			name: item.name,
			value: item.value
		}))
	} catch (error) {
		console.error('获取数据失败:', error)
	} finally {
		loading.value = false // 关闭加载状态
	}
})
</script>

<style scoped>
.chart {
	height: 400px;
}
</style>
