<template>
	<fui-modal :show="visible" width="700" @cancel="closePopup" :buttons="[{text: '关闭', type: 'default'}]" :showClose="true" @close="closePopup" @click="handleModalClick">
		<!-- 自定义关闭按钮 -->
		<template #header>
			<view class="custom-header">
				<text class="modal-title">课程安排详情</text>
				<view class="close-btn" @click="closePopup">
					<text class="close-icon">✕</text>
				</view>
			</view>
		</template>
		<view class="schedule-detail" v-if="scheduleInfo">
			<!-- 课程基本信息 -->
			<view class="section basic-info">
				<view class="section-title">基本信息</view>
				<view class="info-item">
					<text class="item-label">课程名称：</text>
					<text class="item-value">{{ scheduleInfo.course_name }}</text>
				</view>
				<view class="info-item">
					<text class="item-label">上课时间：</text>
					<text class="item-value">{{ scheduleInfo.course_date }} {{ scheduleInfo.time_slot }}</text>
				</view>
				<view class="info-item">
					<text class="item-label">上课地点：</text>
					<text class="item-value">{{ scheduleInfo.campus_name ? scheduleInfo.campus_name + ' ' : '' }}{{ scheduleInfo.venue_name }}</text>
				</view>
				<view class="info-item">
					<text class="item-label">授课教练：</text>
					<text class="item-value">{{ scheduleInfo.coach_name }}</text>
				</view>
				<view class="info-item">
					<text class="item-label">课程状态：</text>
					<text :class="['item-value',statusClass]">{{ scheduleInfo.status_text || statusText }}</text>
				</view>
				<view class="info-item">
					<text class="item-label">班级：</text>
					<text
						class="item-value">{{ scheduleInfo.class_info ? scheduleInfo.class_info.class_name : '无班级' }}</text>
				</view>
				<view class="info-item" v-if="scheduleInfo.course_duration">
					<text class="item-label">课时时长：</text>
					<text class="item-value">{{ scheduleInfo.course_duration }}分钟</text>
				</view>
				<view class="info-item" v-if="scheduleInfo.course_info">
					<text class="item-label">课程有效期：</text>
					<text class="item-value">{{ scheduleInfo.course_info.start_date }} 至 {{ scheduleInfo.course_info.end_date }}</text>
				</view>
			</view>


			<!-- 正式学员 -->
			<view class="section students-info">
				<view class="section-header">
					<view class="section-title">正式学员 ({{ formalStudents.length }}人)</view>
					<view class="header-actions">
						<view class="action-btn batch-checkin-btn" @click="batchCheckIn">
							<fui-icon name="check" :size="14" color="#fff"></fui-icon>
							<text class="btn-text">批量签到</text>
						</view>
						<view class="action-btn arrange-student-btn" @click="handleArrangeStudent">
							<fui-icon name="plus" :size="14" color="#fff"></fui-icon>
							<text class="btn-text">安排学员</text>
						</view>
					</view>
				</view>
				<view class="cards-grid" v-if="formalStudents && formalStudents.length > 0">
					<view class="student-card filled" v-for="(student, index) in formalStudents" :key="index"
						@click="handleStudentClick(student, index)">
						<!-- 续费提醒徽章 -->
						<view v-if="student.needsRenewal && !student.isTrialStudent" class="renewal-badge">待续费</view>

						<!-- 体验课学员标识 -->
						<view v-if="student.isTrialStudent" class="trial-badge">体验课</view>

						<view class="avatar">{{ student.name.charAt(0) }}</view>
						<view class="student-info">
							<view class="student-name">{{ student.name }}</view>
							<view class="student-age">年龄：{{ student.age }}岁</view>
							<view class="attendance-status">
								<text class="status-label">签到状态：</text>
								<text :class="['status-text', getStatusClass(student.status)]">{{ getStatusText(student.status) }}</text>
							</view>
							<view class="course-status">课程状态：{{ student.courseStatus }}</view>
							<view class="course-arrangement">课程安排：{{ student.courseType === 'fixed' ? '固定课' : '临时课' }}</view>

							<!-- 体验课学员显示 -->
							<view v-if="student.isTrialStudent" class="trial-info">
								<view class="trial-hours">体验课时：{{ student.trialClassCount }}节</view>
							</view>

							<!-- 付费学员显示 -->
							<view v-else class="paid-student-info">
								<view class="remaining-hours">剩余课时：{{ student.remainingHours }}节</view>
								<view class="expiry-date">到期时间：{{ student.expiryDate || '未设置' }}</view>

								<!-- 课时进度条 -->
								<view class="progress-container">
									<view class="progress-label">
										<text>课时进度：{{ student.course_progress.used }}/{{ student.course_progress.total }}</text>
										<text class="progress-percentage">{{ student.course_progress.percentage }}%</text>
									</view>
									<view class="progress-bar">
										<view
											class="progress-fill"
											:style="{ width: student.course_progress.percentage + '%' }"
										></view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="empty-list" v-else>
					<text>暂无正式学员参与此课程</text>
				</view>
			</view>

			<!-- 等待位学员 -->
			<view class="section waiting-info" v-if="waitingStudents && waitingStudents.length > 0">
				<view class="section-header">
					<view class="section-title">等待位 ({{ waitingStudents.length }}人)</view>
					<view class="waiting-tip">
						<text class="tip-text">点击卡片转为正式课学员</text>
					</view>
				</view>
				<view class="cards-grid">
					<view class="student-card filled waiting-filled" v-for="(student, index) in waitingStudents" :key="index"
						@click="handleStudentClick(student, index)">
						<!-- 转换提示图标 -->
						<view class="convert-icon">⚡</view>

						<!-- 续费提醒徽章 -->
						<view v-if="student.needsRenewal && !student.isTrialStudent" class="renewal-badge">待续费</view>

						<!-- 体验课学员标识 -->
						<view v-if="student.isTrialStudent" class="trial-badge">体验课</view>

						<view class="avatar waiting-avatar">{{ student.name.charAt(0) }}</view>
						<view class="student-info">
							<view class="student-name">{{ student.name }}</view>
							<view class="student-age">年龄：{{ student.age }}岁</view>
							<view class="attendance-status">
								<text class="status-label">签到状态：</text>
								<text :class="['status-text', getStatusClass(student.status)]">{{ getStatusText(student.status) }}</text>
							</view>
							<view class="course-status">课程状态：{{ student.courseStatus }}</view>
							<view class="course-arrangement">课程安排：等待位</view>

							<!-- 体验课学员显示 -->
							<view v-if="student.isTrialStudent" class="trial-info">
								<view class="trial-hours">体验课时：{{ student.trialClassCount }}节</view>
							</view>

							<!-- 付费学员显示 -->
							<view v-else class="paid-student-info">
								<view class="remaining-hours">剩余课时：{{ student.remainingHours }}节</view>
								<view class="expiry-date">到期时间：{{ student.expiryDate || '未设置' }}</view>

								<!-- 课时进度条 -->
								<view class="progress-container">
									<view class="progress-label">
										<text>课时进度：{{ student.course_progress.used }}/{{ student.course_progress.total }}</text>
										<text class="progress-percentage">{{ student.course_progress.percentage }}%</text>
									</view>
									<view class="progress-bar">
										<view
											class="progress-fill"
											:style="{ width: student.course_progress.percentage + '%' }"
										></view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 操作按钮 -->
			<view class="action-buttons">
				<view class="action-button edit-btn" @click="handleEditCourse">
					<text class="btn-text">编辑课程</text>
				</view>
				<view class="action-button add-btn" @click="handleAddNewCourse">
					<text class="btn-text">新增课程</text>
				</view>
			</view>

		</view>

		<view class="loading" v-if="loading && !scheduleInfo">
			<fui-loading></fui-loading>
			<text class="loading-text">加载中...</text>
		</view>

		<view class="error-message" v-if="error && !scheduleInfo">
			<text>{{ errorMessage }}</text>
			<view class="retry-btn" @click="fetchScheduleDetail">
				<text>重试</text>
			</view>
		</view>

		<!-- 学员点名底部弹窗 -->
		<fui-modal :show="showAttendanceModal" title="学员点名" @cancel="closeAttendanceModal" :buttons="[]">
			<view class="attendance-modal" v-if="selectedStudent">
				<view class="student-info">
					<view class="student-avatar-large">
						<image :src="selectedStudent.avatar || $util.img('/static/icon-img/avatar.png')" mode="aspectFill"></image>
					</view>
					<view class="student-name-large">{{ selectedStudent.name }}</view>
					<view class="current-status">当前状态：{{ selectedStudent.status_text }}</view>
				</view>

				<view class="attendance-options">
					<view class="option-btn sign-in" @click="handleAttendanceAction('sign_in')">
						<text>签到</text>
					</view>
					<view v-if="!selectedStudent.isTrialStudent" class="option-btn leave" @click="handleAttendanceAction('leave')">
						<text>请假</text>
					</view>
					<view class="option-btn cancel" @click="closeAttendanceModal">
						<text>取消</text>
					</view>
				</view>
			</view>
		</fui-modal>

		<!-- 升级确认弹窗 -->
		<fui-modal :show="showUpgradeConfirm" title="升级确认" @cancel="cancelUpgrade" :buttons="[]" :zIndex="10000">
			<view class="upgrade-confirm-modal" v-if="upgradeStudent">
				<view class="confirm-content">
					<view class="upgrade-icon">⚡</view>
					<view class="confirm-text">
						是否将等待位学员 <text class="student-name-highlight">{{ upgradeStudent.name }}</text> 升级为正式学员？
					</view>
					<view class="confirm-tip">
						升级后将占用一个正式位
					</view>
				</view>

				<view class="confirm-buttons">
					<view class="confirm-btn cancel-btn" @click="cancelUpgrade">
						<text>取消</text>
					</view>
					<view class="confirm-btn upgrade-btn" @click="confirmUpgrade">
						<text>确定升级</text>
					</view>
				</view>
			</view>
		</fui-modal>

		<!-- 删除课程安排确认弹窗 -->
		<fui-modal :show="showDeleteSchedulesModal" title="删除确认" @cancel="closeDeleteSchedulesModal" :buttons="[]" :zIndex="10001">
			<view class="delete-confirm-modal" v-if="studentToDelete">
				<view class="confirm-content">
					<view class="error-icon">⚠️</view>
					<view class="error-message">
						{{ deleteErrorMessage }}
					</view>
					<view class="confirm-text">
						是否删除学员 <text class="student-name-highlight">{{ studentToDelete.name }}</text> 的所有未来课程安排？
					</view>
					<view class="confirm-tip">
						删除后，该学员的所有未来课程安排将被清除，但历史记录会保留
					</view>
				</view>

				<view class="confirm-buttons">
					<view class="confirm-btn cancel-btn" @click="closeDeleteSchedulesModal">
						<text>取消</text>
					</view>
					<view class="confirm-btn delete-btn" @click="confirmDeleteSchedules">
						<text>确认删除</text>
					</view>
				</view>
			</view>
		</fui-modal>
	</fui-modal>
