<template>
	<view class="add-hunyang-container">
		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 项目名称 -->
			<view class="form-card">
				<view class="form-title">项目信息</view>
				<view class="form-group">
					<text class="form-label">项目名称</text>
					<input class="form-input" v-model="projectName" placeholder="请输入项目名称"
						placeholder-class="input-placeholder" />
				</view>
			</view>

			<!-- 分组列表 -->
			<view class="form-card" v-for="(group, groupIndex) in groups" :key="group.id">
				<view class="group-header">
					<view class="group-title-wrapper">
						<text class="form-title">{{ group.name || `分组 ${groupIndex + 1}` }}</text>
						
						<view class="delete-group-btn" @click="deleteGroup(groupIndex)">
							<u-icon name="trash" size="16" color="#fff"></u-icon>
						</view>
					</view>
				</view>

				<!-- 分组名称输入 -->
				<view class="form-group" style="margin-bottom: 20rpx;">
					<text class="form-label">分组名称</text>
					<input class="form-input" v-model="group.name" placeholder="请输入分组名称"
						placeholder-class="input-placeholder" />
				</view>

				<!-- 计划项列表 -->
				<view v-for="(item, planIndex) in group.plans" :key="planIndex" class="plan-item">
					<view class="plan-item-header">
						<text class="plan-item-title">计划 {{ planIndex + 1 }}</text>
						<view class="delete-plan-btn" @click="deletePlanItem(groupIndex, planIndex)">
							<u-icon name="trash" size="16" color="#fff"></u-icon>
						</view>
					</view>

					<view class="plan-item-content">
						<!-- 计划名称 -->
						<view class="input-group">
							<text class="input-label">计划名称</text>
							<input class="plan-name-input" v-model="item.name" placeholder="请输入计划名称" />
						</view>

						<!-- 目标时间 - 秒输入 -->
						<view class="input-group">
							<text class="input-label">目标时间</text>
							<view class="time-selector">
								<view class="time-input-wrapper">
									<input class="time-input" v-model="item.targetSeconds" type="number"
										placeholder="" />
									<text class="time-unit">秒</text>
								</view>
							</view>
						</view>
						
						<!-- 单项时长显示 -->
						<!-- <view class="input-group" v-if="item.allTime > 0">
							<text class="input-label">单项时长</text>
							<view class="all-time-display">
								<text class="all-time-value">{{ item.allTime }} 秒</text>
							</view>
						</view> -->

						<!-- 休息时长 - 秒选择 -->
						<view class="input-group">
							<text class="input-label">休息时长</text>
							<view class="rest-selector">
								<input class="rest-input" v-model="item.restTime" type="number" placeholder="请输入休息时长" />
								<text class="time-unit">秒</text>
							</view>
						</view>

						<!-- 圈数 -->
						<view class="input-group">
							<text class="input-label">圈数</text>
							<view class="lap-selector">
								<input class="lap-input" v-model="item.lapCount" type="number" placeholder="请输入圈数" />
								<text class="time-unit">圈</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 添加计划按钮 -->
				<view class="add-plan-btn" @click="addPlanItem(groupIndex)">
					<u-icon name="plus-circle" size="20" color="#1890ff"></u-icon>
					<text class="add-plan-text">添加计划</text>
				</view>
			</view>

			<!-- 添加分组按钮 -->
			<view class="add-group-btn" @click="addGroup">
				<u-icon name="plus-circle" size="24" color="#fff"></u-icon>
				<text class="add-group-text">添加分组</text>
			</view>
		</view>
		<view class="" style="width: 100%; height: 80rpx;" >
			
		</view>
		<!-- 底部按钮区域 -->
		<view class="bottom-actions">
			<view class="action-buttons">
				<button class="cancel-btn" @click="handleCancel">取消</button>
				<button class="confirm-btn" @click="handleSave">保存</button>
			</view>
		</view>
	</view>
