<template>
	<view class="hunyang-container">
		<!-- 项目信息头部 -->
		<view class="card-section header-section" style="position: relative;">
			<view class="header-content">
				<view class="project-name">{{ name }}</view>
				<view class="total-duration">
					<text class="duration-label">计划总时长:</text>
					<text class="duration-value">{{ formatTotalDuration(totalDuration) }}</text>
				</view>
				<view class="total-progress">
					<text class="progress-text">
						总进度: {{ totalCompletedGroupPlans }}/{{ totalGroupPlans }} 计划
					</text>
				</view>
			</view>
			<view style="position: absolute; top: 20rpx; right: 30rpx;">
				<up-icon @click="Service.GoPage('/pages/userFunc/addHunyang?id='+planId)" name="setting" size="22"></up-icon>
			</view>
		</view>

		<!-- 分组训练区域 -->
		<view class="card-section groups-section" v-if="groupStates.length > 0">
			<view class="section-title">训练分组 (同时进行)</view>
			
			<view class="groups-list">
				<view 
					v-for="(groupState, groupIndex) in groupStates" 
					:key="groupIndex" 
					class="group-card"
					:class="{ 
						resting: groupState.isResting && !groupState.isCompleted,
						completed: groupState.isCompleted 
					}"
				>
					<!-- 分组头部 -->
					<view class="group-header">
						<view class="group-title-area">
							<text class="group-name">{{ groupState.groupName }}</text>
							<text class="group-plan-index">
								计划 {{ groupState.currentPlanIndex  }}/{{ groupState.plans.length }}
							</text>
						</view>
						<view class="status-tag" :class="{ completed: groupState.isCompleted }">
							<text v-if="groupState.isCompleted">已完成</text>
							<text v-else-if="groupState.isResting">休息中</text>
							<text v-else>训练中</text>
						</view>
					</view>

					<!-- 当前计划内容 -->
					<view class="plan-content" v-if="!groupState.isCompleted">
						<!-- 计划名称 -->
						<view class="plan-name">{{ groupState.currentPlan?.name }}</view>
						
						<!-- 圈数指示器 -->
						<view class="laps-indicator">
							<view 
								v-for="lap in groupState.currentPlan?.circle" 
								:key="lap"
								class="lap-dot"
								:class="{ completed: lap <= groupState.completedLaps }"
							></view>
						</view>
						
						<!-- 倒计时 -->
						<view class="countdown-box" :class="{ resting: groupState.isResting }">
							<text class="countdown-number">
								{{ formatCountdown(groupState.isResting ? groupState.restCountdown : groupState.countdown) }}
							</text>
						</view>
						
						<!-- 阶段提示 -->
						<view class="phase-hint" :class="{ resting: groupState.isResting }">
							<text v-if="groupState.isResting" class="phase-text">
								休息中 - 第 {{ groupState.completedLaps + 1 }} 圈准备
							</text>
							<text v-else class="phase-text">
								训练中 - 第 {{ groupState.completedLaps + 1 }} 圈
							</text>
						</view>

						<!-- 计划详情 -->
						<view class="plan-details">
							<view class="detail-box">
								<text class="detail-label">目标时间</text>
								<text class="detail-value">{{ groupState.currentPlan?.target }}秒</text>
							</view>
							<view class="detail-box">
								<text class="detail-label">休息时间</text>
								<text class="detail-value">{{ groupState.currentPlan?.rest }}秒</text>
							</view>
							<view class="detail-box">
								<text class="detail-label">圈数</text>
								<text class="detail-value">
									{{ groupState.completedLaps }}/{{ groupState.currentPlan?.circle }}
								</text>
							</view>
						</view>
					</view>

					<!-- 已完成 -->
					<view class="plan-completed" v-else>
						<u-icon name="checkmark-circle-fill" size="48" color="#4caf50"></u-icon>
						<text class="completed-label">分组完成</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 全部完成 -->
	<!-- 	<view class="card-section all-completed" v-if="isAllCompleted">
			<view class="completed-center">
				<u-icon name="checkmark-circle-fill" size="80" color="#4caf50"></u-icon>
				<text class="completed-title">训练完成</text>
				<text class="completed-desc">所有分组计划已执行完毕</text>
			</view>
		</view> -->

		<!-- 底部按钮 -->
		<view class="bottom-controls">
			<view class="controls-inner">
				<view v-if="!isRunning && !isAllCompleted" class="control-btn start-btn" @click="startTraining">
					<u-icon name="play-circle" size="32" color="#fff"></u-icon>
					<text class="btn-text">开始</text>
				</view>
				<view v-else-if="isRunning" class="control-btn pause-btn" @click="pauseTraining">
					<u-icon name="pause-circle" size="32" color="#fff"></u-icon>
					<text class="btn-text">暂停</text>
				</view>
				<view class="control-btn reset-btn" @click="resetTraining">
					<u-icon name="reload" size="32" color="#fff"></u-icon>
					<text class="btn-text">重置</text>
				</view>
			</view>
		</view>
	</view>
