<template>
	<view class="curve-container">
		<!-- 项目选择卡片 -->
		<view class="filter-card ">
			<view class="card-title">
				<u-icon name="grid" size="18" color="#1890ff"></u-icon>
				<text>选择项目</text>
			</view>
			<view class="picker-row" @click="showProject = true">
				<text class="picker-text" :class="{ placeholder: !selectProcet }">{{ selectProcet || '请选择项目' }}</text>
				<u-icon name="arrow-right" size="16" color="#bbb"></u-icon>
			</view>
		</view>
		<!-- 项目选择弹窗 -->
		<up-popup :show="showProject" mode="center" round="32" :safeAreaInsetBottom="false"
			@close="showProject = false">
			<view class="project-popup-content">
				<view class="modal-header">
					<text class="modal-title">选择项目</text>
					<view class="modal-close" @click="showProject = false">
						<u-icon name="close" size="20" color="#999"></u-icon>
					</view>
				</view>
				<scroll-view scroll-y class="popup-project-list">
					<view class="project-list-inner">
						<view v-for="(project, index) in projectOptions[0]" :key="project.planId" class="project-item"
							@click="selectProcetFunc(project)">
							<view class="item-info">
								<text class="item-name">{{ project.name }}</text>
							</view>
						</view>
						<view v-if="!projectOptions[0] || projectOptions[0].length === 0" class="empty-project">
							<text class="empty-text">暂无项目</text>
						</view>
					</view>
				</scroll-view>
			</view>
		</up-popup>

		<!-- 日期选择卡片 -->
		<view class="filter-card " v-if="selectProcet">
			<view class="card-title">
				<u-icon name="calendar" size="18" color="#13c2c2"></u-icon>
				<text>日期范围</text>
			</view>
			<view class="date-filter" @click="openCalendar">
				<view class="date-item">
					<text class="date-label">开始日期</text>
					<text class="date-value" :class="{ placeholder: !begin }">{{ begin || '请选择' }}</text>
				</view>
				<view class="date-divider"></view>
				<view class="date-item">
					<text class="date-label">结束日期</text>
					<text class="date-value" :class="{ placeholder: !end }">{{ end || '请选择' }}</text>
				</view>
				<u-icon name="arrow-right" size="16" color="#bbb" class="date-arrow"></u-icon>
			</view>
		</view>

		<!-- 学生选择卡片 -->
		<view class="filter-card " v-if="selectProcet && begin && projectStudents.length > 0">
			<view class="section-header">
				<view class="card-title">
					<u-icon name="account" size="18" color="#52c41a"></u-icon>
					<text>选择学员</text>
				</view>
				<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)">
					<text class="student-name">{{ student.name }}</text>
					<view class="check-icon" v-if="selectedStudentIds.includes(student.studentId)">
						<u-icon name="checkmark" size="14" color="#fff"></u-icon>
					</view>
				</view>
			</view>
		</view>

		<!-- 图表区域 -->
		<view class="chart-section" v-if="selectedStudentIds.length > 0 && !showCalendar">
			<!-- 统计概览 -->
			<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>

		<!-- 日历弹窗 -->
		<uni-calendar ref="calendar" :insert="false"  range='true' :lunar="true" @confirm="calendarConfirm" />
	</view>
</template>

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

	const MAX_SELECTED_STUDENTS = 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>>([[]])

	interface Student {
		studentId : string
		name : string
	}

	interface StudentTrainingRecord {
		studentId : string
		studentName : string
		time : number
		recordDate : string
		recordFullDate : string
		round : number
	}

	const projectStudents = ref<Student[]>([])
	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
		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[]
	})
	
	let calendar=ref(null)
	
	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 = (project : any) => {
		selectProcet.value = project.name
		selectId.value = project.planId
		showProject.value = false
		selectedStudentIds.value = []
		begin.value = ''
		end.value = ''
		projectStudents.value = []
		lineChartData.value.categories = []
		lineChartData.value.series = []
		loadProjectStudents(selectId.value)
	}

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

	const calendarConfirm = (e : any) => {
		const newDate = e.range
		if (e.range.before !== begin.value  ||  e.range.after !== end.value ) {
			selectedStudentIds.value = []
			lineChartData.value.categories = []
			lineChartData.value.series = []
		}

		begin.value = newDate.before
		if( e.range.after){
			end.value = e.range.after
		}else{
			end.value = e.range.before
		}
		showCalendar.value = false
	}

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

	const loadProjectStudents = (projectId : string) => {
		studentService.GetStudentList('').then(res => {
			if (res.code == 0) {
				projectStudents.value = res.data
			} 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)
		}
		const studentIdList = selectedStudentIds.value.map((item) => item)
		const reqData = {
			planId: selectId.value,
			studentId: JSON.stringify(studentIdList),
			sTime: begin.value,
			eTime: end.value
		}

		PlanService.GetQuxianLog(reqData).then(res => {
			if (res.code == 0) {
				const list = res.data.list || []
				const days = list.map((item : any) => item.dayTime)

				// 按已选学生顺序初始化 series，缺省日期填充 0
				const series = studentIdList.map(id => {
					const student = projectStudents.value.find(s => s.studentId === id)
					return {
						name: student?.name || '',
						data: new Array(days.length).fill(0)
					}
				})

				// 建立 studentId -> series 索引映射
				const idToIndex : Record<string, number> = {}
				studentIdList.forEach((id, idx) => {
					idToIndex[id] = idx
				})

				// 按日期填充数据
				list.forEach((dayItem : any, dayIndex : number) => {
					; (dayItem.data || []).forEach((record : any) => {
						const sIdx = idToIndex[record.studentId]
						if (sIdx !== undefined) {
							series[sIdx].data[dayIndex] = record.time ?? 0
							if (!series[sIdx].name && record.studentName) {
								series[sIdx].name = record.studentName
							}
						}
					})
				})

				lineChartData.value.categories = days
				lineChartData.value.series = series
			} else {
				Service.Msg(res.msg)
			}
		})
	}
