<template>
	<view>
		<!-- ECharts图表容器 -->
		<view class="chart-container" ref="chartContainer">
			<l-echart ref="chart" @finished="onChartFinished" />
		</view>
	</view>
</template>

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

	// 定义数据项接口
	interface DataItem {
		[key : string] : string | number;
	}

	// 定义字段配置接口
	interface FieldConfig {
		field : string;        // 数据字段名
		name : string;         // 显示名称
		color ?: string;       // 线条颜色(可选)
		referenceValue ?: number; // 参考值(可选)
	}

	// 定义组件属性接口
	interface TrendChartProps {
		dataList : DataItem[]; // 数据列表
		timeField : string;    // 时间字段名
		fields : FieldConfig[]; // 需要展示的字段配置
		title ?: string;       // 图表标题
		height ?: string;      // 图表高度
		showLegend ?: boolean; // 是否显示图例
	}

	// 组件属性定义
	const props = withDefaults(defineProps<TrendChartProps>(), {
		timeField: 'createTime',
		fields: () => [],
		title: '数据趋势图',
		height: '30vh',
		showLegend: true
	});

	// 图表引用和状态
	const chart = ref<any>(null);
	const chartContainer = ref<HTMLElement | null>(null);
	const chartInstance = ref<echarts.ECharts | null>(null);
	const chartOption = ref<any>({});
	const isLoading = ref(true);

	// 生成颜色数组 - 为不同线条提供区分色
	const generateColors = (count : number) : string[] => {
		const baseColors = [
			'#337ab7', '#5cb85c', '#5bc0de', '#f0ad4e', '#d9534f',
			'#7b68ee', '#ff6347', '#00ced1', '#ffd700', '#9370db'
		];

		if (count <= baseColors.length) {
			return baseColors.slice(0, count);
		}

		const colors = [...baseColors];
		for (let i = baseColors.length; i < count; i++) {
			const color = `#${Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')}`;
			colors.push(color);
		}

		return colors;
	};

	// 处理系列数据 - 增加错误处理
	const processSeriesData = () => {
		// 验证数据有效性
		if (!props.dataList || props.dataList.length === 0) {
			console.warn('没有可用数据');
			return [];
		}

		if (!props.fields || props.fields.length === 0) {
			console.warn('没有配置要显示的字段');
			return [];
		}

		const colors = generateColors(props.fields.length);
		const series : any[] = [];

		props.fields.forEach((fieldConfig, index) => {
			try {
				// 验证字段是否存在于数据中
				const hasField = props.dataList.some(item => item[fieldConfig.field] !== undefined);
				if (!hasField) {
					console.warn(`数据中不存在字段: ${fieldConfig.field}`);
					return;
				}

				// 处理当前字段的趋势线数据
				const fieldData = props.dataList
					.filter(item => item[props.timeField] && item[fieldConfig.field]) // 过滤无效数据
					.sort((a, b) => {
						const timeA = new Date(a[props.timeField] as string).getTime();
						const timeB = new Date(b[props.timeField] as string).getTime();
						return timeA - timeB;
					})
					.map((item) => {
						const timeValue = new Date(item[props.timeField] as string).getTime();
						const fieldValue = parseFloat(item[fieldConfig.field].toString()) || 0;
						return [timeValue, fieldValue];
					});

				// 添加趋势线系列
				series.push({
					name: fieldConfig.name,
					type: 'line',
					showSymbol: true,
					symbol: 'circle',
					symbolSize: 6,
					smooth: true,
					data: fieldData,
					lineStyle: {
						width: 2,
						color: fieldConfig.color || colors[index]
					},
					itemStyle: {
						color: fieldConfig.color || colors[index],
						borderColor: '#fff',
						borderWidth: 2
					},
					emphasis: {
						scale: true
					}
				});

				// 如果有参考值，添加参考线
				if (fieldConfig.referenceValue !== undefined) {
					series.push({
						type: 'line',
						name: `${fieldConfig.name}参考值`,
						markLine: {
							silent: true,
							lineStyle: {
								type: 'dashed',
								color: fieldConfig.color || colors[index],
								width: 2
							},
							data: [{ yAxis: fieldConfig.referenceValue }],
							label: {
								show: true,
								position: 'end',
								formatter: `${fieldConfig.name}参考值: ${fieldConfig.referenceValue}`,
								fontSize: 12
							}
						},
						data: []
					});
				}
			} catch (error) {
				console.error(`处理字段 ${fieldConfig.field} 时出错:`, error);
			}
		});

		return series;
	};

	// 生成图表配置
	const generateOptions = () => ({
		title: {
			text: props.title,
			left: 'center',
			textStyle: {
				color: '#333',
				fontSize: 16
			},
			padding: [10, 0, 0, 0]
		},
		tooltip: {
			trigger: 'axis',
			backgroundColor: 'rgba(255, 255, 255, 0.95)',
			borderColor: '#eee',
			borderWidth: 1,
			borderRadius: 8,
			textStyle: {
				color: '#333',
				fontSize: 14
			},
			axisPointer: {
				type: 'line',
				lineStyle: {
					color: '#ddd',
					width: 1
				}
			},
			formatter: function (params : any[]) {
				if (!params || params.length === 0) return '';
				const time = new Date(params[0].value[0]).toLocaleString();
				let result = `<div style="font-weight:bold;margin-bottom:5px">${time}</div>`;

				params.forEach((item) => {
					if (item.seriesType === 'line' && item.data) {
						result += `<div style="display:flex;align-items:center;margin:3px 0">
            <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:${item.color};margin-right:5px;"></span>
            <span>${item.seriesName}：${item.value[1].toFixed(2)}</span>
          </div>`;
					}
				});

				return result;
			},
			confine: true
		},
		backgroundColor: 'rgba(255, 255, 255, 0.8)',
		xAxis: {
			type: 'time',
			axisLine: {
				lineStyle: {
					color: '#ddd'
				}
			},
			axisLabel: {
				color: '#666',
				formatter: (value : number) => {
					const date = new Date(value);
					return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
				},
				rotate: 30
			},
			splitLine: {
				show: true,
				lineStyle: {
					color: '#f5f5f5',
					type: 'dashed'
				}
			}
		},
		yAxis: {
			type: 'value',
			axisLine: {
				show: true,
				lineStyle: {
					color: '#ddd'
				}
			},
			splitLine: {
				lineStyle: {
					color: '#f5f5f5',
					type: 'dashed'
				}
			},
			axisLabel: {
				color: '#666',
				formatter: (value : number) => `${value.toFixed(2)}`
			}
		},
		series: processSeriesData(),
		legend: props.showLegend ? {
			type: 'scroll',
			bottom: 5,
			textStyle: {
				color: '#666',
				fontSize: 12
			},
			pageIconColor: '#666',
			pageTextStyle: {
				color: '#999'
			},
			selectedMode: 'multiple'
		} : {
			show: false
		},
		grid: {
			top: props.title ? 60 : 30,
			right: 30,
			bottom: props.showLegend ? 60 : 30,
			left: 50,
			containLabel: true
		},
		dataZoom: [
			{
				type: 'inside',
				start: 0,
				end: 100,
				minValueSpan: 3600 * 1000 * 2
			},
			{
				type: 'slider',
				bottom: 10,
				start: 0,
				end: 100,
				handleSize: 8
			}
		]
	});

	// 初始化图表
	const initChart = async () => {
		if (!chart.value || chartInstance.value) return;

		try {
			// 确保图表容器已正确渲染
			await nextTick();

			// 初始化图表实例
			chartInstance.value = await chart.value.init(echarts);

			// 设置图表配置
			updateChart();

			// 监听窗口大小变化
			const handleResize = () => {
				chartInstance.value?.resize();
			};

			window.addEventListener('resize', handleResize);

			// 组件卸载时清理
			onUnmounted(() => {
				window.removeEventListener('resize', handleResize);
			});
		} catch (error) {
			console.error('图表初始化失败:', error);
			isLoading.value = false; // 即使失败也隐藏加载状态
		}
	};

	// 图表组件加载完成回调
	const onChartFinished = () => {
		initChart();
	};

	// 更新图表
	const updateChart = () => {
		if (!chartInstance.value) return;

		try {
			// 生成新的图表配置
			chartOption.value = generateOptions();

			// 设置图表数据
			chartInstance.value.setOption(chartOption.value, true);

			// 数据加载完成，隐藏加载状态
			isLoading.value = false;
		} catch (error) {
			console.error('更新图表失败:', error);
			isLoading.value = false;
		}
	};

	// 监听数据变化，更新图表
	watch(
		() => [props.dataList, props.fields, props.title],
		() => {
			if (props.dataList.length > 0 && props.fields.length > 0) {
				isLoading.value = true;
				// 延迟更新，确保DOM已更新
				setTimeout(updateChart, 100);
			}
		},
		{ deep: true, immediate: true } // 立即执行一次
	);

	// 生命周期钩子
	onMounted(() => {
		// 设置图表高度
		if (chartContainer.value && props.height) {
			chartContainer.value.style.height = props.height;
		}

		// 如果数据已准备好，初始化图表
		if (props.dataList.length > 0 && props.fields.length > 0) {
			nextTick(() => {
				initChart();
			});
		}
	});

	onUnmounted(() => {
		// 销毁图表，释放资源
		if (chartInstance.value) {
			chartInstance.value.dispose();
			chartInstance.value = null;
		}
	});
</script>

<style scoped>
	/* 图表容器样式 */
	.chart-container {
		width: 100%;
		min-height: 200px;
		padding: 16rpx;
		background: linear-gradient(145deg, #f8f9fa 0%, #ffffff 100%);
		border-radius: 16rpx;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
		position: relative;
		overflow: hidden;
	}

	/* 加载状态样式 - 仅在isLoading为true时显示 */
	.chart-container::before {
		content: '数据加载中...';
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		color: #999;
		font-size: 28rpx;
		z-index: 1;
		transition: opacity 0.3s ease;
		opacity: v-bind(isLoading ? 1 : 0);
		pointer-events: v-bind(isLoading ? 'auto' : 'none');
	}

	/* 移动端适配 */
	@media screen and (max-width: 768px) {
		.chart-container {
			padding: 10rpx;
			border-radius: 12rpx;
		}
	}
</style>