</template>

<script>
	import api from '@/api/apiRoute.js';

	export default {
		name: 'ScheduleDetail',
		props: {
			visible: {
				type: Boolean,
				default: false
			},
			scheduleId: {
				type: [String, Number],
				default: null
			}
		},
		computed: {
			// 分离正式学员和等待位学员
			formalStudents() {
				if (!this.scheduleInfo || !this.scheduleInfo.students) return [];
				return this.scheduleInfo.students.filter(student => student.schedule_type === 1 || student.schedule_type === null);
			},
			waitingStudents() {
				if (!this.scheduleInfo || !this.scheduleInfo.students) return [];
				return this.scheduleInfo.students.filter(student => student.schedule_type === 2);
			},
			statusClass() {
				const statusMap = {
					'pending': 'status-pending',
					'upcoming': 'status-upcoming',
					'ongoing': 'status-ongoing',
					'completed': 'status-completed'
				};
				return statusMap[this.scheduleInfo?.status] || '';
			},
			statusText() {
				const statusTextMap = {
					'pending': '待开始',
					'upcoming': '即将开始',
					'ongoing': '进行中',
					'completed': '已结束'
				};
				return statusTextMap[this.scheduleInfo?.status] || '待开始';
			},
			studentList() {
				const statusMap = {
					0: 'status-absent',
					1: 'status-present',
					2: 'status-leave'
				};

				return this.studentListRaw ? this.studentListRaw.map(student => ({
					...student,
					statusClass: statusMap[student.status] || 'status-absent',
					status_text: this.getStatusText(student.status)
				})) : [];
			},
			// 计算课程进度百分比
			progressPercentage() {
				if (!this.scheduleInfo || !this.scheduleInfo.course_info) return 0;

				const totalHours = this.scheduleInfo.course_info.total_hours || 0;
				const usedHours = this.scheduleInfo.course_info.use_total_hours || 0;

				if (totalHours <= 0) return 0;

				const percentage = Math.round((usedHours / totalHours) * 100);
				return Math.min(percentage, 100); // 确保不超过100%
			}
		},
		data() {
			return {
				loading: false,
				error: false,
				errorMessage: '加载失败，请重试',
				scheduleInfo: null,
				showAttendanceModal: false,
				selectedStudent: null,
				selectedStudentIndex: -1,
				showUpgradeConfirm: false,
				upgradeStudent: null,
				upgradeStudentIndex: -1,
				showDeleteSchedulesModal: false,
				deleteErrorMessage: '',
				studentToDelete: null
			}
		},
		watch: {
			visible(newVal) {
				if (newVal && this.scheduleId) {
					this.fetchScheduleDetail();
				}
			},
			scheduleId(newVal, oldVal) {
				// 只有在弹窗可见且scheduleId真正发生变化时才重新获取数据
				if (newVal && this.visible && newVal !== oldVal) {
					this.fetchScheduleDetail();
				}
			}
		},
		methods: {
			// 处理弹窗按钮点击
			handleModalClick(e) {
				// 如果点击的是关闭按钮，关闭弹窗
				if (e.index === 0) {
					this.closePopup();
				}
			},

			// 获取课程安排详情（使用统一API - 对接admin端）
			async fetchScheduleDetail() {
				if (!this.scheduleId) {
					this.error = true;
					this.errorMessage = '课程ID不能为空';
					return;
				}

				this.loading = true;
				this.error = false;
				this.scheduleInfo = null;

				try {
					// 调用新的统一API获取课程安排详情，与admin端保持一致
					const res = await api.getCourseArrangementDetail({
						schedule_id: this.scheduleId
					});

					if (res.code === 1) {
						// 处理课程安排基本信息
						const data = res.data;

						// 使用新的统一API数据结构，与admin端保持一致
						if (data.schedule_info) {
							// 处理新的统一数据结构（包含schedule_info、formal_students、waiting_students）
							const allStudents = [...(data.formal_students || []), ...(data.waiting_students || [])];

							this.scheduleInfo = {
								// 基本课程信息从schedule_info获取
								id: data.schedule_info.id,
								course_name: data.schedule_info.course_name || '未命名课程',
								course_date: data.schedule_info.course_date,
								time_slot: data.schedule_info.time_slot,
								venue_name: data.schedule_info.venue_name || '未分配',
								campus_name: data.schedule_info.campus_name || '',
								// 教练信息
								coach_name: data.schedule_info.coach_name || '未分配',
								coach_avatar: data.schedule_info.coach_avatar || '',
								// 课程状态
								status: data.schedule_info.status,
								status_text: data.schedule_info.status_text || this.getStatusTextFromCode(data.schedule_info.status),
								// 班级信息
								class_info: data.schedule_info.class_info || null,
								// 时间信息
								time_info: data.schedule_info.time_info || null,
								// 课程时长
								course_duration: data.schedule_info.time_info?.duration || data.schedule_info.course_duration || 60,
								// 合并正式学员和等待位学员数据
								students: allStudents.map(student => ({
									...student,
									status_text: this.getStatusText(student.status || 0),
									// 确保包含课程进度数据
									course_progress: student.course_progress || {
										total: student.totalHours || 0,
										used: student.usedHours || 0,
										remaining: student.remainingHours || 0,
										percentage: student.totalHours > 0 ? Math.round((student.usedHours / student.totalHours) * 100) : 0
									},
									// 确保包含续费和体验课标识
									needsRenewal: student.needsRenewal || false,
									isTrialStudent: student.isTrialStudent || student.person_type !== 'student',
									// 确保包含课程状态和类型
									courseStatus: student.courseStatus || (student.person_type === 'student' ? '正式课' : '体验课'),
									courseType: student.schedule_type === 2 ? 'waiting' : 'formal',
									// 确保包含年龄信息
									age: student.age || 0,
									// 确保包含体验课时信息
									trialClassCount: student.trialClassCount || 0,
									// 确保包含剩余课时和到期时间
									remainingHours: student.remainingHours || student.course_progress?.remaining || 0,
									expiryDate: student.expiryDate || ''
								})),
								// 其他信息
								available_capacity: data.available_capacity || 0,
								enrolled_count: allStudents.length,
								remaining_capacity: data.remaining_capacity || 0
							};
						} else {
							// 兼容旧的数据结构
							this.scheduleInfo = {
								// 基本课程信息
								id: data.id,
								course_name: data.course_name || '未命名课程',
								course_date: data.course_date,
								time_slot: data.time_slot,
								venue_name: data.venue_name || '未分配',
								campus_name: data.campus_name || '',
								// 教练信息
								coach_name: data.coach_name || '未分配',
								coach_avatar: data.coach_avatar || '',
								// 课程状态
								status: data.status,
								status_text: data.status_text || this.getStatusTextFromCode(data.status),
								// 班级信息
								class_info: data.class_info || null,
								// 时间信息
								time_info: data.time_info || null,
								// 课程时长
								course_duration: data.time_info?.duration || data.course_duration || 60,
								// 学员数据
								students: (data.students || []).map(student => ({
									...student,
									status_text: this.getStatusText(student.status || 0),
									// 确保包含课程进度数据
									course_progress: student.course_progress || {
										total: student.totalHours || 0,
										used: student.usedHours || 0,
										remaining: student.remainingHours || 0,
										percentage: student.totalHours > 0 ? Math.round((student.usedHours / student.totalHours) * 100) : 0
									},
									// 确保包含续费和体验课标识
									needsRenewal: student.needsRenewal || false,
									isTrialStudent: student.isTrialStudent || false,
									// 确保包含课程状态和类型
									courseStatus: student.courseStatus || (student.person_type === 'student' ? '正式课' : '体验课'),
									courseType: student.schedule_type === 2 ? 'waiting' : 'formal',
									// 确保包含年龄信息
									age: student.age || 0,
									// 确保包含体验课时信息
									trialClassCount: student.trialClassCount || 0,
									// 确保包含剩余课时和到期时间
									remainingHours: student.remainingHours || 0,
									expiryDate: student.expiryDate || ''
								})),
								// 其他信息
								available_capacity: data.available_capacity || 0,
								enrolled_count: data.enrolled_count || 0,
								remaining_capacity: data.remaining_capacity || 0
							};
						}

						console.log('课程安排详情加载成功:', this.scheduleInfo);
					} else {
						uni.showToast({
							title: res.msg || '获取课程安排详情失败',
							icon: 'none'
						});
						this.error = true;
						this.errorMessage = res.msg || '获取课程安排详情失败';
					}
				} catch (error) {
					console.error('获取课程安排详情失败:', error);
					this.error = true;
					this.errorMessage = error.message || '获取课程安排详情失败，请重试';
				} finally {
					this.loading = false;
				}
			},

			// 关闭弹窗
			closePopup() {
				this.$emit('update:visible', false);
			},

			// 编辑课程操作
			handleEditCourse() {
				this.$emit('edit-course', {
					scheduleId: this.scheduleId,
					scheduleInfo: this.scheduleInfo
				});
				this.closePopup();
			},

			// 新增课程操作
			handleAddNewCourse() {
				this.$emit('add-new-course', {
					scheduleId: this.scheduleId,
					scheduleInfo: this.scheduleInfo,
					date: this.scheduleInfo?.course_date,
					timeSlot: this.scheduleInfo?.time_slot
				});
				this.closePopup();
			},

			// 学员点击处理
			handleStudentClick(student, index) {
        console.log('点击了学员:', student)
				// 检查学员签到状态，只有状态为0（待上课）才能进行签到操作
				if (student.status !== 0) {
					uni.showToast({
						title: `该学员已${this.getStatusText(student.status)}，无法重复操作`,
						icon: 'none',
						duration: 2000
					});
					return;
				}

				// 检查是否是等待位学员
				if (student.schedule_type === 2) {
					// 等待位学员 - 询问是否转为正式课
					this.handleWaitingStudentClick(student, index);
				} else {
					// 正式学员 - 进行签到/请假操作
					this.selectedStudent = student;
					this.selectedStudentIndex = index;
					this.showAttendanceModal = true;
				}
			},

			// 处理等待位学员点击
			handleWaitingStudentClick(student, index) {
				this.upgradeStudent = student;
				this.upgradeStudentIndex = index;
				this.showUpgradeConfirm = true;
			},

			// 确认升级等待位学员
			confirmUpgrade() {
				this.showUpgradeConfirm = false;
				if (this.upgradeStudent && this.upgradeStudentIndex >= 0) {
					this.convertWaitingToFormal(this.upgradeStudent, this.upgradeStudentIndex);
				}
			},

			// 取消升级等待位学员
			cancelUpgrade() {
				this.showUpgradeConfirm = false;
				this.upgradeStudent = null;
				this.upgradeStudentIndex = -1;
			},

			// 将等待位学员转为正式课学员（处理客户资源升级为正式学员）
			async convertWaitingToFormal(student, index) {
				try {
					uni.showLoading({
						title: '升级中...'
					});

					console.log('升级学员信息:', student);

					// 构建升级数据 - 使用我刚实现的后端接口
					const upgradeData = {
						schedule_id: this.scheduleId,
						person_id: student.person_id || null, // person_id可能为空
						person_type: student.person_type || 'customer_resource',
            from_schedule_type: 2, // 客户资源类型
            to_schedule_type: 1,   // 正式学员类型
						resources_id: student.resources_id || student.resource_id || student.id
					};

					// 如果是正式学员，添加student_id
					if (student.person_type === 'student') {
						upgradeData.student_id = student.student_id || student.id;
					}

					// 调用升级接口
					const response = await api.upgradeStudentSchedule(upgradeData);

					if (response.code === 1) {
						// 重新获取课程详情以更新学员列表
						await this.fetchScheduleDetail();

						uni.showToast({
							title: `学员 ${student.name} 升级成功！已转为正式学员`,
							icon: 'success',
							duration: 3000
						});
					} else {
						uni.showToast({
							title: response.msg || '升级失败',
							icon: 'none',
							duration: 3000
						});
					}
				} catch (error) {
					console.error('升级学员失败:', error);

					let errorMessage = '升级失败，请重试';
					if (error.message) {
						if (error.message.includes('timeout')) {
							errorMessage = '升级超时，请重试';
						} else if (error.message.includes('Network')) {
							errorMessage = '网络异常，请检查网络连接';
						}
					}

					uni.showToast({
						title: errorMessage,
						icon: 'none',
						duration: 3000
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 关闭点名弹窗
			closeAttendanceModal() {
				this.showAttendanceModal = false;
				this.selectedStudent = null;
				this.selectedStudentIndex = -1;
			},

			// 显示删除课程安排确认弹窗
			showDeleteSchedulesConfirm(errorMessage) {
				this.deleteErrorMessage = errorMessage;
				this.studentToDelete = this.selectedStudent;
				this.showDeleteSchedulesModal = true;
			},

			// 关闭删除确认弹窗
			closeDeleteSchedulesModal() {
				this.showDeleteSchedulesModal = false;
				this.deleteErrorMessage = '';
				this.studentToDelete = null;
			},

			// 确认删除学员所有未来课程安排
			async confirmDeleteSchedules() {
				if (!this.studentToDelete) return;

				try {
					uni.showLoading({
						title: '删除中...'
					});

					// 调用删除API
					const deleteData = {
						student_id: this.studentToDelete.id,
						reason: '体验课次数用完，清理未来课程安排'
					};

					// 如果有resources_id，也传过去
					if (this.studentToDelete.resources_id) {
						deleteData.resources_id = this.studentToDelete.resources_id;
					}

					const response = await api.deleteStudentFutureSchedules(deleteData);

					if (response.code === 1) {
						// 删除成功
						const deletedCount = response.data?.deleted_count || 0;

						uni.showToast({
							title: `成功删除${deletedCount}个未来课程安排`,
							icon: 'success',
							duration: 3000
						});

						// 刷新课程详情
						this.fetchScheduleDetail();
					} else {
						uni.showToast({
							title: response.msg || '删除失败',
							icon: 'none',
							duration: 3000
						});
					}
				} catch (error) {
					console.error('删除课程安排失败:', error);
					uni.showToast({
						title: '删除失败，请重试',
						icon: 'none',
						duration: 3000
					});
				} finally {
					uni.hideLoading();
					this.closeDeleteSchedulesModal();
					this.closeAttendanceModal();
				}
			},

			// 处理点名操作（使用统一API - 对接admin端）
			async handleAttendanceAction(action) {
				if (!this.selectedStudent) return;

				const actionMap = {
					'sign_in': { status: 1, text: '已签到' },
					'leave': { status: 2, text: '请假' }
				};

				if (actionMap[action]) {
					try {
						uni.showLoading({
							title: '处理中...'
						});

						// 使用新的统一状态更新API，与admin端保持一致
						const updateData = {
							schedule_id: this.scheduleId,
							person_id: this.selectedStudent.person_id || this.selectedStudent.id,
							person_type: this.selectedStudent.person_type || 'student',
							status: actionMap[action].status,
							reason: `移动端${actionMap[action].text}操作`
						};

						// 根据学员类型添加对应的ID
						if (this.selectedStudent.person_type === 'student') {
							updateData.student_id = this.selectedStudent.student_id || this.selectedStudent.id;
						} else {
							updateData.resources_id = this.selectedStudent.resources_id || this.selectedStudent.resource_id || this.selectedStudent.id;
						}

						// 如果是请假，可以添加请假备注
						if (action === 'leave') {
							updateData.reason = '移动端请假操作';
						}

						console.log('更新学员状态数据:', updateData);

						// 调用新的统一状态更新接口
						const response = await api.updateStudentStatusInArrangement(updateData);

						if (response.code === 1) {
							// API调用成功，更新前端状态
							this.selectedStudent.status = actionMap[action].status;
							this.selectedStudent.status_text = actionMap[action].text;
							this.selectedStudent.statusClass = this.getStudentStatusClass(actionMap[action].status);

							// 更新scheduleInfo中的学员信息
							if (this.scheduleInfo && this.scheduleInfo.students && this.selectedStudentIndex >= 0) {
								this.$set(this.scheduleInfo.students, this.selectedStudentIndex, this.selectedStudent);
							}

							// 发射事件给父组件
							this.$emit('student-attendance', {
								scheduleId: this.scheduleId,
								studentId: this.selectedStudent.id,
								action: action,
								status: actionMap[action].status,
								studentName: this.selectedStudent.name
							});

							uni.showToast({
								title: `${this.selectedStudent.name} ${actionMap[action].text}成功`,
								icon: 'success',
								duration: 3000
							});
						} else {
							// API调用失败
							// 检查是否是体验课次数用完的错误
							if (response.msg && response.msg.includes('体验课次数已用完') && action === 'checkin') {
								// 弹窗询问是否删除该学员的所有课程安排
								this.showDeleteSchedulesConfirm(response.msg);
							} else {
								uni.showToast({
									title: response.msg || `${actionMap[action].text}失败`,
									icon: 'none',
									duration: 3000
								});
							}
						}
					} catch (error) {
						console.error(`${action} API调用失败:`, error);

						let errorMessage = `${actionMap[action].text}失败，请重试`;
						if (error.message) {
							if (error.message.includes('timeout')) {
								errorMessage = `${actionMap[action].text}超时，请重试`;
							} else if (error.message.includes('Network')) {
								errorMessage = '网络异常，请检查网络连接';
							}
						}

						uni.showToast({
							title: errorMessage,
							icon: 'none',
							duration: 3000
						});
					} finally {
						uni.hideLoading();
					}
				}

				this.closeAttendanceModal();
			},

			// 获取学员状态样式类
			getStudentStatusClass(status) {
				const statusMap = {
					0: 'status-pending', // 待上课
					1: 'status-completed', // 已上课
					2: 'status-leave' // 请假
				};
				return statusMap[status] || '';
			},
			// 获取状态文本
			getStatusText(status) {
				const statusTextMap = {
					0: '待上课',
					1: '已上课',
					2: '请假'
				};
				return statusTextMap[status] || '未知状态';
			},

			// 获取签到状态样式类
			getStatusClass(status) {
				const statusClassMap = {
					0: 'status-pending', // 待上课
					1: 'status-completed', // 已上课
					2: 'status-leave' // 请假
				};
				return statusClassMap[status] || '';
			},

			// 根据课程状态代码获取状态文本
			getStatusTextFromCode(statusCode) {
				const statusTextMap = {
					'pending': '待开始',
					'upcoming': '即将开始',
					'ongoing': '进行中',
					'completed': '已结束'
				};
				return statusTextMap[statusCode] || '待开始';
			},

			// 批量签到
			batchCheckIn() {
				uni.navigateTo({
					url: `/pages-coach/coach/schedule/sign_in?id=${this.scheduleId}`,
					success: () => {
						console.log('跳转到批量签到页面成功');
						// 关闭当前弹窗
						this.closePopup();
					},
					fail: (error) => {
						console.error('跳转到批量签到页面失败:', error);
						uni.showToast({
							title: '跳转失败，请重试',
							icon: 'none'
						});
					}
				});
			},

			// 处理安排学员按钮点击（支持统一学员管理功能）
			handleArrangeStudent() {
				try {
					// 跳转到课程安排详情页面进行学员管理
					const url = `/pages-market/clue/class_arrangement_detail?schedule_id=${this.scheduleId}`;
					console.log('跳转到学员管理页面:', url);

					uni.navigateTo({
						url: url,
						success: () => {
							console.log('成功跳转到学员管理页面');
							// 关闭当前弹窗
							this.closePopup();
						},
						fail: (error) => {
							console.error('跳转到学员管理页面失败:', error);
							uni.showToast({
								title: '跳转失败，请重试',
								icon: 'none',
								duration: 3000
							});
						}
					});
				} catch (error) {
					console.error('处理安排学员按钮失败:', error);
					uni.showToast({
						title: '操作失败，请重试',
						icon: 'none',
						duration: 3000
					});
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	/* 自定义头部样式 */
	.custom-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		background: #2a2a2a;
		border-bottom: 1px solid #3a3a3a;
	}

	.modal-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #29d3b4;
	}

	.close-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.1);
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.close-btn:hover {
		background: rgba(255, 255, 255, 0.2);
	}

	.close-btn:active {
		background: rgba(255, 255, 255, 0.3);
	}

	.close-icon {
		font-size: 24rpx;
		color: #999;
		font-weight: bold;
		line-height: 1;
	}

	.schedule-detail {
		padding: 20rpx;
		max-height: 80vh;
		overflow-y: auto;
		position: relative;
	}

	.section {
		margin-bottom: 30rpx;
		background-color: #2a2a2a;
		border-radius: 12rpx;
		padding: 20rpx;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		border-bottom: 1px solid #3a3a3a;
		padding-bottom: 10rpx;
	}

	.section-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #29d3b4;
		flex: 1;
	}

	.header-actions {
		display: flex;
		gap: 12rpx;
	}

	.action-btn {
		display: flex;
		align-items: center;
		padding: 8rpx 16rpx;
		border-radius: 6rpx;
		cursor: pointer;
		transition: background-color 0.3s;

		&:hover {
			opacity: 0.8;
		}

		.btn-text {
			margin-left: 6rpx;
			font-size: 24rpx;
			color: #fff;
		}
	}

	.batch-checkin-btn {
		background-color: #007bff;

		&:hover {
			background-color: #0056b3;
		}
	}

	.arrange-student-btn {
		background-color: #29d3b4;

		&:hover {
			background-color: #22a68b;
		}
	}

	.waiting-tip {
		display: flex;
		align-items: center;
		padding: 8rpx 16rpx;
		background: rgba(139, 92, 246, 0.2);
		border-radius: 6rpx;
		border: 1px solid rgba(139, 92, 246, 0.3);
	}

	.tip-text {
		font-size: 22rpx;
		color: #8b5cf6;
		font-weight: 500;
	}

	.info-item {
		display: flex;
		margin-bottom: 16rpx;
		font-size: 28rpx;
	}

	.item-label {
		color: #999;
		width: 160rpx;
		flex-shrink: 0;
	}

	.item-value {
		color: #fff;
		flex: 1;
	}


	.student-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.student-item {
		display: flex;
		align-items: center;
		background-color: #3a3a3a;
		border-radius: 8rpx;
		padding: 15rpx;
		width: calc(50% - 10rpx);
		cursor: pointer;
		transition: background-color 0.3s;

		&:active {
			background-color: #4a4a4a;
		}
	}

	.student-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 40rpx;
		overflow: hidden;
		margin-right: 15rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.student-detail {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.student-name {
		font-size: 28rpx;
		color: #fff;
		margin-bottom: 8rpx;
	}

	.student-status {
		font-size: 24rpx;
	}

	.status-pending {
		color: #ff9500;
	}

	.status-upcoming {
		color: #29d3b4;
	}

	.status-ongoing {
		color: #007aff;
	}

	.status-completed {
		color: #8e8e93;
	}

	.status-leave {
		color: #ff3b30;
	}

	/* 签到状态相关样式 */
	.attendance-status {
		display: flex;
		align-items: center;
		margin: 8rpx 0;
		font-size: 24rpx;
	}

	.status-label {
		color: #666;
		margin-right: 8rpx;
	}

	.status-text {
		font-weight: 600;
		padding: 4rpx 12rpx;
		border-radius: 12rpx;
		font-size: 22rpx;
	}

	.status-text.status-pending {
		background: rgba(255, 149, 0, 0.1);
		color: #ff9500;
		border: 1rpx solid rgba(255, 149, 0, 0.2);
	}

	.status-text.status-completed {
		background: rgba(41, 211, 180, 0.1);
		color: #29d3b4;
		border: 1rpx solid rgba(41, 211, 180, 0.2);
	}

	.status-text.status-leave {
		background: rgba(255, 59, 48, 0.1);
		color: #ff3b30;
		border: 1rpx solid rgba(255, 59, 48, 0.2);
	}

	.status-absent {
		color: #8e8e93;
	}

	.status-present {
		color: #29d3b4;
	}

	.action-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 30rpx;
		gap: 20rpx;
		width: 100%;
	}

	.action-button {
		flex: 1;
		height: 80rpx;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		transition: all 0.3s ease;
		position: relative;
		overflow: hidden;

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

		.btn-text {
			font-size: 28rpx;
			font-weight: 600;
			color: #fff;
		}
	}

	.edit-btn {
		background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
		border: 1px solid #007bff;

		&:hover {
			background: linear-gradient(135deg, #0056b3 0%, #004085 100%);
		}

		&:active {
			background: linear-gradient(135deg, #004085 0%, #002752 100%);
		}
	}

	.add-btn {
		background: linear-gradient(135deg, #29d3b4 0%, #22a68b 100%);
		border: 1px solid #29d3b4;

		&:hover {
			background: linear-gradient(135deg, #22a68b 0%, #1a8b6f 100%);
		}

		&:active {
			background: linear-gradient(135deg, #1a8b6f 0%, #136045 100%);
		}
	}


	.loading,
	.error-message {
		height: 300rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.loading-text {
		margin-top: 20rpx;
		font-size: 28rpx;
		color: #ccc;
	}

	.error-message {
		color: #ff6b6b;
		font-size: 28rpx;
		text-align: center;
	}

	.retry-btn {
		margin-top: 30rpx;
		padding: 12rpx 30rpx;
		background-color: #29d3b4;
		border-radius: 8rpx;
		color: #fff;
		font-size: 24rpx;
	}

	.empty-list {
		padding: 40rpx 0;
		text-align: center;
		color: #999;
		font-size: 28rpx;
	}

	/* 学员点名弹窗样式 */
	.attendance-modal {
		padding: 20rpx;
	}

	.student-info {
		text-align: center;
		margin-bottom: 40rpx;
	}

	.student-avatar-large {
		width: 120rpx;
		height: 120rpx;
		border-radius: 60rpx;
		overflow: hidden;
		margin: 0 auto 20rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.student-name-large {
		font-size: 32rpx;
		color: #fff;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.current-status {
		font-size: 24rpx;
		color: #999;
	}

	.attendance-options {
		display: flex;
		gap: 20rpx;
		justify-content: center;
	}

	.option-btn {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20rpx;
		border-radius: 12rpx;
		min-width: 120rpx;
		cursor: pointer;
		transition: opacity 0.3s;

		text {
			margin-top: 8rpx;
			font-size: 24rpx;
			color: #fff;
		}

		&:active {
			opacity: 0.7;
		}
	}

	.option-btn.sign-in {
		background-color: #29d3b4;
	}

	.option-btn.leave {
		background-color: #ff9500;
	}

	.option-btn.cancel {
		background-color: #8e8e93;
	}

	/* 学员卡片网格样式 */
	.cards-grid {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
		margin-top: 20rpx;
	}

	.student-card {
		background: #3a3a3a;
		border-radius: 12rpx;
		padding: 20rpx;
		min-height: 200rpx;
		position: relative;
		cursor: pointer;
		transition: all 0.3s ease;
		border: 2px solid transparent;
		width: calc(50% - 8rpx);
		flex: 0 0 calc(50% - 8rpx);
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.student-card.filled {
		border-color: #29d3b4;
	}

	.student-card.waiting-filled {
		border-color: #8b5cf6;
		background: #2a2a3a;
		position: relative;
	}

	/* 转换提示图标 */
	.convert-icon {
		position: absolute;
		top: 8rpx;
		left: 8rpx;
		width: 32rpx;
		height: 32rpx;
		background: linear-gradient(45deg, #8b5cf6, #a855f7);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16rpx;
		z-index: 5;
		animation: pulse 2s infinite;
	}

	@keyframes pulse {
		0% {
			transform: scale(1);
			opacity: 1;
		}
		50% {
			transform: scale(1.1);
			opacity: 0.8;
		}
		100% {
			transform: scale(1);
			opacity: 1;
		}
	}

	.student-card:active {
		transform: scale(0.98);
		background-color: #4a4a4a;
	}

	/* 徽章样式 */
	.renewal-badge {
		position: absolute;
		top: 12rpx;
		right: 12rpx;
		background: #ef4444;
		color: white;
		font-size: 20rpx;
		padding: 4rpx 8rpx;
		border-radius: 8rpx;
		z-index: 10;
		font-weight: 500;
	}

	.trial-badge {
		position: absolute;
		top: 12rpx;
		right: 12rpx;
		background: #8b5cf6;
		color: white;
		font-size: 20rpx;
		padding: 4rpx 8rpx;
		border-radius: 8rpx;
		z-index: 10;
		font-weight: 500;
	}

	/* 头像样式 */
	.avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		background: #29d3b4;
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: 600;
		font-size: 24rpx;
		margin-bottom: 12rpx;
		flex-shrink: 0;
	}

	.waiting-avatar {
		background: #8b5cf6;
	}

	/* 学员信息样式 */
	.student-info {
		font-size: 22rpx;
		line-height: 1.4;
		width: 100%;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
	}

	.student-name {
		font-weight: 600;
		font-size: 26rpx;
		color: #fff;
		margin-bottom: 8rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		width: 100%;
		box-sizing: border-box;
	}

	.student-age,
	.course-status,
	.course-arrangement {
		color: #999;
		margin-bottom: 6rpx;
		font-size: 22rpx;
	}

	/* 体验课学员信息样式 */
	.trial-info {
		margin-top: 8rpx;
	}

	.trial-hours {
		color: #8b5cf6;
		font-weight: 500;
		font-size: 22rpx;
	}

	/* 付费学员信息样式 */
	.paid-student-info {
		margin-top: 8rpx;
	}

	.remaining-hours,
	.expiry-date {
		color: #999;
		margin-bottom: 6rpx;
		font-size: 20rpx;
	}

	/* 课时进度条样式 */
	.progress-container {
		margin-top: 10rpx;
	}

	.progress-label {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 6rpx;
		font-size: 18rpx;
		color: #999;
	}

	.progress-percentage {
		color: #29d3b4;
		font-weight: 600;
		font-size: 18rpx;
	}

	.progress-bar {
		width: 100%;
		height: 8rpx;
		background: #4a4a4a;
		border-radius: 4rpx;
		overflow: hidden;
	}

	.progress-fill {
		height: 100%;
		background: linear-gradient(90deg, #29d3b4 0%, #22a68b 100%);
		border-radius: 4rpx;
		transition: width 0.3s ease;
	}

	/* 升级确认弹窗样式 */
	.upgrade-confirm-modal {
		padding: 40rpx 30rpx;
		text-align: center;
	}

	.confirm-content {
		margin-bottom: 40rpx;
	}

	.upgrade-icon {
		font-size: 60rpx;
		margin-bottom: 20rpx;
		background: linear-gradient(45deg, #8b5cf6, #a855f7);
		background-clip: text;
		-webkit-background-clip: text;
		color: transparent;
		animation: glow 2s ease-in-out infinite alternate;
	}

	@keyframes glow {
		from {
			filter: drop-shadow(0 0 5rpx #8b5cf6);
		}
		to {
			filter: drop-shadow(0 0 15rpx #a855f7);
		}
	}

	.confirm-text {
		font-size: 32rpx;
		color: #fff;
		line-height: 1.5;
		margin-bottom: 16rpx;
	}

	.student-name-highlight {
		color: #8b5cf6;
		font-weight: bold;
	}

	.confirm-tip {
		font-size: 26rpx;
		color: #999;
		line-height: 1.4;
	}

	.confirm-buttons {
		display: flex;
		gap: 20rpx;
		justify-content: center;
	}

	.confirm-btn {
		flex: 1;
		padding: 24rpx 32rpx;
		border-radius: 12rpx;
		cursor: pointer;
		transition: all 0.3s ease;
		text-align: center;
		max-width: 200rpx;
	}

	.confirm-btn text {
		font-size: 28rpx;
		font-weight: 600;
	}

	.cancel-btn {
		background: #4a4a4a;
		border: 1px solid #666;
	}

	.cancel-btn text {
		color: #ccc;
	}

	.cancel-btn:active {
		background: #5a5a5a;
		transform: scale(0.98);
	}

	.upgrade-btn {
		background: linear-gradient(45deg, #8b5cf6, #a855f7);
		border: 1px solid #8b5cf6;
	}

	.upgrade-btn text {
		color: #fff;
	}

	.upgrade-btn:active {
		background: linear-gradient(45deg, #7c3aed, #9333ea);
		transform: scale(0.98);
	}

	/* 删除确认弹窗样式 */
	.delete-confirm-modal {
		padding: 40rpx 30rpx;
		text-align: center;
	}

	.error-icon {
		font-size: 60rpx;
		margin-bottom: 20rpx;
		color: #ef4444;
		animation: shake 2s ease-in-out infinite;
	}

	@keyframes shake {
		0%, 100% { transform: translateX(0); }
		25% { transform: translateX(-5rpx); }
		75% { transform: translateX(5rpx); }
	}

	.error-message {
		font-size: 28rpx;
		color: #ef4444;
		font-weight: 600;
		margin-bottom: 20rpx;
		padding: 20rpx;
		background: rgba(239, 68, 68, 0.1);
		border-radius: 16rpx;
		border: 2rpx solid rgba(239, 68, 68, 0.2);
	}

	.delete-btn {
		background: linear-gradient(45deg, #ef4444, #f87171);
		color: #fff;
		border: none;
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.95);
			box-shadow: 0 2rpx 8rpx rgba(239, 68, 68, 0.4);
		}
	}
</style>
