<template>
	<view class="" :style="{ 'padding-top': `${statusBarHeight}px` }">

		<view style="height: 100rpx"></view>
		<view class="navbar">
			<van-nav-bar title="课表" fixed title-class="navTitle">
				<view slot="left" class="chooseDate flex flex_start_center">
					<view @click="showdatetime">{{ currentDate }}</view>
				</view>
			</van-nav-bar>
		</view>
		<van-popup :show="showPopup" round position="bottom" custom-style="height: 50%" @close="onClose">
			<van-datetime-picker type="year-month" :value="getCurrentDate" @cancel="onClose" @confirm="onConfirm" />
		</van-popup>
		<swiper :style="{height:!isShowAllDay?'220rpx':'620rpx'}" circular :current="1"
			@change="changeSwiper($event,preSwiperId)">
			<swiper-item v-for="(Sitem,Sindex) in swiperArr" :key="Sindex">
				<view class="calendar flex flex_wrap">
					<view v-for="(item, index) in weekArr" :key="index" class="calendar-week-item no_shrink">
						<view class="calendar-week">{{ item }}</view>
					</view>
					<view v-for="(item, index) in sliceWeekArr" :key="index" class="calendar-item no_shrink"
						v-if="!isShowAllDay">
						<view class="calendar-day flex flex_center_center" ref="calendarDay"
							@click="calendarActive(item)" v-show="item">
							<view class=""
								:class="{ 'calendar-active': activeDay === item.day ,'calendar-leave':isLeave(item),'calendar-leave2':isLeave2(item)}">
								{{ item.day }}
							</view>
						</view>
						<view class="isToday" v-if="item.isToday === 1">今天</view>
						<view class="haveCourse" v-if="getHaveCourse(item)"></view>
					</view>
					<view v-for="(item, index) in calendar" :key="index" class="calendar-item no_shrink"
						v-if="isShowAllDay">
						<view class="calendar-day flex flex_center_center" ref="calendarDay"
							@click="calendarActive(item), sliceWeek(item)" v-show="item">
							<view class=""
								:class="{ 'calendar-active': activeDay === item.day,'calendar-leave':isLeave(item),'calendar-leave2':isLeave2(item) }">
								{{ item.day }}
							</view>
						</view>
						<view class="isToday" v-if="item.isToday === 1">今天</view>
						<view class="haveCourse" v-if="getHaveCourse(item)"></view>
					</view>

					<view class="openorclose flex flex_center_center">
						<van-divider contentPosition="center" style="width: 90%" v-if="isShowAllDay">
							<van-icon name="arrow-up" size="40rpx" color="#0000ff" @click="changeCalendar" />
						</van-divider>
						<van-divider contentPosition="center" style="width: 90%" v-if="!isShowAllDay">
							<van-icon name="arrow-down" size="40rpx" color="#0000ff" @click="changeCalendar" />
						</van-divider>
					</view>
				</view>
			</swiper-item>
		</swiper>

		<view class="Timetable-box">
			<view class="flex flex_center_center" v-if="loading">
				<van-loading size="48rpx" type="spinner">加载中...</van-loading>
			</view>
			<van-empty description="暂无课程" v-if="dataList.length === 0" />
			<view v-for="(item, index) in dataList" :key="index" v-if="dataList.length > 0">
				<Item :data="item" />
			</view>
		</view>
		<van-toast id="van-toast" />
		<view class="btnfixed">
			<image @click="goappointment"
				src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/educationStu/yuyuebtn.png"
				mode="widthFix"></image>
		</view>
	</view>
</template>

