<template>
	<view class="curve-container">
		<!-- 页面标题区域 -->
		<view class="header-section">
			<view class="header-title">
				<text class="title">曲线走势图</text>
				<text class="subtitle">学员成绩趋势变化分析</text>
			</view>
		</view>

		<!-- ==================== 项目选择区域 ==================== -->
		<view class="project-select-section">
			<view class="section-header">
				<text class="section-title">选择项目</text>
			</view>
			<!-- 项目选择器 -->
			<picker mode="selector" :range="projectOptions" range-key="name" :value="selectedProjectIndex" @change="handleProjectChange">
				<view class="picker-wrapper">
					<text class="picker-text">{{ selectedProjectName }}</text>
					<u-icon name="arrow-down" size="18" color="#999"></u-icon>
				</view>
			</picker>
		</view>

		<!-- ==================== 学生选择区域 ==================== -->
		<!-- 仅在选择项目后显示 -->
		<view class="student-select-section" v-if="selectedProjectId && projectStudents.length > 0">
			<view class="section-header">
				<text class="section-title">选择学员（最多3人）</text>
				<text class="select-count">已选：{{ selectedStudentIds.length }}/3</text>
			</view>
			<!-- 学生列表 -->
			<view class="student-list">
				<view v-for="student in projectStudents" :key="student.id" :class="['student-item', { 'selected': selectedStudentIds.includes(student.id) }]" @click="toggleStudent(student.id)">
					<!-- 学生头像（使用首字母作为头像） -->
					<view class="student-avatar">
						<text class="avatar-text">{{ student.name.charAt(0) }}</text>
					</view>
					<!-- 学生姓名 -->
					<text class="student-name">{{ student.name }}</text>
					<!-- 选择状态图标 -->
					<view class="check-icon" v-if="selectedStudentIds.includes(student.id)">
						<u-icon name="checkmark" size="16" color="#fff"></u-icon>
					</view>
				</view>
			</view>
		</view>


		<!-- ==================== 图表展示区域 ==================== -->
		<!-- 仅在选择了至少一名学生后显示 -->
		<view class="chart-section" v-if="selectedStudentIds.length > 0">
			<!-- 数据统计卡片 -->
			<view class="stats-card">
				<view class="stat-item">
					<text class="stat-label">选中项目</text>
					<text class="stat-value">{{ selectedProjectName }}</text>
				</view>
				<view class="stat-divider"></view>
				<view class="stat-item">
					<text class="stat-label">对比学员</text>
					<text class="stat-value">{{ selectedStudentIds.length }}人</text>
				</view>
				<view class="stat-divider"></view>
				<view class="stat-item">
					<text class="stat-label">训练次数</text>
					<text class="stat-value">{{ maxTrainingCount }}次</text>
				</view>
			</view>

			<!-- 折线图卡片 -->
			<view class="chart-card">
				<view class="chart-header">
					<text class="chart-title">成绩趋势对比</text>
					<text class="chart-desc">历史训练成绩变化曲线</text>
				</view>
				<!-- 折线图容器 -->
				<view class="chart-box">
					<qiun-data-charts type="line" :opts="lineOpts" :chartData="lineChartData" :ontouch="true" />
				</view>
			</view>

			<!-- 图例说明 -->
			<view class="legend-section">
				<text class="legend-title">图例说明</text>
				<view class="legend-list">
					<view v-for="(student, index) in selectedStudents" :key="student.id" class="legend-item">
						<view class="legend-color" :style="{ backgroundColor: chartColors[index] }"></view>
						<text class="legend-name">{{ student.name }}</text>
						<text class="legend-desc">（{{ getStudentBestTime(student.id) }}s 最佳）</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { onShow, onLoad } from "@dcloudio/uni-app"
	import { Service } from '@/Service/Service'
	import { ref, computed, watch } from 'vue'

	// ==================== 常量定义 ====================

	// 最大选择学生数量限制
	const MAX_SELECTED_STUDENTS = 3

	// 图表颜色配置（最多支持3种颜色）
	const chartColors = ['#52c41a', '#1890ff', '#faad14']

	// ==================== 响应式数据 - 项目相关 ====================

	// 项目列表数据
	const projectList = ref([
		{ id: '1', name: '100米自由泳' },
		{ id: '2', name: '50米自由泳' },
		{ id: '3', name: '200米由泳' },
		{ id: '4', name: '100米蛙泳' }
	])

	// 项目选择器选项（用于 picker 组件）
	const projectOptions = ref(projectList.value)

	// 当前选中的项目索引（用于 picker 组件的显示）
	const selectedProjectIndex = ref(-1)

	// 当前选中的项目 ID
	const selectedProjectId = ref('')

	// 当前选中的项目名称（用于显示）
	const selectedProjectName = computed(() => {
		if (selectedProjectIndex.value === -1) {
			return '请选择项目'
		}
		return projectList.value[selectedProjectIndex.value]?.name || '请选择项目'
	})

	// ==================== TypeScript 接口定义 ====================

	/**
	 * 学生接口
	 * 定义学生的基本信息
	 */
	interface Student {
		id: string
		name: string
	}

	/**
	 * 学生训练记录接口
	 * 定义学生某次训练的详细记录
	 */
	interface StudentTrainingRecord {
		studentId: string
		studentName: string
		time: number
		recordDate: string
		recordFullDate: string
		round: number
	}

	// ==================== 响应式数据 - 学生相关 ====================

	// 当前项目的学生列表
	const projectStudents = ref<Student[]>([])

	// 已选中的学生 ID 列表
	const selectedStudentIds = ref<string[]>([])

	// 已选中的学生详细信息列表（（计算属性）
	const selectedStudents = computed(() => {
		return projectStudents.value.filter(student =>
			selectedStudentIds.value.includes(student.id)
		)
	})

	// ==================== 响应式数据 - 图表相关 ====================

	// 折线图配置选项
	const lineOpts = ref({
		color: chartColors,
		padding: [15, 10, 0, 15],
		legend: {
			show: true,
			position: 'bottom',
			itemGap: 30
		},
		xAxis: {
			disableGrid: true,
			itemCount: 6,
			rotateLabel: true
		},
		yAxis: {
			data: [{
				min: 0,
				format: (val: number) => val.toFixed(1) + 's'
			}]
		},
		extra: {
			line: {
				type: 'curve',
				width: 2,
				activeType: 'hollow',
				linearType: 'none',
				onGap: false
			}
		}
	})

	// 折线图数据
	const lineChartData = ref({
		categories: [] as string[],
		series: [] as any[]
	})

	// 最大训练次数（计算属性）
	const maxTrainingCount = computed(() => {
		const allRecords = mockTrainingRecords[selectedProjectId.value] || []
		const studentCounts = new Map<string, number>()
		allRecords.forEach(record => {
			studentCounts.set(record.studentId, (studentCounts.get(record.studentId) || 0) + 1)
		})
		return Math.max(0, ...Array.from(studentCounts.values()))
	})

	// ==================== 模拟数据 ====================

	// 模拟的学生数据（按项目分组）
	const mockProjectStudents: Record<string, Student[]> = {
		'1': [
			{ id: 's1', name: '张小明' },
			{ id: 's2', name: '李小红' },
			{ id: 's3', name: '王小明' },
			{ id: 's4', name: '赵小芳' },
			{ id: 's5', name: '陈小刚' }
		],
		'2': [
			{ id: 's6', name: '刘小华' },
			{ id: 's7', name: '张小丽' },
			{ id: 's8', name: '杨小龙' }
		],
		'3': [
			{ id: 's9', name: '黄小东' },
			{ id: 's10', name: '吴小西' },
			{ id: 's11', name: '周小南' },
			{ id: 's12', name: '徐小北' }
		],
		'4': [
			{ id: 's13', name: '马小兵' },
			{ id: 's14', name: '朱小红' }
		]
	}

	// 模拟的训练记录数据（按项目分组）
	const mockTrainingRecords: Record<string, StudentTrainingRecord[]> = {
		'1': [
			{ studentId: 's1', studentName: '张小明', time: 28.5, recordDate: '03-12', recordFullDate: '2026-03-12', round: 1 },
			{ studentId: 's1', studentName: '张小明', time: 27.2, recordDate: '03-14', recordFullDate: '2026-03-14', round: 1 },
			{ studentId: 's1', studentName: '张小明', time: 26.5, recordDate: '03-16', recordFullDate: '2026-03-16', round: 1 },
			{ studentId: 's1', studentName: '张小明', time: 25.8, recordDate: '03-19', recordFullDate: '2026-03-19', round: 1 },
			{ studentId: 's1', studentName: '张小明', time: 25.2, recordDate: '03-24', recordFullDate: '2026-03-24', round: 1 },
			{ studentId: 's2', studentName: '李小红', time: 32.5, recordDate: '03-12', recordFullDate: '2026-03-12', round: 1 },
			{ studentId: 's2', studentName: '李小红', time: 31.2, recordDate: '03-14', recordFullDate: '2026-03-14', round: 1 },
			{ studentId: 's2', studentName: '李小红', time: 30.5, recordDate: '03-19', recordFullDate: '2026-03-19', round: 1 },
			{ studentId: 's2', studentName: '李小红', time: 29.8, recordDate: '03-24', recordFullDate: '2026-03-24', round: 1 },
			{ studentId: 's3', studentName: '王小明', time: 25.8, recordDate: '03-12', recordFullDate: '2026-03-12', round: 1 },
			{ studentId: 's3', studentName: '王小明', time: 24.5, recordDate: '03-16', recordFullDate: '2026-03-16', round: 1 },
			{ studentId: 's3', studentName: '王小明', time: 23.8, recordDate: '03-24', recordFullDate: '2026-03-24', round: 1 },
			{ studentId: 's4', studentName: '赵小芳', time: 33.5, recordDate: '03-14', recordFullDate: '2026-03-14', round: 1 },
			{ studentId: 's4', studentName: '赵小芳', time: 32.2, recordDate: '03-19', recordFullDate: '2026-03-19', round: 1 },
			{ studentId: 's5', studentName: '陈小刚', time: 35.5, recordDate: '03-19', recordFullDate: '2026-03-19', round: 1 }
		],
		'2': [
			{ studentId: 's6', studentName: '刘小华', time: 24.5, recordDate: '03-12', recordFullDate: '2026-03-12', round: 1 },
			{ studentId: 's6', studentName: '刘小华', time: 23.8, recordDate: '03-14', recordFullDate: '2026-03-14', round: 1 },
			{ studentId: 's6', studentName: '刘小华', time: 23.2, recordDate: '03-19', recordFullDate: '2026-03-19', round: 1 },
			{ studentId: 's7', studentName: '张小丽', time: 26.8, recordDate: '03-12', recordFullDate: '2026-03-12', round: 1 },
			{ studentId: 's7', studentName: '张小丽', time: 26.2, recordDate: '03-16', recordFullDate: '2026-03-16', round: 1 },
			{ studentId: 's8', studentName: '杨小龙', time: 25.5, recordDate: '03-14', recordFullDate: '2026-03-14', round: 1 },
			{ studentId: 's8', studentName: '杨小龙', time: 24.8, recordDate: '03-19', recordFullDate: '2026-03-19', round: 1 }
		],
		'3': [
			{ studentId: 's9', studentName: '黄小东', time: 125.8, recordDate: '03-12', recordFullDate: '2026-03-12', round: 1 },
			{ studentId: 's9', studentName: '黄小东', time: 124.5, recordDate: '03-14', recordFullDate: '2026-03-14', round: 1 },
			{ studentId: 's10', studentName: '吴小西', time: 128.5, recordDate: '03-12', recordFullDate: '2026-03-12', round: 1 },
			{ studentId: 's10', studentName: '吴小西', time: 127.2, recordDate: '03-16', recordFullDate: '2026-03-16', round: 1 },
			{ studentId: 's10', studentName: '吴小西', time: 126.8, recordDate: '03-19', recordFullDate: '2026-03-19', round: 1 }
		],
		'4': [
			{ studentId: 's13', studentName: '马小兵', time: 82.5, recordDate: '03-12', recordFullDate: '2026-03-12', round: 1 },
			{ studentId: 's13', studentName: '马小兵', time: 81.8, recordDate: '03-14', recordFullDate: '2026-03-14', round: 1 },
			{ studentId: 's14', studentName: '朱小红', time: 88.5, recordDate: '03-12', recordFullDate: '2026-03-12', round: 1 }
		]
	}

	// ==================== 生命周期钩子 ====================

	onLoad(() => {
		loadProjectData()
	})

	onShow(() => {
		// TODO: 如果需要在页面显示时刷新数据，可以在这里添加逻辑
	})

	// ==================== 监听器 ====================

	// 监听选中学生 ID 列表的变化
	// 使用 getter 函数返回数组副本，这样可以确保监听器触发
	watch(() => [...selectedStudentIds.value], (newIds, oldIds) => {
		console.log('selectedStudentIds changed:', newIds)
		console.log('oldIds:', oldIds)
		updateChartData()
	})

	// ==================== 业务逻辑方法 ====================

	const loadProjectData = () => {
		// TODO: 调用后端 API 获取项目列表
	}

	const handleProjectChange = (e: any) => {
		const index = e.detail.value
		selectedProjectIndex.value = index
		const selectedProject = projectList.value[index]
		if (selectedProject) {
			selectedProjectId.value = selectedProject.id
			loadProjectStudents(selectedProject.id)
		}
		selectedStudentIds.value = []
	}

	const loadProjectStudents = (projectId: string) => {
		if (mockProjectStudents[projectId]) {
			projectStudents.value = mockProjectStudents[projectId]
		} else {
			projectStudents.value = []
		}
	}

	const toggleStudent = (studentId: string) => {
		const index = selectedStudentIds.value.indexOf(studentId)
		if (index !== -1) {
			selectedStudentIds.value.splice(index, 1)
		} else {
			if (selectedStudentIds.value.length >= MAX_SELECTED_STUDENTS) {
				Service.Msg(`最多只能选择 ${MAX_SELECTED_STUDENTS} 名学员`)
				return
			}
			selectedStudentIds.value.push(studentId)
		}
	}

	const getStudentBestTime = (studentId: string): number => {
		const records = mockTrainingRecords[selectedProjectId.value] || []
		const studentRecords = records.filter(r => r.studentId === studentId)
		if (studentRecords.length === 0) return 0
		return Math.min(...studentRecords.map(r => r.time))
	}

	const updateChartData = () => {
		if (selectedStudentIds.value.length === 0 || !selectedProjectId.value) {
			lineChartData.value.series = []
			lineChartData.value.categories = []
			return
		}

		const projectRecords = mockTrainingRecords[selectedProjectId.value] || []
		const allDates = new Set<string>()
		projectRecords.forEach(record => {
			allDates.add(record.recordFullDate)
		})

		const sortedDates = Array.from(allDates).sort()

		lineChartData.value.categories = sortedDates.map(date => {
			const parts = date.split('-')
			return `${parts[1]}-${parts[2]}`
		})

		const seriesData: any[] = []

		selectedStudentIds.value.forEach((studentId, index) => {
			const studentRecords = projectRecords.filter(r => r.studentId === studentId)
			studentRecords.sort((a, b) => a.recordFullDate.localeCompare(b.recordFullDate))

			const timeMap = new Map<string, number>()
			studentRecords.forEach(record => {
				timeMap.set(record.recordFullDate, record.time)
			})

			const timeData = sortedDates.map(date => timeMap.get(date) || null)
			const studentName = projectStudents.value.find(s => s.id === studentId)?.name || '未知学员'

			seriesData.push({
				name: studentName,
				data: timeData,
				color: chartColors[index]
			})
		})
		console.log();
		lineChartData.value.series = seriesData
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #f5f5f5;
	}

	.curve-container {
		min-height: 100vh;
		padding-bottom: 40rpx;
	}

	.header-section {
		background-color: #fff;
		padding: 32rpx 28rpx 24rpx;
		margin-bottom: 20rpx;

		.header-title {
			.title {
				font-size: 36rpx;
				font-weight: 700;
				color: #333;
				display: block;
				margin-bottom: 8rpx;
			}

			.subtitle {
				font-size: 24rpx;
				color: #999;
			}
		}
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;

		.section-title {
			font-size: 30rpx;
			font-weight: 600;
			color: #333;
		}

		.select-count {
			font-size: 24rpx;
			color: #52c41a;
		}
	}

	.project-select-section {
		background-color: #fff;
		margin: 0 20rpx 20rpx;
		border-radius: 16rpx;
		padding: 28rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

		.picker-wrapper {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 24rpx;
			background-color: #f8f8f8;
			border-radius: 12rpx;
			border: 1rpx solid #e8e8e8;
			transition: all 0.3s ease;

			&:active {
				background-color: #f0f0f0;
				border-color: #52c41a;
			}

			.picker-text {
				font-size: 28rpx;
				color: #333;
			}
		}
	}

	.student-select-section {
		background-color: #fff;
		margin: 0 20rpx 20rpx;
		border-radius: 16rpx;
		padding: 28rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

		.section-header {
			margin-bottom: 24rpx;
		}

		.student-list {
			display: grid;
			grid-template-columns: repeat(4, 1fr);
			gap: 16rpx;

			.student-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 20rpx 10rpx;
				background-color: #f8f8f8;
				border-radius: 12rpx;
				border: 2rpx solid transparent;
				transition: all 0.3s ease;
				position: relative;

				&:active {
					transform: scale(0.95);
				}

				&.selected {
					background-color: #f0f9eb;
					border-color: #52c41a;
				}

				.student-avatar {
					width: 60rpx;
					height: 60rpx;
					background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-bottom: 12rpx;
					box-shadow: 0 2rpx 8rpx rgba(82, 196, 26, 0.3);

					.avatar-text {
						font-size: 24rpx;
						font-weight: 700;
						color: #fff;
					}
				}

				.student-name {
					font-size: 24rpx;
					color: #333;
					text-align: center;
				}

				.check-icon {
					position: absolute;
					top: 8rpx;
					right: 8rpx;
					width: 28rpx;
					height: 28rpx;
					background-color: #52c41a;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
		}
	}

	

	.chart-section {
		margin: 0 20rpx;

		.stats-card {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 24rpx;
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;
			justify-content: space-around;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

			.stat-item {
				text-align: center;

				.stat-label {
					font-size: 24rpx;
					color: #999;
					display: block;
					margin-bottom: 8rpx;
				}

				.stat-value {
					font-size: 32rpx;
					font-weight: 700;
					color: #52c41a;
				}
			}

			.stat-divider {
				width: 1rpx;
				height: 50rpx;
				background-color: #eee;
			}
		}

		.chart-card {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 24rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

			.chart-header {
				margin-bottom: 20rpx;
				padding-left: 12rpx;
				border-left: 6rpx solid #52c41a;

				.chart-title {
					font-size: 30rpx;
					font-weight: 600;
					color: #333;
					display: block;
					margin-bottom: 6rpx;
				}

				.chart-desc {
					font-size: 24rpx;
					color: #999;
				}
			}

			.chart-box {
				width: 100%;
				height: 500rpx;
				background-color: #fafafa;
				border-radius: 12rpx;
				overflow: hidden;
			}
		}

		.legend-section {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 24rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

			.legend-title {
				font-size: 28rpx;
				font-weight: 600;
				color: #333;
				margin-bottom: 20rpx;
			}

			.legend-list {
				display: flex;
				flex-direction: column;
				gap: 16rpx;

				.legend-item {
					display: flex;
					align-items: center;
					gap: 12rpx;

					.legend-color {
						width: 24rpx;
						height: 24rpx;
						border-radius: 50%;
						flex-shrink: 0;
					}

					.legend-name {
						font-size: 26rpx;
						color: #333;
						font-weight: 600;
					}

					.legend-desc {
						font-size: 24rpx;
						color: #999;
					}
				}
			}
		}
	}
</style>
