<template>
	<view class="class-arrange-root">
		<!-- 顶部日期选择 -->
		<view class="date-bar">
			<view class="date-item" v-for="(item, idx) in weekList" :key="idx" :class="{active: item.status}" @click="getDate(item.date,item.day)">
				<view class="week">{{ item.week }}</view>
				<view class="day">{{ item.day }}</view>
			</view>
		</view>
		<!-- "查询"按钮移到日期条下方 -->
		<view class="more-bar-wrapper">
			<view class="more-bar" @click="openSearchPopup">
				<text>查询</text>
				<uni-icons type="arrowdown" size="18" color="#bdbdbd" />
			</view>
		</view>
		<!-- 日历底部弹窗 -->
		<uni-popup ref="calendarPopup" type="bottom">
			<uni-calendar @change="onCalendarChange" />
		</uni-popup>

		<!-- 查询弹窗 -->
		<view v-if="showSearchPopup" class="search_popup_mask" @tap="showSearchPopup=false">
			<view class="search_popup_content" @tap.stop>
				<view class="popup_search_content">
					<view class="popup_header">
						<view class="popup_title">筛选</view>
						<view class="popup_close" @tap="showSearchPopup=false">
							<text class="close_text">✕</text>
						</view>
					</view>
					
					<scroll-view :scroll-y="true" class="popup_scroll_view">
						<!-- 筛选区域 -->
						<view class="popup_filter_section">
							<view class="popup_filter_row">
								<view class="popup_filter_item">
									<text class="popup_filter_label">时间查询</text>
									<picker :value="timeIndex" :range="timeOptions" @change="onTimeChange">
										<view class="popup_filter_picker">{{ timeOptions[timeIndex] }}</view>
									</picker>
								</view>
								<view class="popup_filter_item">
									<text class="popup_filter_label">班主任筛选</text>
									<input class="popup_filter_input" placeholder="人员名称筛选" v-model="searchForm.teacher_name" />
								</view>
							</view>
							
							<view class="popup_filter_row">
								<view class="popup_filter_item">
									<text class="popup_filter_label">开始日期</text>
									<picker mode="date" :value="searchForm.start_date" @change="onStartDateChange">
										<view class="popup_filter_input">
											{{ searchForm.start_date || '选择开始日期' }}
										</view>
									</picker>
								</view>
								<view class="popup_filter_item">
									<text class="popup_filter_label">结束日期</text>
									<picker mode="date" :value="searchForm.end_date" @change="onEndDateChange">
										<view class="popup_filter_input">
											{{ searchForm.end_date || '选择结束日期' }}
										</view>
									</picker>
								</view>
							</view>
							
							<view class="popup_filter_row">
								<view class="popup_filter_item">
									<text class="popup_filter_label">固定位筛选</text>
									<input class="popup_filter_input" placeholder="输入固定位编号" v-model="searchForm.venue_number" type="number" />
								</view>
							</view>
						</view>
					</scroll-view>
					
					<view class="popup_filter_buttons">
						<view class="popup_filter_btn reset_btn" @click="resetSearchOnly">重置</view>
						<view class="popup_filter_btn search_btn" @click="searchDataAndClose">搜索</view>
						<view class="popup_filter_btn close_btn" @click="closeSearchPopup">关闭</view>
					</view>
				</view>
			</view>
		</view>


		<!-- 课程卡片列表 -->
		<view class="course-list">
			<view class="course-card" v-for="(course, idx) in courseList" :key="idx">
				<view class="card-header">
					<view class="status-end">{{ getStatusText(course.status) }}</view>
				</view>
				<view class="card-body">
					<view class="row">时间：{{ course.course_date || '未设置' }}</view>
					<view class="row">校区：{{ course.campus_name || '未设置' }}</view>
					<view class="row">教室：{{ course.venue ? course.venue.venue_name : '未设置' }}</view>
					<view class="row">课程：{{ course.course ? course.course.course_name : '未设置' }}</view>
					<view class="row">人数：{{ course.available_capacity || 0 }}</view>
					<view class="row">安排情况：{{ course.student ? course.student.length : 0 }}/{{course.max_students ? course.max_students : '不限'}}</view>
				</view>
				<view class="card-footer">
					<button class="detail-btn" @click="viewDetail(course)">详情</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import apiRoute from '@/api/apiRoute.js';
	export default {
		data() {
			return {
				weekList: [],
				selectedDayIndex: 4,
				date: '',
				courseList: [],
				resource_id: '',
        student_id: '',
				
				// 查询弹窗相关
				showSearchPopup: false,
				searchForm: {
					time_hour: '',
					start_date: '',
					end_date: '',
					teacher_name: '',
					venue_number: ''
				},
				
				// 时间选择器相关
				timeIndex: 0,
				timeOptions: ['全部时间', '上午(8:00-12:00)', '下午(12:00-18:00)', '晚上(18:00-22:00)']
			};
		},
		onLoad(options) {
			this.resource_id = options.resource_id || '';
			this.student_id = options.student_id || '';
			this.getDate();
			
		},
		methods: {
			async getDate(date = '', day = '') {
				try {
					let res = await apiRoute.getDate({
						'date': date,
						'day': day
					})
					this.weekList = res.data.dates
					this.date = res.data.date

					let data = await apiRoute.courseAllList({
						'schedule_date': this.date
					})
					// 确保courseList是数组，并处理可能的空数据
					this.courseList = Array.isArray(data.data) ? data.data : []


				} catch (error) {
					console.error('获取信息失败:', error);
					// 确保即使出错也有默认数据
					this.courseList = [];
					uni.showToast({
						title: '获取课程数据失败',
						icon: 'none'
					});
				}
			},
			openCalendar() {
				this.$refs.calendarPopup.open();
			},
			closeCalendar() {
				console.log(123123)
				this.$refs.calendarPopup.close();
			},
			viewDetail(course) {
				// 跳转到课程详情页
				const resourceId = this.resource_id || '';
				const studentId = this.student_id || '';
				console.log('跳转到课程详情页:', course.id, resourceId, studentId);
				uni.navigateTo({
					url: '/pages-market/clue/class_arrangement_detail?schedule_id=' + course.id + '&resource_id=' + resourceId + '&student_id=' + studentId,
					fail: (err) => {
						console.error('跳转到课程详情页失败:', err);
						uni.showToast({
							title: '页面跳转失败',
							icon: 'none'
						});
					}
				});
			},
			onCalendarConfirm(e) {

				// 这里可以处理选中的日期 e.fulldate
				uni.showToast({
					title: '选择日期：' + e.fulldate,
					icon: 'none'
				});

				this.closeCalendar();
			},
			onCalendarChange(e) {
				this.getDate(e.fulldate, e.date);
				this.closeCalendar();
			},
			getStatusText(status) {
				const statusMap = {
					pending: '待开始',
					upcoming: '即将开始',
					ongoing: '进行中',
					completed: '已结束'
				};
				return statusMap[status] || status;
			},
			
			// 查询弹窗相关方法
			openSearchPopup() {
				this.showSearchPopup = true;
			},
			
			closeSearchPopup() {
				this.showSearchPopup = false;
			},
			
			// 时间选择器变化
			onTimeChange(e) {
				this.timeIndex = e.detail.value;
				this.searchForm.time_hour = this.timeOptions[this.timeIndex];
			},
			
			// 开始日期选择变化
			onStartDateChange(e) {
				this.searchForm.start_date = e.detail.value;
				console.log('开始日期选择:', e.detail.value);
			},
			
			// 结束日期选择变化
			onEndDateChange(e) {
				this.searchForm.end_date = e.detail.value;
				console.log('结束日期选择:', e.detail.value);
			},
			
			// 搜索并关闭弹窗
			searchDataAndClose() {
				console.log('执行搜索，表单数据:', this.searchForm);
				this.searchCourseData();
				this.showSearchPopup = false;
			},
			
			// 搜索课程数据
			async searchCourseData() {
				try {
					let searchParams = {
						schedule_date: this.date
					};
					
					// 添加搜索条件
					if (this.searchForm.time_hour && this.searchForm.time_hour !== '全部时间') {
						searchParams.time_hour = this.searchForm.time_hour;
					}
					if (this.searchForm.start_date) {
						searchParams.start_date = this.searchForm.start_date;
					}
					if (this.searchForm.end_date) {
						searchParams.end_date = this.searchForm.end_date;
					}
					if (this.searchForm.teacher_name) {
						searchParams.teacher_name = this.searchForm.teacher_name;
					}
					if (this.searchForm.venue_number) {
						searchParams.venue_number = this.searchForm.venue_number;
					}
					
					console.log('搜索参数:', searchParams);
					
					let data = await apiRoute.courseAllList(searchParams);
					// 确保courseList是数组，并处理可能的空数据
					this.courseList = Array.isArray(data.data) ? data.data : [];
					
					uni.showToast({
						title: '查询完成',
						icon: 'success'
					});
				} catch (error) {
					console.error('搜索失败:', error);
					uni.showToast({
						title: '搜索失败',
						icon: 'none'
					});
				}
			},
			
			// 重置搜索条件
			resetSearchOnly() {
				this.searchForm = {
					time_hour: '',
					start_date: '',
					end_date: '',
					teacher_name: '',
					venue_number: ''
				};
				this.timeIndex = 0;
				
				// 重新加载默认数据
				this.getDate();
			},
			
			// 数据安全处理方法 - 确保嵌套对象访问的安全性
			safeGet(obj, path, defaultValue = '') {
				if (!obj) return defaultValue;
				const keys = path.split('.');
				let result = obj;
				for (let key of keys) {
					if (result === null || result === undefined || !result.hasOwnProperty(key)) {
						return defaultValue;
					}
					result = result[key];
				}
				return result || defaultValue;
			}
		},
	};
