<template>
	<up-navbar v-if="!isLandscape" title="混氧项目" placeholder='true' :autoBack="true">
	</up-navbar>
	<view class="hunyang-container">
		<!-- 项目信息头部 -->
		<view class="card-section header-section">
			<view class="header-content">
				<view class="project-name">{{ name }}</view>
				<view class="header-action" :style="{    'margin-right': isLandscape?'70rpx':'0'  } "
					@click="Service.GoPage('/pages/userFunc/addHunyang?id='+planId)">
					<up-icon name="setting" size="22"></up-icon>
				</view>
			</view>
		</view>

		<!-- 分组训练区域 -->
		<view class="card-section groups-section" v-if="groupStates.length > 0">
			<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">
							<view class="group-name">{{ groupState.groupName }}</view>
						</view>
						<view class="plan-name">{{ groupState.currentPlan?.name }}</view>
						<text class="group-plan-index">
							{{ groupState.allTime }}
							<!-- {{ groupState.currentPlanIndex  }}/{{ groupState.plans.length }} -->
						</text>
					</view>

					<!-- 当前计划内容 -->
					<view class="plan-content" v-if="!groupState.isCompleted">
						<!-- 倒计时 -->
						<view class="countdown-box" :style="{ 'margin': !isLandscape? '23rpx 0':'4rpx 0'  }"
							:class="{ resting: groupState.isResting }">
							<view class="countdown-number"
								:style="{transform: !isLandscape? 'scale(2, 2)':'scale(1.3, 1.4 )'}">
								{{ formatCountdown(groupState.isResting ? groupState.restCountdown : groupState.countdown) }}
							</view>
						</view>



						<!-- 计划详情 -->
						<view class="plan-details">
							<view v-if="!isLandscape" class="group-controls">
								<view v-if="!groupState.isRunning && !groupState.isCompleted"
									class="group-control-btn group-start-btn" @click="startGroup(groupState)">
									<u-icon name="play-circle" size="24" color="#fff"></u-icon>
									<text>开始</text>
								</view>
								<view v-else-if="groupState.isRunning" class="group-control-btn group-pause-btn"
									@click="pauseGroup(groupState)">
									<u-icon name="pause-circle" size="24" color="#fff"></u-icon>
									<text>暂停</text>
								</view>
							</view>
							<text class="detail-badge">
								M:{{ formatCountdown(groupState.currentPlan?.target) }}
							</text>
							<text class="detail-badge">
								X:{{ groupState.currentPlan?.rest }}
							</text>
							<text class="detail-badge">
								Q:  {{ groupState.completedLaps }}/{{ groupState.currentPlan?.circle }}
							</text>
							<view v-if="!isLandscape" class="group-controls">
								<view class="group-control-btn group-reset-btn" @click="resetGroup(groupIndex)">
									<u-icon name="reload" size="24" color="#fff"></u-icon>
									<text>重置</text>
								</view>
							</view>
						</view>

						<!-- 分组控制按钮 -->
						<view v-if="isLandscape" class="group-controls">
							<view v-if="!groupState.isRunning && !groupState.isCompleted"
								class="group-control-btn group-start-btn" @click="startGroup(groupState)">
								<u-icon name="play-circle" size="24" color="#fff"></u-icon>
								<text>开始</text>
							</view>
							<view v-else-if="groupState.isRunning" class="group-control-btn group-pause-btn"
								@click="pauseGroup(groupState)">
								<u-icon name="pause-circle" size="24" color="#fff"></u-icon>
								<text>暂停</text>
							</view>
							<view class="group-control-btn group-reset-btn" @click="resetGroup(groupIndex)">
								<u-icon name="reload" size="24" color="#fff"></u-icon>
								<text>重置</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>
						<text class="completed-label" style="color: var(--nav-mian); font-size: 24rpx;"
							@click="resetGroup(groupIndex)">重置</text>
					</view>
				</view>
			</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
		allTime : string
		group : PlanItem[]
	}

	interface GroupState {
		groupName : string
		plans : PlanItem[]
		currentPlanIndex : number
		currentPlan : PlanItem | null
		countdown : number
		restCountdown : number
		completedLaps : number
		isResting : boolean
		isCompleted : boolean
		isPlanCompleted : boolean // 当前计划是否已完成（最后一圈休息后切换计划）
		isRunning : boolean // 当前分组是否正在运行
	}

	// ==================== 数据 ====================
	const planId = ref('')
	const name = ref('')
	const groupStates = ref<GroupState[]>([])
	const isRunning = ref(false)
	const timer = ref<number | null>(null)
	const planTotalDuration = ref(0) // 接口返回的计划总时长
	const isLandscape = ref(false) // 是否为横屏

	// ==================== 计算属性 ====================
	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
		getPlanInfo()
	})
	onShow(() => {
		checkOrientation()
		uni.onWindowResize(checkOrientation)
	})

	onShow(() => {
		uni.$on('change',()=>{
			getPlanInfo()
		})
	})

	onUnmounted(() => {
		stopTimer()
		uni.offWindowResize(checkOrientation)
	})

	// ==================== 方法 ====================
	const checkOrientation = () => {
		const info = uni.getSystemInfoSync()
		isLandscape.value = info.windowWidth > info.windowHeight
	}

	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,
			allTime: g.allTime,
			plans: g.group,
			currentPlanIndex: 0,
			currentPlan: g.group[0] || null,
			countdown: 0,
			restCountdown: 0,
			completedLaps: 0,
			isResting: false,
			isCompleted: g.group.length === 0,
			isPlanCompleted: false,
			isRunning: false
		}))
	}

	// ==================== 分组级控制 ====================
	const startGroup = (gs : GroupState) => {
		if (gs.isCompleted) {
			Service.Msg('该分组已完成')
			return
		}

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

		gs.isRunning = true

		// 如果全局计时器未运行，启动它
		if (!timer.value) {
			startGlobalTimer()
		}
	}

	const pauseGroup = (gs : GroupState) => {
		gs.isRunning = false

		// 检查是否还有运行的分组，如果没有则停止全局计时器
		const hasRunning = groupStates.value.some(g => g.isRunning)
		if (!hasRunning) {
			stopTimer()
		}
	}

	const resetGroup = (groupIndex : number) => {
		const gs = groupStates.value[groupIndex]
		if (!gs) return

		// 停止当前分组运行
		gs.isRunning = false

		// 重置分组状态
		gs.currentPlanIndex = 0
		gs.currentPlan = gs.plans[0] || null
		gs.countdown = 0
		gs.restCountdown = 0
		gs.completedLaps = 0
		gs.isResting = false
		gs.isCompleted = gs.plans.length === 0
		gs.isPlanCompleted = false

		// 检查是否还有运行的分组，如果没有则停止全局计时器
		const hasRunning = groupStates.value.some(g => g.isRunning)
		if (!hasRunning) {
			stopTimer()
		}
	}

	// ==================== 全局计时器 ====================
	const startGlobalTimer = () => {
		isRunning.value = true

		timer.value = setInterval(() => {
			let hasRunningGroup = false
			let allCompleted = true

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

				if (!gs.isRunning) return
				hasRunningGroup = true

				if (gs.isResting) {
					// 休息倒计时
					gs.restCountdown -= 0.01
					if (gs.restCountdown <= 0) {
						gs.isResting = false
						gs.restCountdown = 0

						if (gs.isPlanCompleted) {
							// 当前计划所有圈已完成，切换到下一个计划
							gs.isPlanCompleted = false
							gs.currentPlanIndex++
							if (gs.currentPlanIndex >= gs.plans.length) {
								// 分组全部完成
								gs.isCompleted = true
								gs.currentPlan = null
								gs.isRunning = false
							} else {
								// 开始下一个计划
								gs.currentPlan = gs.plans[gs.currentPlanIndex]
								gs.countdown = gs.currentPlan.target
								gs.completedLaps = 0
							}
						} else {
							// 继续当前计划的下一圈
							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.isPlanCompleted = true
							gs.isResting = true
							gs.restCountdown = gs.currentPlan?.rest || 0
						} else {
							// 进入休息
							gs.isResting = true
							gs.restCountdown = gs.currentPlan?.rest || 0
						}
					}
				}
			})

			if (allCompleted || !hasRunningGroup) {
				stopTimer()
			}
		}, 10)
	}

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

		// 启动所有未完成的组
		groupStates.value.forEach(gs => {
			if (!gs.isCompleted) {
				startGroup(gs)
			}
		})
	}

	const pauseTraining = () => {
		groupStates.value.forEach(gs => {
			gs.isRunning = false
		})
		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,
			allTime: gs.allTime,
			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 {
		position: relative;

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

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

		.header-action {
			position: absolute;
			top: 24rpx;
			right: 24rpx;
			padding: 4rpx;
		}

		.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;
		gap: 4rpx;
	}

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

	.group-name {
		font-size: 22rpx;
		font-weight: 600;
		color: #333;
		width: 78rpx;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.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: 22rpx;
		font-weight: 600;
		color: #333;


	}

	/* 圈数指示器 */
	.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 {

		.countdown-number {
			font-size: 72rpx;
			font-weight: bold;
			color: #000;
		}

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

	.plan-details {
		display: flex;
		justify-content: space-between;
		align-items: center;
		gap: 16rpx;
	}

	.detail-badge {
		display: inline-flex;
		align-items: center;
		gap: 4rpx;
		font-size: 24rpx;
		color: #666;
		background: #f5f7fa;
		padding: 8rpx 4rpx;
		border-radius: 24rpx;
	}

	.detail-badge-tag {
		width: 32rpx;
		height: 32rpx;
		background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
		border-radius: 50%;
		font-size: 20rpx;
		color: #fff;
		font-weight: 700;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}

	/* 分组控制按钮 */
	.group-controls {
		display: flex;
		justify-content: space-between;
		gap: 20rpx;

		padding-top: 16rpx;
	}

	.group-control-btn {
		display: flex;
		align-items: center;
		gap: 8rpx;
		padding: 12rpx 24rpx;
		border-radius: 24rpx;
		font-size: 24rpx;
		color: #fff;
		transition: all 0.2s ease;

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

	.group-start-btn {
		background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
	}

	.group-pause-btn {
		background: linear-gradient(135deg, #faad14 0%, #d48806 100%);
	}

	.group-reset-btn {
		background: linear-gradient(135deg, #ff4d4f 0%, #d9363e 100%);
	}

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

	/* 横屏适配 */
	@media (orientation: landscape) {
		.hunyang-container {
			padding: 16rpx;
			padding-bottom: 140rpx;
		}

		.card-section {
			padding: 16rpx 20rpx;
			margin-bottom: 12rpx;
		}

		.header-section {
			.header-content {
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
			}

			.header-action {
				position: static;
			}

			.project-name {
				font-size: 34rpx;
				letter-spacing: 2rpx;
			}
		}

		.section-title {
			font-size: 26rpx;
			margin-bottom: 12rpx;
			letter-spacing: 1rpx;
		}

		.groups-list {
			flex-direction: row;
			flex-wrap: wrap;
			gap: 16rpx;
		}

		.group-card {
			padding: 16rpx 20rpx;
			flex: 1;
			min-width: 40%;
			max-width: 50%;
			box-sizing: border-box;
		}

		.group-header {
			margin-bottom: 10rpx;
		}

		.group-name {
			font-size: 18rpx;
			letter-spacing: 1rpx;
			width: 78rpx;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}

		.group-plan-index {
			font-size: 18rpx;
			letter-spacing: 1rpx;
		}

		.plan-name {
			font-size: 18rpx;
			letter-spacing: 1rpx;
			flex: 1;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
			text-align: center;
		}

		.laps-indicator {
			margin-bottom: 10rpx;
			gap: 10rpx;

			.lap-dot {
				width: 14rpx;
				height: 14rpx;
			}
		}

		.countdown-box {
			margin: 10rpx 0;

			.countdown-number {
				font-size: 72rpx;
				transform: scale(1.2, 1.3);
			}
		}

		.phase-hint {
			margin-bottom: 10rpx;
			padding: 6rpx 16rpx;

			.phase-text {
				font-size: 22rpx;
				letter-spacing: 1rpx;
			}
		}

		.plan-details {
			gap: 12rpx;
		}

		.detail-badge {
			font-size: 24rpx;
			padding: 6rpx 14rpx;
			letter-spacing: 1rpx;
		}

		.group-controls {
			padding-top: 10rpx;
			gap: 16rpx;
			justify-content: center;
		}

		.group-control-btn {
			font-size: 24rpx;
			padding: 10rpx 28rpx;
			letter-spacing: 2rpx;
			gap: 6rpx;
		}

		.plan-completed {
			padding: 20rpx;
			gap: 10rpx;

			.completed-label {
				font-size: 26rpx;
				letter-spacing: 2rpx;
			}
		}

		.bottom-controls {
			padding: 10rpx 32rpx;

			.controls-inner {
				max-width: 100%;
				gap: 24rpx;
				justify-content: center;
			}
		}

		.control-btn {
			padding: 7rpx 32rpx;
			flex: none;
			min-width: 140rpx;
			gap: 8rpx;
		}

		.btn-text {
			font-size: 18rpx;
			letter-spacing: 2rpx;
		}
	}
</style>