</template>

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

	// 计划项接口
	interface PlanItem {
		name: string
		targetSeconds: string
		restTime: string
		lapCount: string
		allTime?: number
	}

	// 分组接口
	interface Group {
		id: string
		name: string
		plans: PlanItem[]
		allTime?: number
	}

	// 项目名称
	const projectName = ref('')

	// 分组列表
	const groups = ref<Group[]>([])
	let planId = ref('')

	onLoad((data: any) => {
		planId.value = data.id
		if (planId.value) {
			getPlanInfo()
		} else {
			// 新建时默认添加一个分组
			addGroup()
		}
	})

	// 获取计划详情
	const getPlanInfo = () => {
		PlanService.GetPlanInfo(planId.value).then(res => {
			if (res.code == 0) {
				projectName.value = res.data.plan.name
				const projectData = JSON.parse(res.data.plan.project)
				// 兼容旧数据：如果 project 是数组，放入一个默认分组
				if (Array.isArray(projectData)) {
					groups.value = projectData.map((g: any, index: number) => ({
						id: generateId(),
						name: g.groupName || `分组 ${index + 1}`,
						allTime: g.allTime || 0,
						plans: (g.group || []).map((item: any) => ({
							name: String(item.name || ''),
							targetSeconds: String(item.target || ''),
							restTime: String(item.rest || ''),
							lapCount: String(item.circle || ''),
							allTime: item.allTime || 0
						}))
					}))
				} else if (projectData.groups && Array.isArray(projectData.groups)) {
					// 新数据格式
					groups.value = projectData.groups.map((g: any) => ({
						id: g.id || generateId(),
						name: g.name || '',
						allTime: g.allTime || 0,
						plans: (g.plans || []).map((item: any) => ({
							name: String(item.name || ''),
							targetSeconds: String(item.target || ''),
							restTime: String(item.rest || ''),
							lapCount: String(item.circle || ''),
							allTime: item.allTime || 0
						}))
					}))
				}
			} else {
				Service.Msg(res.msg)
			}
		})
	}

	// 计算计划总时长（秒）
	const totalDuration = computed(() => {
		let total = 0
		groups.value.forEach(group => {
			group.plans.forEach(item => {
				const targetSeconds = parseInt(item.targetSeconds) || 0
				const restTime = parseInt(item.restTime) || 0
				const lapCount = parseInt(item.lapCount) || 0
				// 计算公式：(目标时间 + 休息时间) * 圈数
				total += (targetSeconds + restTime) * lapCount
			})
		})
		return total
	})

	// 格式化总时长显示（时:分:秒）
	const formatTotalTime = (seconds: number): string => {
		if (seconds <= 0) return '00:00:00'
		const hours = Math.floor(seconds / 3600)
		const minutes = Math.floor((seconds % 3600) / 60)
		const secs = Math.floor(seconds % 60)
		return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
	}

	// 生成唯一ID
	const generateId = (): string => {
		return Date.now().toString() + Math.random().toString(36).substr(2, 9)
	}

	// 添加分组
	const addGroup = () => {
		const newGroup: Group = {
			id: generateId(),
			name: '',
			plans: []
		}
		groups.value.push(newGroup)
	}

	// 删除分组
	const deleteGroup = (groupIndex: number) => {
		uni.showModal({
			title: '确认删除',
			content: '确定要删除该分组吗？分组内的所有计划也将被删除。',
			success: (res) => {
				if (res.confirm) {
					groups.value.splice(groupIndex, 1)
					Service.Msg('删除成功')
				}
			}
		})
	}

	// 添加计划项
	const addPlanItem = (groupIndex: number) => {
		const newItem: PlanItem = {
			name: '',
			targetSeconds: '',
			restTime: '',
			lapCount: ''
		}
		groups.value[groupIndex].plans.push(newItem)
	}

	// 删除计划项
	const deletePlanItem = (groupIndex: number, planIndex: number) => {
		uni.showModal({
			title: '确认删除',
			content: '确定要删除该计划吗？',
			success: (res) => {
				if (res.confirm) {
					groups.value[groupIndex].plans.splice(planIndex, 1)
					Service.Msg('删除成功')
				}
			}
		})
	}

	// 验证表单
	const validateForm = (): boolean => {
		if (!projectName.value.trim()) {
			Service.Msg('请输入项目名称')
			return false
		}

		if (groups.value.length === 0) {
			Service.Msg('请至少添加一个分组')
			return false
		}

		for (let g = 0; g < groups.value.length; g++) {
			const group = groups.value[g]
			if (!group.name.trim()) {
				Service.Msg(`分组 ${g + 1} 请输入分组名称`)
				return false
			}

			if (group.plans.length === 0) {
				Service.Msg(`分组 "${group.name}" 请至少添加一个计划`)
				return false
			}

			for (let i = 0; i < group.plans.length; i++) {
				const item = group.plans[i]
				if (!item.name.trim()) {
					Service.Msg(`分组 "${group.name}" 计划 ${i + 1} 请输入计划名称`)
					return false
				}
				if (!item.targetSeconds) {
					Service.Msg(`分组 "${group.name}" 计划 ${i + 1} 请输入目标时间`)
					return false
				}
				const seconds = parseInt(item.targetSeconds) || 0
				if (seconds === 0) {
					Service.Msg(`分组 "${group.name}" 计划 ${i + 1} 目标时间不能为0`)
					return false
				}
				if (!item.restTime || parseInt(item.restTime) < 0) {
					Service.Msg(`分组 "${group.name}" 计划 ${i + 1} 请输入有效的休息时长`)
					return false
				}
				if (!item.lapCount || parseInt(item.lapCount) <= 0) {
					Service.Msg(`分组 "${group.name}" 计划 ${i + 1} 请输入有效的圈数`)
					return false
				}
			}
		}

		return true
	}

	// 计算单项时长
	const calculatePlanAllTime = (item: PlanItem): number => {
		const target = parseInt(item.targetSeconds) || 0
		const rest = parseInt(item.restTime) || 0
		const circle = parseInt(item.lapCount) || 0
		return (target + rest) * circle
	}

	// 计算分组总时长
	const calculateGroupAllTime = (group: Group): number => {
		return group.plans.reduce((sum, item) => sum + calculatePlanAllTime(item), 0)
	}

	// 保存
	const handleSave = () => {
		if (!validateForm()) {
			return
		}

		const projectData = groups.value.map(group => {
			const groupAllTime = calculateGroupAllTime(group)
			return {
				allTime: groupAllTime,
				groupName: group.name,
				group: group.plans.map(item => ({
					allTime: calculatePlanAllTime(item),
					name: item.name,
					target: parseInt(item.targetSeconds) || 0,
					rest: parseInt(item.restTime) || 0,
					circle: parseInt(item.lapCount) || 0
				}))
			}
		})
		
		
		
		const data = {
			planId: planId.value,
			name: projectName.value,
			planType: '混氧项目',
			departType: '',
			interval: '',
			groupInt: String(groups.value.length),
			subsectionDistance: '',
			subsectionInt: '',
			users: '',
			project: JSON.stringify(projectData),
			group: ''
		}

		
		PlanService.AddPlan(data).then(res => {
			if (res.code == 0) {
				Service.Msg(planId.value?'修改成功!':'添加成功!')
				
				if(planId.value){
					setTimeout(() => {
						Service.GoPageBack()
					}, 1000)
					
					uni.$emit('change')
				}else{
					setTimeout(() => {
						Service.GoPageDelse('/pages/userFunc/hunyang?id=' + res.data.planId)
					}, 1000)	
				}
				
				
				
				
			} else {
				Service.Msg(res.msg)
			}
		})
	}

	// 取消
	const handleCancel = () => {
		uni.showModal({
			title: '确认取消',
			content: '确定要取消吗？已输入的内容将不会保存。',
			success: (res) => {
				if (res.confirm) {
					Service.GoPageBack()
				}
			}
		})
	}
