<template>
	<fui-modal :show="visible" title="课程安排详情" width="700" @cancel="closePopup" :buttons="[]" :showClose="true">
		<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 }}</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-title">学员信息 ({{ scheduleInfo.students ? scheduleInfo.students.length : 0 }}人)
				</view>
				<view class="student-list" v-if="scheduleInfo.students && scheduleInfo.students.length > 0">
					<view class="student-item" v-for="(student, index) in scheduleInfo.students" :key="index" 
						@click="handleStudentClick(student, index)">
						<view class="student-avatar">
							<image :src="student.avatar || '/static/icon-img/avatar.png'" mode="aspectFill"></image>
						</view>
						<view class="student-detail">
							<text class="student-name">{{ student.name }}</text>
							<text class=""
								:class="['student-status',student.statusClass]">{{ student.status_text }}</text>
						</view>
					</view>
				</view>
				<view class="empty-list" v-else>
					<text>暂无学员参与此课程</text>
				</view>
			</view>

			<!-- 操作按钮 -->
			<view class="action-buttons">
				<fui-button type="primary" @click="handleEditCourse">编辑课程</fui-button>
				<fui-button type="default" @click="handleAddNewCourse">新增课程</fui-button>
			</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 || '/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')">
						<fui-icon name="check" :size="20" color="#fff"></fui-icon>
						<text>签到</text>
					</view>
					<view class="option-btn leave" @click="handleAttendanceAction('leave')">
						<fui-icon name="clock" :size="20" color="#fff"></fui-icon>
						<text>请假</text>
					</view>
					<view class="option-btn cancel" @click="closeAttendanceModal">
						<fui-icon name="close" :size="20" color="#fff"></fui-icon>
						<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: {
			statusClass() {
				const statusMap = {
					'pending': 'status-pending',
					'upcoming': 'status-upcoming',
					'ongoing': 'status-ongoing',
					'completed': 'status-completed'
				};
				return statusMap[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
			}
		},
		watch: {
			visible(newVal) {
				if (newVal && this.scheduleId) {
					this.fetchScheduleDetail();
				}
			},
			scheduleId(newVal) {
				if (newVal && this.visible) {
					this.fetchScheduleDetail();
				}
			}
		},
		methods: {
			// 获取课程安排详情
			async fetchScheduleDetail() {
				if (!this.scheduleId) {
					this.error = true;
					this.errorMessage = '课程ID不能为空';
					return;
				}

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

				try {
					const res = await api.getCourseScheduleInfo({
						schedule_id: this.scheduleId
					});
					if (res.code === 1) {
						this.scheduleInfo = res.data;
					} 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) {
				this.selectedStudent = student;
				this.selectedStudentIndex = index;
				this.showAttendanceModal = true;
			},

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

			// 处理点名操作
			handleAttendanceAction(action) {
				if (!this.selectedStudent) return;
				
				const actionMap = {
					'sign_in': { status: 1, text: '已签到' },
					'leave': { status: 2, text: '请假' }
				};
				
				if (actionMap[action]) {
					// 更新学员状态
					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'
					});
				}
				
				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] || '未知状态';
			},
		}
	}
</script>

<style lang="scss" scoped>
	.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-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #29d3b4;
		margin-bottom: 20rpx;
		border-bottom: 1px solid #3a3a3a;
		padding-bottom: 10rpx;
	}

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

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

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

	.action-buttons {
		display: flex;
		justify-content: space-around;
		margin-top: 30rpx;
		gap: 30rpx;
	}


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