<script>
	import Item from "./timeTable-item.vue";
	import {
		ref,
		reactive,
		toRefs,
		toRef,
		getCurrentInstance,
		watch,
		computed,
		onMounted,
		nextTick,
		inject,
	} from "vue";
	import {
		getWeek,
		getToday,
		getMonthMaxDay,
	} from "../../utils/date.js";
	import {
		getStundentPlanStatistical
	} from "../../api/index";
	export default {
		name: "",
		props: {},
		components: {
			Item
		},
		setup(props) {
			const Toast = inject('$toast')
			const indexData=uni.getStorageSync('indexData')
			let weekArr = ["日", "一", "二", "三", "四", "五", "六"];
			//年月选择
			let currentDate = ref(0);
			currentDate.value = getToday("y", "m");
			let getCurrentDate = ref(0);
			getCurrentDate.value = new Date().getTime();
			//弹出层
			let showPopup = ref(false);
			let showdatetime = () => {
				showPopup.value = true;
			};
			let onClose = () => {
				showPopup.value = false;
			};
			//选择月份
			let onConfirm = (val) => {
				showPopup.value = false;
				isShowAllDay.value = true;
				activeDay.value = 1;
				let curdate = new Date(val.detail);
				getCurrentDate.value = val.detail;
				let year = curdate.getFullYear();
				let month = curdate.getMonth() < 9 ? "0" + (curdate.getMonth() + 1) : curdate.getMonth() + 1
				currentDate.value = year + "-" + month
				getcalendar(curdate.getFullYear(), curdate.getMonth() + 1);
				let newArr = calendar.value.slice(emptyArr.length, calendar.value.length);
				sliceWeek(newArr[0]);
				data.msg.StartTime = currentDate.value + '-01'
				data.msg.EndTime = currentDate.value + '-' + getMonthMaxDay(year, month);
				// that.getData()
				that.getAllData()

			};
			//获取当月日历数组
			let calendar = ref([]);
			//默认选中
			let activeDay = ref(1);
			//切换选中日期
			let calendarActive = (item) => {
				let d = item.$orig?.day || item.day
				activeDay.value = d;
				let day = d < 10 ? "0" + d : d;
				data.msg.StartTime = currentDate.value + "-" + day;
				data.msg.EndTime = currentDate.value + "-" + day;
				that.getData();
			};
			let emptyArr = []; //日历补空
			let getcalendar = (y, m) => {
				calendar.value = getWeek(y, m);
				emptyArr.length = calendar.value[0].week;
				if (calendar.value[0].week > 0) {
					emptyArr.fill({
						week: "",
						day: ""
					});
					calendar.value.unshift(...emptyArr);
				}
			};
			//截取最近一周
			let isShowAllDay = ref(false);
			let sliceWeekArr = ref([]);
			let sliceWeek = (item) => {
				let w = item.$orig?.week || item.week || 0
				let d = item.$orig?.day || item.day || 0
				let newArr = calendar.value.slice(emptyArr.length, calendar.value.length);
				let s = d - (w + 1) <= 0 ? 0 : d - (w + 1);
				let e = d + (6 - w);
				sliceWeekArr.value = newArr.slice(s, e);
				if (s === 0) {
					sliceWeekArr.value.unshift(...emptyArr);
				}
			};
			//切换日历展示模式
			let changeCalendar = () => {
				isShowAllDay.value = !isShowAllDay.value;
			};
			//-------------------上边日历部分---------------------------------------
			let loadingS = () => Toast({
				type: "loading",
				message: "加载中...",
				mask: true,
				duration: 0,
				forbidClick: true,
			})
			let data = reactive({
				msg: {
					ClassId: indexData.ClassId,
					StartTime: "",
					EndTime: "",
					CouseId:indexData.CourseId,
					ClassScrollType:indexData.ClassScrollType
				},
				statusBarHeight: 0,
				dataList: [],
				allData: [],
				loading: false,
				swiperArr: [{
					y: 2022,
					m: 1,
				}, {
					y: 2022,
					m: 2,
				}, {
					y: 2022,
					m: 3,
				}],
				swiperArrDemo: [{
					y: 2022,
					m: 1,
				}, {
					y: 2022,
					m: 2,
				}, {
					y: 2022,
					m: 3,
				}],
				currentSwiper: 1,
				preSwiperId: 1,
				timer: null, //防抖
			});
			let methods = {
				// 获取当天数据
				async getData() {
					if(data.msg.ClassId<=0) return
					data.loading = true
					let res = await getStundentPlanStatistical(data.msg);
					data.loading = false
					if (res) {
						data.dataList = res.Data;
					}
				},
				//获取当月数据
				async getAllData() {
					if(data.msg.ClassId<=0) return
					loadingS()
					try {
						let res = await getStundentPlanStatistical(data.msg);
						Toast.clear()
						if (data.timer) data.timer = null
						if (res) {
							data.dataList = res.Data;
							data.allData = res.Data;
						}
					} catch {
						Toast.clear()
					}

				},
				jumpPage(url) {
					uni.navigateTo({
						url: url,
					});
				},
				back() {
					uni.navigateBack();
				},
				getHaveCourse(item) {
					let date = currentDate.value + '-' + (item.day < 10 ? '0' + item.day : item.day)
					let res = false
					let find = data.allData.find((e) => {
						return e.ClassDateStr === date
					})
					if (find) {
						res = true
					}
					return res
				},
				// 请假
				isLeave(item) {
					let date = currentDate.value + '-' + (item.day < 10 ? '0' + item.day : item.day)
					let res = false
					let find = data.allData.find((e) => {
						return e.ClassDateStr === date
					})

					if (find) {
						let res1 = find.PlanTimeList.some(e => {
							return e.IsLeave === 1 && e.IsCheck == 2
						})
						if (res1) {
							res = true
						}
					}
					return res
				},
				// 缺勤
				isLeave2(item) {
					let date = currentDate.value + '-' + (item.day < 10 ? '0' + item.day : item.day)
					let res = false
					let find = data.allData.find((e) => {
						return e.ClassDateStr === date
					})
					if (find) {
						let res1 = find.PlanTimeList.some(e => {
							return e.IsCheck === 1
						})
						if (res1) {
							res = true
						}
					}
					return res
				},
				goappointment() {
					let day = currentDate.value + '-' + activeDay.value;
					uni.navigateTo({
						url: '/pages/appointment/index?day=' + day,
					});
				},
				initSwiper(){
					const date=new Date()
					const y=date.getFullYear()
					const m=date.getMonth()+1
					const d=date.getDate()
					let obj={
						y,
						m,
					}
					let obj1={
						y,
						m:m-1,
					}
					let obj2={
						y,
						m:m+1,
					}
					if(m==1){
						obj1.y=y-1
						obj1.m=12
					}
					if(m==12){
						obj1.y=y+1
						obj1.m=1
					}
					data.swiperArr=[obj1,obj,obj2]
					data.swiperArrDemo=[obj1,obj,obj2]
					console.log(data.swiperArr, data.swiperArrDemo)
				},
				changeSwiper(val, PreId) {
					let CurId = val.detail.current
					data.currentSwiper = 1
					if ((CurId > PreId && (CurId !== 2 || PreId !== 0)) || (CurId == 0 && PreId == 2)) {
						console.log('右滑')
						methods.right(CurId)
					} else if ((CurId < PreId && (CurId !== 0 || PreId !== 2)) || (CurId == 2 && PreId == 0)) {
						console.log('左滑')
						methods.left(CurId)
					}
					data.preSwiperId = val.detail.current

				},
				right(curId) {
					data.swiperArrDemo.forEach(e => {
						if (e.m == 12) {
							e.y = e.y + 1
							e.m = 1
						} else {
							e.m += 1
						}

					})
					if (curId == 0) {
						data.swiperArr = [data.swiperArrDemo[1], {}, {}]
					} else if (curId == 1) {
						data.swiperArr = [{}, data.swiperArrDemo[1], {}]
					} else if (curId == 2) {
						data.swiperArr = [{}, {}, data.swiperArrDemo[1]]
					}
					const showM = data.swiperArrDemo[1]
					const obj = {
						detail: showM.y + '-' + (showM.m < 10 ? '0' + showM.m : showM.m) + '-01'
					}
					if (data.timer) clearTimeout(data.timer)
					data.timer = setTimeout(() => {
						onConfirm(obj)
					}, 500)



				},
				left(curId) {
					data.swiperArrDemo.forEach(e => {
						if (e.m == 1) {
							e.y = e.y - 1
							e.m = 12
						} else {
							e.m = e.m - 1
						}
					})
					if (curId == 0) {
						data.swiperArr = [data.swiperArrDemo[1], {}, {}]
					} else if (curId == 1) {
						data.swiperArr = [{}, data.swiperArrDemo[1], {}]
					} else if (curId == 2) {
						data.swiperArr = [{}, {}, data.swiperArrDemo[1]]
					}
					const showM = data.swiperArrDemo[1]
					const obj = {
						detail: showM.y + '-' + (showM.m < 10 ? '0' + showM.m : showM.m) + '-01'
					}
					if (data.timer) clearTimeout(data.timer)
					data.timer = setTimeout(() => {
						onConfirm(obj)
					}, 500)
				}
			};
			onMounted(() => {
				getcalendar(new Date().getFullYear(), new Date().getMonth() + 1);
				let today = calendar.value.find((e) => {
					return e.isToday === 1;
				});
				if (today) {
					activeDay.value = today.day;
				}
				sliceWeek(today);
				data.statusBarHeight = uni.getSystemInfoSync().statusBarHeight;
			});
			let that = methods;
			return {
				currentDate,
				getCurrentDate,
				showPopup,
				showdatetime,
				onClose,
				onConfirm,
				calendar,
				activeDay,
				calendarActive,
				weekArr,
				sliceWeekArr,
				sliceWeek,
				isShowAllDay,
				changeCalendar,
				...toRefs(data),
				...methods,
			};
		},
		onShow() {
			this.msg.StartTime = getToday('y', 'm') + '-01';
			this.msg.EndTime = getToday('y', 'm') + '-' + getMonthMaxDay();
			if (this.$isLogin()) {
				this.getAllData()
			}
		},
		onLoad(options) {
			this.initSwiper()
		}
	};