</template>

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

	// ==================== 类型 ====================
	interface PlanItem {
		name: string
		target: number
		rest: number
		circle: number
	}

	interface GroupData {
		groupName: string
		group: PlanItem[]
	}

	interface GroupState {
		groupName: string
		plans: PlanItem[]
		currentPlanIndex: number
		currentPlan: PlanItem | null
		countdown: number
		restCountdown: number
		completedLaps: number
		isResting: boolean
		isCompleted: boolean
	}

	// ==================== 数据 ====================
	const planId = ref('')
	const name = ref('')
	const groupStates = ref<GroupState[]>([])
	const isRunning = ref(false)
	const timer = ref<number | null>(null)

	// ==================== 计算属性 ====================
	const totalGroupPlans = computed(() => {
		return groupStates.value.reduce((sum, gs) => sum + gs.plans.length, 0)
	})

	const totalCompletedGroupPlans = computed(() => {
		return groupStates.value.reduce((sum, gs) => {
			if (gs.isCompleted) return sum + gs.plans.length
			return sum + gs.currentPlanIndex
		}, 0)
	})

	const isAllCompleted = computed(() => {
		return groupStates.value.length > 0 && groupStates.value.every(gs => gs.isCompleted)
	})

	const totalDuration = computed(() => {
		return groupStates.value.reduce((total, gs) => {
			return total + gs.plans.reduce((sum, plan) => {
				return sum + plan.target * plan.circle + plan.rest * (plan.circle - 1)
			}, 0)
		}, 0)
	})

	// ==================== 生命周期 ====================
	onLoad((data: any) => {
		planId.value = data.id
	})

	onShow(() => {
		getPlanInfo()
	})

	onUnmounted(() => {
		stopTimer()
	})

	// ==================== 方法 ====================
	const getPlanInfo = () => {
		PlanService.GetPlanInfo(planId.value).then(res => {
			if (res.code === 0) {
				name.value = res.data.plan.name
				const data: GroupData[] = JSON.parse(res.data.plan.project)
				initGroups(data)
			} else {
				Service.Msg(res.msg)
			}
		}).catch(() => {
			Service.Msg('获取计划信息失败')
		})
	}

	const initGroups = (data: GroupData[]) => {
		groupStates.value = data.map(g => ({
			groupName: g.groupName,
			plans: g.group,
			currentPlanIndex: 0,
			currentPlan: g.group[0] || null,
			countdown: 0,
			restCountdown: 0,
			completedLaps: 0,
			isResting: false,
			isCompleted: g.group.length === 0
		}))
	}

	const startTraining = () => {
		if (groupStates.value.length === 0) {
			Service.Msg('暂无训练计划')
			return
		}
		if (isAllCompleted.value) {
			Service.Msg('训练已完成')
			return
		}

		isRunning.value = true

		// 初始化未开始的分组
		groupStates.value.forEach(gs => {
			if (!gs.isCompleted && gs.countdown === 0 && !gs.isResting) {
				gs.countdown = gs.currentPlan?.target || 0
			}
		})

		// 启动计时器
		timer.value = setInterval(() => {
			let allDone = true

			groupStates.value.forEach(gs => {
				if (gs.isCompleted) return
				allDone = false

				if (gs.isResting) {
					// 休息倒计时
					gs.restCountdown -= 0.01
					if (gs.restCountdown <= 0) {
						gs.isResting = false
						gs.restCountdown = 0
						gs.countdown = gs.currentPlan?.target || 0
					}
				} else {
					// 训练倒计时
					gs.countdown -= 0.01
					if (gs.countdown <= 0) {
						gs.completedLaps++

						if (gs.completedLaps >= (gs.currentPlan?.circle || 0)) {
							// 当前计划完成，切换到下一个
							gs.currentPlanIndex++
							if (gs.currentPlanIndex >= gs.plans.length) {
								// 分组全部完成
								gs.isCompleted = true
								gs.currentPlan = null
							} else {
								// 开始下一个计划
								gs.currentPlan = gs.plans[gs.currentPlanIndex]
								gs.countdown = gs.currentPlan.target
								gs.completedLaps = 0
							}
						} else {
							// 进入休息
							gs.isResting = true
							gs.restCountdown = gs.currentPlan?.rest || 0
						}
					}
				}
			})

			if (allDone) {
				stopTimer()
			}
		}, 10)
	}

	const pauseTraining = () => {
		stopTimer()
	}

	const stopTimer = () => {
		isRunning.value = false
		if (timer.value) {
			clearInterval(timer.value)
			timer.value = null
		}
	}

	const resetTraining = () => {
		stopTimer()
		const data = groupStates.value.map(gs => ({
			groupName: gs.groupName,
			group: gs.plans
		}))
		initGroups(data)
	}

	const formatCountdown = (seconds: number): string => {
		const s = Math.max(0, Math.floor(seconds))
		const m = Math.floor(s / 60)
		const sec = s % 60
		return `${m.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`
	}

	const formatTotalDuration = (seconds: number): string => {
		if (seconds === 0) return '0分0秒'
		const m = Math.floor(seconds / 60)
		const s = Math.floor(seconds % 60)
		return `${m}分${s}秒`
	}
