<template>
	<div ref="chartRef" :style="{ width, height }"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from "vue";
import * as echarts from "echarts";

// 定义组件props
const props = defineProps({
	// 图表配置项
	option: {
		type: Object,
		required: true
	},
	// 图表宽度
	width: {
		type: String,
		default: "100%"
	},
	// 图表高度
	height: {
		type: String,
		default: "400px"
	},
	// 图表主题
	theme: {
		type: String,
		default: ""
	},
	// 是否显示加载动画
	loading: {
		type: Boolean,
		default: false
	},
	// 自动调整大小
	autoresize: {
		type: Boolean,
		default: true
	}
});

// 定义可触发的事件
const emit = defineEmits(["chart-click", "chart-ready"]);

// 图表实例和容器引用
const chartRef = ref(null);
let chartInstance = null;

// 初始化图表
const initChart = () => {
	if (!chartRef.value) return;

	// 销毁现有实例
	if (chartInstance) {
		chartInstance.dispose();
	}

	// 创建新实例
	chartInstance = echarts.init(chartRef.value, props.theme);

	// 设置配置项
	chartInstance.setOption(props.option);

	// 绑定事件
	chartInstance.on("click", params => {
		emit("chart-click", params);
	});

	// 图表准备就绪
	emit("chart-ready", chartInstance);

	// 处理加载状态
	if (props.loading) {
		chartInstance.showLoading();
	} else {
		chartInstance.hideLoading();
	}
};

// 调整图表大小
const resizeChart = () => {
	if (chartInstance) {
		chartInstance.resize();
	}
};

// 监听选项变化
watch(
	() => props.option,
	newOption => {
		if (chartInstance) {
			chartInstance.setOption(newOption);
		}
	},
	{ deep: true }
);

// 监听加载状态变化
watch(
	() => props.loading,
	loading => {
		if (chartInstance) {
			if (loading) {
				chartInstance.showLoading();
			} else {
				chartInstance.hideLoading();
			}
		}
	}
);

// 组件挂载
onMounted(() => {
	nextTick(() => {
		initChart();

		// 如果启用自动调整大小，监听窗口变化
		if (props.autoresize) {
			window.addEventListener("resize", resizeChart);
		}
	});
});

// 组件卸载
onUnmounted(() => {
	if (chartInstance) {
		chartInstance.dispose();
		chartInstance = null;
	}

	if (props.autoresize) {
		window.removeEventListener("resize", resizeChart);
	}
});

// 暴露方法给父组件
defineExpose({
	getInstance: () => chartInstance,
	resize: resizeChart
});
</script>