</script>

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

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

	/* 通用卡片 */
	.filter-card {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
		// border-left: 8rpx solid #999;

	}

	.card-title {
		display: flex;
		align-items: center;
		gap: 10rpx;
		font-size: 30rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 16rpx;
	}

	/* 项目选择 */
	.picker-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 22rpx 24rpx;
		background: #f5f7fa;
		border-radius: 12rpx;
		border: 1rpx solid #e4e8ee;
		transition: all 0.2s;

		&:active {
			background: #eef1f6;
		}

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

			&.placeholder {
				color: #999;
				font-weight: 400;
			}
		}
	}

	/* 日期选择 */
	.date-filter {
		display: flex;
		align-items: center;
		background: #f0fafa;
		border-radius: 12rpx;
		padding: 22rpx 24rpx;
		border: 1rpx solid #d6f0f0;
		transition: all 0.2s;

		&:active {
			background: #e6f5f5;
		}
	}

	.date-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 6rpx;
	}

	.date-label {
		font-size: 24rpx;
		color: #666;
		font-weight: 500;
	}

	.date-value {
		font-size: 30rpx;
		color: #333;
		font-weight: 600;

		&.placeholder {
			color: #999;
			font-weight: 400;
		}
	}

	.date-divider {
		width: 2rpx;
		height: 50rpx;
		background: #b2dfdb;
		margin: 0 20rpx;
	}

	.date-arrow {
		margin-left: 12rpx;
	}

	/* 学生选择区域 */
	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;

		.select-count {
			font-size: 24rpx;
			color: #52c41a;
			font-weight: 600;
			background: #f0f9eb;
			padding: 6rpx 16rpx;
			border-radius: 20rpx;
		}
	}

	.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: #f5f7fa;
		border-radius: 12rpx;
		border: 2rpx solid transparent;
		transition: all 0.2s;
		position: relative;

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

		&.selected {
			background: #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;
			font-weight: 500;
		}

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

	/* 图表区域 */
	.chart-section {
		margin-top: 4rpx;
		position: relative;
		z-index: 1;
	}

	.stats-card {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-around;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
		// border-left: 8rpx solid #faad14;

		.stat-item {
			text-align: center;

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

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

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

	.chart-card {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
		// border-left: 8rpx solid #52c41a;

		.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;
			border: 1rpx solid #f0f0f0;

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

	/* 项目选择弹窗 */
	.project-popup-content {
		width: 680rpx;
		max-height: 70vh;
		background: linear-gradient(180deg, #fafbfc 0%, #fff 100%);
		border-radius: 32rpx;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		box-shadow: 0 24rpx 80rpx rgba(0, 0, 0, 0.25), 0 0 0 1rpx rgba(0, 0, 0, 0.04);
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 36rpx 32rpx 28rpx;
		background: linear-gradient(180deg, #fafbfc 0%, #fff 100%);
		border-bottom: 1rpx solid rgba(0, 0, 0, 0.06);

		.modal-title {
			font-size: 36rpx;
			font-weight: 700;
			background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
			-webkit-background-clip: text;
			-webkit-text-fill-color: transparent;
			background-clip: text;
		}

		.modal-close {
			width: 60rpx;
			height: 60rpx;
			border-radius: 50%;
			background: linear-gradient(135deg, #f5f5f5 0%, #f0f0f0 100%);
			display: flex;
			align-items: center;
			justify-content: center;
			transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);

			&:active {
				background: linear-gradient(135deg, #e8e8e8 0%, #e0e0e0 100%);
				transform: scale(0.92);
			}
		}
	}

	.popup-project-list {
		max-height: 55vh;
		padding: 24rpx 28rpx;
	}

	.project-list-inner {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	.project-item {
		display: flex;
		align-items: center;
		gap: 16rpx;
		padding: 20rpx 24rpx;
		background: linear-gradient(135deg, #fff 0%, #fafbfc 100%);
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06), 0 0 0 1rpx rgba(0, 0, 0, 0.04) inset;
		position: relative;
		overflow: hidden;
		border-radius: 16rpx;

		&::after {
			content: '';
			position: absolute;
			top: 0;
			left: 0;
			width: 4rpx;
			height: 100%;
			background: linear-gradient(180deg, #1890ff 0%, #40a9ff 100%);
			opacity: 0;
			transition: opacity 0.3s ease;
		}

		&:active::after {
			opacity: 1;
		}

		.item-info {
			flex: 1;
			min-width: 0;
			display: flex;
			align-items: center;

			.item-name {
				font-size: 28rpx;
				font-weight: 600;
				color: #333;
				letter-spacing: 1rpx;
			}
		}
	}

	.empty-project {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 60rpx 0;

		.empty-text {
			font-size: 28rpx;
			color: #999;
		}
	}
</style>