</script>

<style lang="scss" scoped>
	.hunyang-container {
		min-height: 100vh;
		background-color: #f5f7fa;
		padding: 20rpx;
		padding-bottom: 200rpx;
	}

	.card-section {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
	}

	.header-section {
		.header-content {
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 12rpx;
		}

		.project-name {
			font-size: 36rpx;
			font-weight: 600;
			color: #333;
		}

		.total-duration {
			display: flex;
			align-items: center;
			gap: 8rpx;
			background: #f0f0f0;
			padding: 10rpx 20rpx;
			border-radius: 20rpx;

			.duration-label {
				font-size: 24rpx;
				color: #666;
			}

			.duration-value {
				font-size: 26rpx;
				font-weight: 500;
				color: #333;
			}
		}

		.total-progress {
			.progress-text {
				font-size: 24rpx;
				color: #999;
			}
		}
	}

	.section-title {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 20rpx;
		padding-left: 16rpx;
		position: relative;

		&::before {
			content: '';
			position: absolute;
			left: 0;
			top: 50%;
			transform: translateY(-50%);
			width: 4rpx;
			height: 24rpx;
			background: #4a90e2;
			border-radius: 2rpx;
		}
	}

	.groups-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.group-card {
		background: #f8f9fa;
		border-radius: 12rpx;
		padding: 24rpx;
		border: 2rpx solid #e8e8e8;
		transition: all 0.2s ease;

		&.resting {
			border-color: #ff9800;
			background: #fffbf0;
		}

		&.completed {
			border-color: #4caf50;
			background: #f0f9f0;
			opacity: 0.8;
		}
	}

	.group-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.group-title-area {
		display: flex;
		flex-direction: column;
		gap: 4rpx;
	}

	.group-name {
		font-size: 30rpx;
		font-weight: 600;
		color: #333;
	}

	.group-plan-index {
		font-size: 22rpx;
		color: #999;
	}

	.status-tag {
		padding: 6rpx 16rpx;
		border-radius: 8rpx;
		background: #e6f0ff;
		font-size: 22rpx;
		color: #4a90e2;
		font-weight: 500;

		&.completed {
			background: #e8f5e9;
			color: #4caf50;
		}
	}

	.plan-content {
		text-align: center;
	}

	.plan-name {
		font-size: 34rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 16rpx;
	}

	/* 圈数指示器 */
	.laps-indicator {
		display: flex;
		justify-content: center;
		gap: 12rpx;
		margin-bottom: 16rpx;

		.lap-dot {
			width: 16rpx;
			height: 16rpx;
			border-radius: 50%;
			background: #e0e0e0;
			transition: all 0.3s ease;

			&.completed {
				background: #4caf50;
				transform: scale(1.2);
			}
		}
	}

	/* 阶段提示 */
	.phase-hint {
		margin-bottom: 16rpx;
		padding: 8rpx 20rpx;
		border-radius: 20rpx;
		background: #e6f0ff;
		display: inline-block;

		.phase-text {
			font-size: 24rpx;
			color: #4a90e2;
			font-weight: 500;
		}

		&.resting {
			background: #fff8e1;

			.phase-text {
				color: #ff9800;
			}
		}
	}

	.countdown-box {
		margin: 20rpx 0;

		.countdown-number {
			font-size: 72rpx;
			font-weight: bold;
			font-family: 'Helvetica Neue', monospace;
			color: #4a90e2;
			letter-spacing: 2rpx;
		}

		&.resting .countdown-number {
			color: #ff9800;
			animation: flash 0.5s ease-in-out infinite;
		}
	}

	.plan-details {
		display: flex;
		justify-content: space-around;
		margin-top: 20rpx;
		padding-top: 16rpx;
		border-top: 1rpx dashed #e0e0e0;
	}

	.detail-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 6rpx;
	}

	.detail-label {
		font-size: 22rpx;
		color: #999;
	}

	.detail-value {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
	}

	.plan-completed {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 30rpx;
		gap: 12rpx;

		.completed-label {
			font-size: 28rpx;
			color: #4caf50;
			font-weight: 500;
		}
	}

	.all-completed {
		.completed-center {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 40rpx;
			gap: 16rpx;
		}

		.completed-title {
			font-size: 36rpx;
			font-weight: 600;
			color: #4caf50;
		}

		.completed-desc {
			font-size: 26rpx;
			color: #999;
		}
	}

	.bottom-controls {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #ffffff;
		padding: 16rpx 24rpx calc(24rpx + env(safe-area-inset-bottom));
		z-index: 100;
		border-top: 1rpx solid #e8e8e8;
	}

	.controls-inner {
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 20rpx;
		max-width: 750rpx;
		margin: 0 auto;
	}

	.control-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8rpx;
		padding: 20rpx;
		border-radius: 12rpx;
		transition: all 0.2s ease;
		flex: 1;

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

	.btn-text {
		font-size: 24rpx;
		font-weight: 500;
		color: #fff;
	}

	.start-btn {
		background: #4caf50;
	}

	.pause-btn {
		background: #ff9800;
	}

	.reset-btn {
		background: #2196f3;
	}

	@keyframes flash {
		0%, 100% { opacity: 1; }
		50% { opacity: 0.6; }
	}
</style>
