<template>
	<view class="container">
		<image class="cbg" :src="base.imgHost('common_bg.png')"></image>
		<view class="search-wrap" v-if="selectList.length>0">
			<view class="search">
				<!-- <view class="select"> -->
				<w-select width="250rpx" :showClose="false" style="margin-left: 20rpx;" v-model="chooseValue"
					:list="selectList" valueName="name" keyName="id" @change="changeMonth">
				</w-select>
				<!-- </view> -->
				<view class="all" @click="changeAll">全部课表</view>
			</view>
		</view>
		<view class="search-tab" v-if="selectDayList.length>0">
			<u-tabs :bg-color="'#f0f7fc'" active-color="#b89155" :list="selectDayList" name="value" :is-scroll="true"
				:current="current" @change="changeSearchDay"></u-tabs>
		</view>
		<view class="wrap" :style="isAll?'padding-top:100rpx':'padding-top:30rpx'">
			<view v-if="dayDataList.length>0">
				<view class="item" v-for="item in dayDataList">
					<view v-if="isAll" class="item-date">{{item.monthday}}</view>
					<view v-if="type=='near' && item.course" style="color:#b89155;padding-bottom:10rpx">
						{{item.course.type_detail?item.course.type_detail.name+"|":''}}{{item.course.name?item.course.name:''}}
					</view>
					<view class="item-period">{{item.period}}</view>
					<view class="item-img">
						<image :src="base.imgHost('mycourse-c2.png')" style="width:22rpx;height:22rpx"></image>
						<text>{{item.theme}}</text>
					</view>
					<view class="item-img">
						<image :src="base.imgHost('mycourse-c1.png')" style="width:20rpx;height:23rpx"></image>
						<text>{{item.teacher?item.teacher.name:''}}</text>
					</view>
					<view class="item-img">
						<image :src="base.imgHost('mycourse-c3.png')" style="width:19rpx;height:27rpx"></image>
						<text>{{item.address}}</text>
					</view>
					<view class="item-btn">
						<view @click="goSign(item.id)">签到</view>
						// <view v-if="item.course_content_evaluation && item.course_content_evaluation.status==1" @click="goSurvey(item.id)">问卷调查</view>
					</view>
				</view>
			</view>
			<view class="nodata" v-else>
				<u-empty text="当前没有排课" mode="data"></u-empty>
			</view>
		</view>
	</view>
</template>