</script>

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

	.add-hunyang-container {
		min-height: 100vh;
		padding-bottom: 140rpx;
	}

	/* 表单区域 */
	.form-section {
		padding: 20rpx;
	}

	.form-card {
		background-color: #fff;
		border-radius: 24rpx;
		padding: 32rpx 28rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);

		.form-title {
			font-size: 32rpx;
			font-weight: 700;
			color: #333;
			margin-bottom: 28rpx;
			display: block;
		}
	}

	/* 分组头部 */
	.group-header {
		margin-bottom: 20rpx;

		.group-title-wrapper {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.form-title {
				margin-bottom: 0;
			}
		}
	}

	/* 删除分组按钮 */
	.delete-group-btn {
		width: 44rpx;
		height: 44rpx;
		background: linear-gradient(135deg, #ff4d4f 0%, #d9363e 100%);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 8rpx rgba(255, 77, 79, 0.3);
		transition: all 0.2s ease;

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

	/* 表单输入 */
	.form-group {
		margin-bottom: 0;

		.form-label {
			display: block;
			font-size: 28rpx;
			font-weight: 600;
			color: #333;
			margin-bottom: 14rpx;
		}

		.form-input {
			width: 100%;
			height: 88rpx;
			background-color: #f5f5f5;
			border-radius: 16rpx;
			padding: 0 24rpx;
			font-size: 28rpx;
			color: #333;
			transition: all 0.2s ease;

			&:focus {
				background-color: #fff;
				box-shadow: 0 0 0 4rpx rgba(24, 144, 255, 0.15);
			}
		}
	}

	/* 计划总时长 */
	.total-time-section {
		margin-top: 28rpx;
		padding-top: 24rpx;
		border-top: 2rpx solid #f0f0f0;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.total-time-label {
			font-size: 28rpx;
			font-weight: 600;
			color: #666;
		}

		.total-time-value {
			font-size: 36rpx;
			font-weight: bold;
			color: #1890ff;
			font-family: 'DIN Alternate', 'Helvetica Neue', monospace;
			letter-spacing: 2rpx;
			background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
			padding: 12rpx 24rpx;
			border-radius: 12rpx;
			border: 2rpx solid #91d5ff;
		}
	}

	/* 计划项 */
	.plan-item {
		background-color: #f9f9f9;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
		border: 2rpx solid #f0f0f0;

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

			.plan-item-title {
				font-size: 28rpx;
				font-weight: 600;
				color: #333;
			}

			.delete-plan-btn {
				width: 44rpx;
				height: 44rpx;
				background: linear-gradient(135deg, #ff4d4f 0%, #d9363e 100%);
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 2rpx 8rpx rgba(255, 77, 79, 0.3);
				transition: all 0.2s ease;

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

		.plan-item-content {
			display: flex;
			flex-direction: column;
			gap: 20rpx;
		}
	}

	/* 输入组 */
	.input-group {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.input-label {
			font-size: 26rpx;
			font-weight: 500;
			color: #666;
			min-width: 120rpx;
		}
	}

	/* 时间选择器 */
	.time-selector {
		display: flex;
		align-items: center;
		gap: 8rpx;
		flex: 1;

		.time-input-wrapper {
			display: flex;
			align-items: center;
			background-color: #fff;
			border-radius: 12rpx;
			padding: 0 16rpx;
			height: 72rpx;
			flex: 1;

			.time-input {
				flex: 1;
				font-size: 28rpx;
				color: #333;
				text-align: right;
			}

			.time-unit {
				font-size: 24rpx;
				color: #999;
				margin-left: 8rpx;
			}
		}

		.time-separator {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			padding: 0 4rpx;
		}
	}

	/* 休息选择器 */
	.rest-selector,
	.lap-selector {
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 0 16rpx;
		height: 72rpx;
		flex: 1;

		.rest-input,
		.lap-input {
			flex: 1;
			font-size: 28rpx;
			color: #333;
			text-align: right;
		}

		.time-unit {
			font-size: 24rpx;
			color: #999;
			margin-left: 12rpx;
		}
	}

	/* 计划名称输入 */
	.plan-name-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 0 16rpx;
		height: 72rpx;
	}

	/* 分组总时长 */
	.group-time-info {
		margin-right: 16rpx;
		padding: 6rpx 12rpx;
		background: #e6f7ff;
		border-radius: 8rpx;
	}

	.group-time-text {
		font-size: 24rpx;
		color: #1890ff;
		font-weight: 500;
	}

	/* 单项时长显示 */
	.all-time-display {
		padding: 12rpx 16rpx;
		background: #f6ffed;
		border-radius: 8rpx;
		border: 1rpx solid #b7eb8f;
	}

	.all-time-value {
		font-size: 28rpx;
		color: #52c41a;
		font-weight: 600;
	}

	/* 添加计划按钮 */
	.add-plan-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 12rpx;
		padding: 24rpx 32rpx;
		margin-top: 20rpx;
		background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
		border-radius: 16rpx;
		border: 2rpx dashed #91d5ff;
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.98);
			background: linear-gradient(135deg, #e6f7ff 0%, #d6f4ff 100%);
		}

		.add-plan-text {
			font-size: 28rpx;
			color: #1890ff;
			font-weight: 500;
		}
	}

	/* 添加分组按钮 */
	.add-group-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 12rpx;
		padding: 28rpx 32rpx;
		margin-top: 20rpx;
		background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
		border-radius: 16rpx;
		box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.3);
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.98);
			box-shadow: 0 2rpx 8rpx rgba(82, 196, 26, 0.2);
		}

		.add-group-text {
			font-size: 30rpx;
			color: #fff;
			font-weight: 600;
		}
	}

	/* 底部操作按钮 */
	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 20rpx 30rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		border-top: 1rpx solid #f0f0f0;
		box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.08);
		z-index: 99;

		.action-buttons {
			display: flex;
			gap: 16rpx;
		}
	}

	.cancel-btn,
	.confirm-btn {
		flex: 1;
		height: 88rpx;
		border-radius: 16rpx;
		border: none;
		font-size: 30rpx;
		font-weight: 600;
		transition: all 0.25s ease;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.cancel-btn {
		background-color: #f5f5f5;
		color: #666;

		&:active {
			background-color: #e8e8e8;
			transform: scale(0.96);
		}
	}

	.confirm-btn {
		background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
		color: #fff;
		box-shadow: 0 6rpx 16rpx rgba(24, 144, 255, 0.35);

		&:active {
			transform: scale(0.96);
			box-shadow: 0 3rpx 8rpx rgba(24, 144, 255, 0.25);
		}
	}
</style>