</script>

<style lang="less" scoped>
	.class-arrange-root {
		background: #232323;
		min-height: 100vh;
		padding-bottom: 30rpx;
	}

	.date-bar {
		display: flex;
		align-items: center;
		background: #232323;
		padding: 0 0 10rpx 0;
		overflow-x: auto;
		border-bottom: 1px solid #333;

		.date-item {
			flex: 1;
			text-align: center;
			color: #bdbdbd;
			padding: 16rpx 0 0 0;

			.week {
				font-size: 22rpx;
			}

			.day {
				font-size: 28rpx;
				margin-top: 4rpx;
			}

			&.active {
				color: #29d3b4;

				.day {
					border-radius: 50%;
					background: #333;
					color: #29d3b4;
					padding: 2rpx 10rpx;
				}
			}
		}
	}

	.more-bar-wrapper {
		width: 100%;
		display: flex;
		justify-content: center;
		margin: 10rpx 0 0 0;
	}

	.more-bar {
		display: flex;
		align-items: center;
		color: #bdbdbd;
		font-size: 22rpx;
		cursor: pointer;
		background: #333;
		border-radius: 20rpx;
		padding: 8rpx 24rpx;
	}

	.course-list {
		margin-top: 20rpx;

		.course-card {
			background: #434544;
			border-radius: 10rpx;
			margin: 0 0 20rpx 0;
			padding: 0 0 20rpx 0;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);

			.card-header {
				display: flex;
				justify-content: flex-end;
				padding: 10rpx 20rpx 0 0;

				.status-end {
					background: #e95c6b;
					color: #fff;
					border-radius: 10rpx;
					padding: 4rpx 18rpx;
					font-size: 22rpx;
				}
			}

			.card-body {
				padding: 0 20rpx;

				.row {
					color: #fff;
					font-size: 24rpx;
					margin: 8rpx 0;
				}
			}

			.card-footer {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 0 20rpx;

				.sign-info {
					color: #bdbdbd;
					font-size: 22rpx;
				}

				.detail-btn {
					background: transparent;
					border: 2rpx solid #ffd86b;
					color: #ffd86b;
					border-radius: 8rpx;
					padding: 6rpx 24rpx;
					font-size: 24rpx;
          width: 100%;
					margin-top: 40rpx;
				}
			}
		}
	}

	// 搜索弹窗样式
	.search_popup_mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
		z-index: 999;
		display: flex;
		flex-direction: column;
	}

	.search_popup_content {
		background: #fff;
		border-bottom-left-radius: 24rpx;
		border-bottom-right-radius: 24rpx;
		animation: slideDown 0.3s ease-out;
		width: 100%;
		max-height: 80vh;
		overflow: hidden;
		display: flex;
		flex-direction: column;
	}

	@keyframes slideDown {
		from {
			transform: translateY(-100%);
		}
		to {
			transform: translateY(0);
		}
	}

	// 弹窗搜索内容样式
	.popup_search_content {
		padding: 0;
		background: #fff;
		min-height: 60vh;
		max-height: 80vh;
		display: flex;
		flex-direction: column;
		border-bottom-left-radius: 24rpx;
		border-bottom-right-radius: 24rpx;
		overflow: hidden;
	}

	.popup_header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 32rpx;
		border-bottom: 1px solid #f0f0f0;
	}

	.popup_title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.popup_close {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		
		.close_text {
			font-size: 32rpx;
			color: #999;
		}
	}

	.popup_scroll_view {
		flex: 1;
		padding: 32rpx;
		overflow-y: auto;
	}

	.popup_filter_section {
		margin-bottom: 32rpx;
		
		&:last-child {
			margin-bottom: 0;
		}
	}

	.popup_filter_row {
		display: flex;
		gap: 20rpx;
		margin-bottom: 24rpx;
		
		&:last-child {
			margin-bottom: 0;
		}
	}

	.popup_filter_item {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 12rpx;
		
		&.full_width {
			flex: 1;
		}
		
		.popup_filter_label {
			font-size: 26rpx;
			color: #666;
			font-weight: 500;
		}
		
		.popup_filter_input {
			height: 72rpx;
			line-height: 72rpx;
			padding: 0 16rpx;
			border: 1px solid #ddd;
			border-radius: 8rpx;
			font-size: 28rpx;
			color: #333;
			background: #fff;
			
			&::placeholder {
				color: #999;
			}
		}
		
		.popup_filter_picker {
			height: 72rpx;
			line-height: 72rpx;
			padding: 0 16rpx;
			border: 1px solid #ddd;
			border-radius: 8rpx;
			font-size: 28rpx;
			color: #333;
			background: #fff;
			position: relative;
			
			&::after {
				content: '▼';
				position: absolute;
				right: 16rpx;
				font-size: 20rpx;
				color: #999;
			}
		}
	}

	.popup_filter_buttons {
		display: flex;
		gap: 20rpx;
		padding: 32rpx;
		margin-top: auto;
		border-top: 1px solid #f0f0f0;
		background: #fff;
		border-bottom-left-radius: 24rpx;
		border-bottom-right-radius: 24rpx;
	}

	.popup_filter_btn {
		flex: 1;
		height: 72rpx;
		line-height: 72rpx;
		text-align: center;
		border-radius: 8rpx;
		font-size: 28rpx;
		font-weight: 600;
		
		&.search_btn {
			background: #29d3b4;
			color: #fff;
		}
		
		&.reset_btn {
			background: #f5f5f5;
			color: #666;
			border: 1px solid #ddd;
		}
		
		&.close_btn {
			background: #666;
			color: #fff;
		}
	}
</style>