<script>
	import wSelect from "@/components/w-select/w-select.vue"
	export default {
		components: {
			wSelect
		},
		data() {
			return {
				list: [],
				dayDataList: [],
				chooseValue: '',
				selectList: '',
				selectDayList: [],
				current: 0,
				isAll: false,
				type: ''
			}
		},
		onLoad(options) {
			this.type = options.type ? options.type : ''
			uni.setNavigationBarTitle({
				title: this.type == 'near' ? '近期课表' : '本班课表',
				success: function() {
					console.log('标题设置成功');
				},
				fail: function(err) {
					console.error('标题设置失败', err);
				}
			});
			this.getMyCourseContents(options.id)
		},
		methods: {
			goSign(id){
				uni.navigateTo({
					url:'/packages/sign/index?id='+id
				})
			},
			goSurvey(id){
				uni.navigateTo({
					url:'/packages/surveyFill/index?id='+id
				})
			},
			async getMyCourseContents(id) {
				let res = {
					list: []
				}
				if (this.type === 'near') {
					// 近期课表
					res = await this.$u.api.myCourseContent()
					// 筛掉今天之前的
					res.list = this.filterDataByToday(res.list)
				} else {
					res = await this.$u.api.courseContent({
						course_id: id,
					})
				}

				this.list = res.list
				if (res.list.length > 0) {
					// this.dayDataList = res.list
					let obj = this.groupByMonthAndSort(res.list)
					const currentMonth = this.$moment().format('YYYY年MM月')
					const currentDay = this.$moment().format('MM月DD日')
					if (this.selectList.length > 0) {
						this.selectDayList = this.selectList[this.selectList.length - 1]['item']
						this.chooseValue = this.selectList[this.selectList.length - 1]['name']
						this.dayDataList = this.selectList[this.selectList.length - 1]['item'][0]['arr']
						this.current = 0
						this.selectList.map((item, index) => {
							if (item.name === currentMonth) {
								this.chooseValue = item.name
								this.selectDayList = item.item
								this.dayDataList = item.item[0]['arr']
								item.item.map((cur, index1) => {
									if (cur.value === currentDay) {
										this.dayDataList = cur['arr']
										this.current = index1
									}
								})
							}
						})
					}
					console.log("this.selectList", this.selectList)

				}


			},
			filterDataByToday(arr) {
				// 获取当前日期
				let filteredData = []
				const today = this.$moment().format('YYYY-MM-DD');
				// 筛选出 date 字段大于或等于今天的数据
				filteredData = arr.filter(item => {
					const itemDate = this.$moment(item.date).format('YYYY-MM-DD');
					return this.$moment(itemDate).isSameOrAfter(today);
				});

				return filteredData
			},
			changeMonth(e) {
				console.log("e", e, this.chooseValue)
				this.selectDayList = e.item
				this.dayDataList = e.item[0]['arr']
				this.current = 0
				this.isAll = false
			},
			changeAll() {
				this.current = 0
				this.selectDayList = []
				this.dayDataList = this.list
				this.isAll = true
				// this.$set(this,'chooseValue','请选择')
			},
			// 切换日期
			changeSearchDay(e) {
				console.log("e1", e)
				this.current = e
				this.dayDataList = this.selectDayList[e]['arr']
			},
			// 将日期换成 年月合并
			groupByMonthAndSort(a) {
				// 创建一个空对象来存储按月份分组的数据
				const groupedData = {};
				const weekArr = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
				// 遍历数组 a 中的每个对象
				a.forEach(item => {
					// 提取 date 字段，并转换为包含年份和月份的字符串格式
					const date = this.$moment(item.date, 'YYYY-MM-DD');

					const monthKey = date.format('YYYY年MM月');
					// 添加 monthday 字段
					const weekDay = weekArr[date.day()]
					item.monthday = date.format('MM月DD日') + '(' + weekDay + ')';

					// 如果这个月份还没有出现在 groupedData 中，就添加一个空数组
					if (!groupedData[monthKey]) {
						groupedData[monthKey] = [];
					}
					// 将当前对象添加到对应的月份数组中
					groupedData[monthKey].push(item);
				});
				let _arr = []
				for (var k in groupedData) {
					_arr.push({
						name: k,
						item: groupedData[k],
						id: k
					})
				}
				this.selectList = this.transformItemsToObject(_arr)
				// 返回重组后的数据
				return groupedData;
			},
			// 将 想同日期的合并
			transformItemsToObject(arr) {
				return arr.map(month => {
					const transformedItems = month.item.reduce((acc, curr) => {
						const key = curr.monthday;
						const existingItem = acc.find(item => item.value === key);

						if (existingItem) {
							existingItem.arr.push(curr);
						} else {
							acc.push({
								value: key,
								arr: [curr]
							});
						}

						return acc;
					}, []);

					return {
						...month,
						item: transformedItems
					};
				});
			},

		}

	}
</script>

<style scoped lang="scss">
	.container {
		padding: 30rpx;
		width: 100%;
		height: 100vh;
		overflow: scroll;

		.cbg {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100vh;
		}


		.search {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			width: 100%;
			padding: 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			box-shadow: 1rpx -4rpx 15rpx 0 #333;
			z-index: 9;
			background-color: #fff;
			height: 100rpx;

			.all {
				font-size: 28rpx;
				color: #b89155;
			}
		}

		.search-tab {
			// position: fixed;
			// top: 100rpx;
			// left: 0;
			// width: 100%;
			margin-top: 100rpx;
			background-color: #fff;
		}

		.wrap {
			position: relative;
			// padding-top: 20rpx;

			.item {
				background-color: #fff;
				padding: 30rpx;
				margin-bottom: 20rpx;
				border-radius: 20rpx;

				&-date {
					font-size: 32rpx;
					color: #b08c6c;
					margin-bottom: 20rpx
				}

				&-period {
					color: #333333;
					margin-left: 20rpx;
					margin-bottom: 10rpx
				}

				&-img {
					color: #666666;
					display: flex;
					align-items: center;
					margin-left: 20rpx;
					margin-bottom: 10rpx;

					image {
						margin-right: 10rpx;
					}
				}
				&-btn{
					width: 100%;
					position: relative;
					padding: 20rpx 0;
					display: flex;
					justify-content: flex-end;
					&>view {
						width: 30%;
						text-align: center;
						margin-left:20rpx;
						color: #fff;
						background: linear-gradient(to right, #5e5fbc, #0d0398);
						border-radius: 30rpx;
						padding: 10rpx;
					}
				}
			}

			.nodata {
				height: 100vh;
			}
		}
	}
</style>