<template>
	<div ref="chartContainer" style="width: 100%; height: 300px"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'

interface ChartData {
	categories: string[]
	successful: number[]
	failed: number[]
}

interface Props {
	data: ChartData
	title?: string
}

const props = withDefaults(defineProps<Props>(), {
	title: '执行统计'
})

const chartContainer = ref<HTMLElement>()
let chart: echarts.ECharts | null = null

const initChart = () => {
	if (!chartContainer.value) return

	chart = echarts.init(chartContainer.value)

	const option: echarts.EChartsOption = {
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'shadow'
			}
		},
		legend: {
			data: ['Successful', 'Failed'],
			top: 0
		},
		xAxis: {
			type: 'category',
			data: props.data.categories,
			boundaryGap: true
		},
		yAxis: {
			type: 'value',
			splitLine: {
				lineStyle: {
					color: '#f0f0f0'
				}
			}
		},
		series: [
			{
				name: 'Successful',
				data: props.data.successful,
				type: 'bar',
				itemStyle: {
					color: '#13c2c2'
				},
				barWidth: '30%',
				barGap: '30%'
			},
			{
				name: 'Failed',
				data: props.data.failed,
				type: 'bar',
				itemStyle: {
					color: '#ff6b6b'
				},
				barWidth: '30%',
				barGap: '30%'
			}
		],
		grid: {
			left: '3%',
			right: '4%',
			bottom: '3%',
			top: '50px',
			containLabel: true
		}
	}

	chart.setOption(option)
}

const handleResize = () => {
	chart?.resize()
}

watch(
	() => props.data,
	() => {
		if (chart) {
			const option: echarts.EChartsOption = {
				xAxis: {
					data: props.data.categories
				},
				series: [
					{
						data: props.data.successful
					},
					{
						data: props.data.failed
					}
				]
			}
			chart.setOption(option)
		}
	},
	{ deep: true }
)

onMounted(() => {
	initChart()
	window.addEventListener('resize', handleResize)
})

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