<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="select-section">
			<view class="select-label">
				<view class="label-text" style="margin-bottom: 20rpx;">选择项目</view>
				<view class="picker-wrapper" @click="showProject=true">
					<text class="picker-text">{{ selectProcet || '请选择项目' }}</text>
					<u-icon name="arrow-down" size="18" color="#999"></u-icon>
				</view>
			</view>
		</view>
		<up-picker v-model:show="showProject" keyName="name" valueName="planId" @confirm="selectProcetFunc"
			:columns="projectOptions"></up-picker>

		<!-- 日期选择 -->
		<view class="date-filter" style="margin: 20rpx 20rpx 0;" v-if="selectProcet">
			<view class="date-picker" @click="openCalendar()">
				<up-icon name="calendar" color="#3B82F6" size="25"></up-icon>
				<view class="date-text">
					<text class="label">开始日期</text>
					<text class="value">{{ begin || '请选择' }}</text>
				</view>
			</view>
			<view class="date-picker" @click="openCalendar()">
				<up-icon name="calendar" color="#3B82F6" size="25"></up-icon>
				<view class="date-text">
					<text class="label">结束日期</text>
					<text class="value">{{ end || '请选择' }}</text>
				</view>
			</view>
		</view>

		<!-- ==================== 学生选择区域 ==================== -->
		<!-- 仅在选择项目和时间后显示 -->
		<view class="student-select-section" v-if="selectProcet && begin && 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.studentId"
					:class="['student-item', { 'selected': selectedStudentIds.includes(student.studentId) }]"
					@click="toggleStudent(student.studentId)">
					<!-- 学生头像（使用首字母作为头像） -->
					<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.studentId)">
						<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">{{ selectProcet }}</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>

			<!-- 折线图卡片 -->
			<view class="chart-card">
				<view class="chart-header">
					<text class="chart-title">成绩趋势对比</text>
					<text class="chart-desc">历史训练成绩变化曲线</text>
				</view>
				<!-- 折线图容器 -->
				<scroll-view class="chart-scroll" scroll-x :show-scrollbar="false">
					<view class="chart-box" :style="{ width: chartWidth + 'rpx' }">
						<qiun-data-charts type="line" :opts="lineOpts" :chartData="lineChartData" :ontouch="true" />
					</view>
				</scroll-view>
			</view>

		</view>

		<!-- 日历弹窗 -->
		<up-calendar :show="showCalendar" mode="date" minDate='1776240407000' @confirm="calendarConfirm"
			@close="calendarClose">
		</up-calendar>
	</view>
</template>

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

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

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

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

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

	// 项目选择
	let showProject = ref(false)
	let selectProcet = ref('')
	let selectId = ref('')

	// 日期选择
	const begin = ref<string>('')
	const end = ref<string>('')
	const showCalendar = ref(false)

	const projectOptions = ref<Array<any>>([[]])

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

	/**
	 * 学生接口
	 * 定义学生的基本信息
	 */
	interface Student {
		studentId : 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.studentId)
		)
	})

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

	// 计算图表宽度（根据数据点数量动态调整）
	const chartWidth = computed(() => {
		const categoryCount = lineChartData.value.categories.length
		if (categoryCount <= 6) return 700
		// 每个数据点分配 100rpx，最小 700rpx
		return Math.max(700, categoryCount * 100)
	})

	// 折线图配置选项
	const lineOpts = ref({
		color: chartColors,
		padding: [15, 10, 0, 15],
		legend: {
			show: true,
			position: 'bottom',
			itemGap: 30
		},
		xAxis: {
			disableGrid: true,
			rotateLabel: true,
			scrollShow: true,
			scrollAlign: 'left'
		},
		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[]
	})



	onLoad(() => {
		getProjectData()
	})

	onShow(() => {

	})





	const getProjectData = () => {
		PlanService.GetPlanListNoPage('计时项目').then(res => {
			if (res.code == 0) {
				projectOptions.value[0] = res.data.list
			} else {
				Service.Msg(res.msg)
			}
		})
	}

	const selectProcetFunc = (e : any) => {
		selectProcet.value = e.value[0].name
		selectId.value = e.value[0].planId
		selectedStudentIds.value = []
		loadProjectStudents(selectId.value)
	}

	const openCalendar = () => {
		showCalendar.value = true
	}

	const calendarConfirm = (e : any) => {
		begin.value = e[0]
		end.value = e[e.length - 1]
		showCalendar.value = false
	}

	const calendarClose = () => {
		showCalendar.value = false
	}

	const loadProjectStudents = (projectId : string) => {
		PlanService.GetPlanInfo(projectId).then(res => {
			if (res.code == 0) {
				projectStudents.value = res.data.plan.users
			} else {
				Service.Msg(res.msg)
			}
		})
	}

	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)
		}
		let studentIdList = selectedStudentIds.value.map((item) => {
			return item
		})
		let data = {
			planId: selectId.value,
			studentId: JSON.stringify(studentIdList),
			sTime: begin.value,
			eTime: end.value
		}
		interface DataItem {
			name : string
			data : any[]
		}


		const xData = ref<DataItem[]>(
			Array.from({ length: studentIdList.length }, () => ({
				name: '',
				data: []
			}))
		)
		PlanService.GetQuxianLog(data).then(res => {
			if (res.code == 0) {

				res.data.list.map((item : any) => {
					lineChartData.value.categories.push(item.dayTime)
					item.data.map((content : any, index : any) => {
						xData.value[index].name = content.studentName
						xData.value[index].data.push(content.time)
					})
				})
				console.log(xData.value);
				lineChartData.value.series = xData.value
			} else {
				Service.Msg(res.msg)
			}
		})

	}
</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;
		}
	}

	.date-filter {
		display: flex;
		gap: 24rpx;

		.date-picker {
			flex: 1;
			display: flex;
			align-items: center;
			gap: 16rpx;
			background-color: #fff;
			border-radius: 16rpx;
			padding: 20rpx;

			.date-text {
				.label {
					display: block;
					font-size: 26rpx;
					color: #999;
				}

				.value {
					display: block;
					font-size: 30rpx;
					color: #333;
					margin-top: 4rpx;
					font-weight: 600;
				}
			}
		}
	}

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

		.select-label {
			margin-bottom: 16rpx;

			.label-text {
				font-size: 26rpx;
				font-weight: 600;
				color: #666;
			}
		}

		.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: #faad14;
				transform: scale(0.98);
			}

			.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-scroll {
				width: 100%;
				height: 500rpx;
				background-color: #fafafa;
				border-radius: 12rpx;
				overflow: hidden;
				white-space: nowrap;

				.chart-box {
					height: 100%;
					display: inline-block;
				}
			}
		}

		.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>