</script>

<style scoped>
	.swiper {
		/* min-height: 400rpx; */
		height: 620rpx;
	}

	.chooseDate {
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #111111;
	}

	.calendar {
		width: 690rpx;
		/* height: 120rpx; */
		background-color: #f5f6f7;
		border-radius: 20rpx;
		margin: 0 auto;
		/* overflow-x: auto; */
		margin-bottom: 38rpx;
	}

	.calendar-week-item {
		width: 98.5rpx;
		height: 60rpx;
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #111111;
		text-align: center;
	}

	.calendar-item {
		width: 98.5rpx;
		height: 80rpx;
		text-align: center;
		position: relative;
	}

	.calendar-week {
		height: 60rpx;
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 500;
		line-height: 58rpx;
		color: #999999;
	}

	.calendar-day {
		/* height: 50rpx; */
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 500;
		line-height: 48rpx;
		color: #111111;

	}

	.isToday {
		font-size: 18rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #999999;
	}

	.calendar-active {
		width: 50rpx;
		height: 50rpx;
		background-color: rgba(0, 0, 255, 0.9) !important;
		border-radius: 50%;
		color: #FFFFFF !important;
	}

	.calendar-leave {
		width: 50rpx;
		height: 50rpx;
		background-color: #E6A23C;
		border-radius: 50%;
	}

	.calendar-leave2 {
		width: 50rpx;
		height: 50rpx;
		background-color: #F56C6C;
		border-radius: 50%;
	}

	.calendar .openorclose {
		margin-bottom: 17rpx;
		width: 100%;
	}

	.Timetable-box {
		box-sizing: border-box;
		/* 	padding-left: 30rpx;
		text-align: center; */
	}

	/deep/.navTitle {
		font-size: 32rpx;
		font-family: PingFang SC;
		font-weight: 800;
		color: #111111;
	}

	/deep/.van-divider {
		margin: 0 auto;
	}

	.haveCourse {
		width: 10rpx;
		height: 10rpx;
		border-radius: 50%;
		background-color: #FF0000;
		position: absolute;
		top: 10rpx;
		right: 10rpx;
	}

	.btnfixed {
		position: fixed;
		right: 20rpx;
		bottom: 92rpx;
		z-index: 9999;
	}

	.btnfixed image {
		width: 65px;
		height: auto;
	}
</style>
