<template>
	<view>
		<view class="calendar">
			<view class="calendar_day">
				<view class="day_x" :style="{'color': (day_index == index ? '#FE3B3C' : '')}"
					v-for="(item, index) in dayArr" :key="index" @click.stop="dayList(item,index)">
					<view class="day_x_a">{{item.weeks}}</view>
					<view class="day_x_b">{{item.days}}</view>
				</view>
			</view>
			<view class="calendar_time">
				<view class="time_x" 
				  :class="{
				    'time_x_sty': item?.checked, 
				    'disabled-time': item?.disabled
				  }" 
				  v-for="(item, index) in timeHostArr[day_index]" 
				  :key="index"
				  @click="handleTimeClick(item)">
				  <text>{{item?.hours}}</text>
				  <text v-if="item.hasReservation === 1" class="hasRe-text">已预约</text>
				</view>
			</view>
		</view>
		<!-- <view class="sub" @click="sub()">
			立即预约
		</view> -->
	</view>
</template>
<script>
	export default {
		props: {
			timeArr: {
				type: Array,
				default: () => []
			},

			timeHostArr: {
				type: Array,
				default: () => []
			},
			businessDuration: {
				type: Number,
				default: 0
			} // 从父组件接收的服务时长（分钟）
		},
		data() {
			return {
				dayArr: [],
				day_index: 0,
				host_index: '',
				nowTimes: new Date().getTime(), // 只保留一个定义
				disableAfterTime: null,
				selectedTime: null,
				selectedDay: null, // 新增：记录选择的日期
				selectedTimeSlots: {}, // 存储每个日期的选择状态
			}
		},
		watch: {
			timeArr: {
				handler(newVal) {
					let dateArr = newVal.map(item => {
						let day = new Date(item)
						const daysOfWeek = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
						return {
							weeks: daysOfWeek[day.getDay()],
							days: item.slice(5)
						}
					})
					this.dayArr = dateArr
				},
				immediate: true
			},
			timeHostArr: {
				handler(newVal) {
					// 当timeHostArr更新时，恢复之前的选择状态
					if (newVal && newVal.length > 0) {
						this.restoreSelections();
					}
				},
				deep: true
			}
		},
		mounted() {
		},
		methods: {
			// 恢复选择状态
			restoreSelections() {
				if (!this.timeHostArr[this.day_index]) return;
				
				// 遍历当前日期的时间槽
				this.timeHostArr[this.day_index].forEach(slot => {
					// 检查这个时间槽是否在之前被选中
					const dateKey = this.timeArr[this.day_index];
					if (this.selectedTimeSlots[dateKey] && 
						this.selectedTimeSlots[dateKey].includes(slot.timeStamp)) {
						slot.checked = true;
						
						// 计算并禁用后续的时间段
						const seconds = this.businessDuration * 60;
						const endTimestamp = slot.timeStamp + seconds;
						
						// 禁用后续的时间段
						this.timeHostArr[this.day_index].forEach(s => {
							if (s.timeStamp > slot.timeStamp && 
								s.timeStamp <= endTimestamp) {
								s.disabled = true;
							}
						});
					}
				});
			},
			
			handleTimeClick(item) {
				console.log(this.businessDuration, '>>>>>>businessDuration');
				// 禁用点击，取消点击触发
				if (item.disabled) return false
				
				// 计算服务时间秒
				const seconds = this.businessDuration * 60
				// 计算最终服务时间
				const endTimestamp = (item.timeStamp + seconds)
				
				// 禁用区域/释放区域数据
				const filteredSlots = this.timeHostArr[this.day_index].filter(i => {
				   return (i.timeStamp > item.timeStamp && 
				          i.timeStamp <= endTimestamp)
				 })
				 
				console.log(filteredSlots, '>>>>>filteredSlots');
				
				// 当前日期
				const currentDate = this.timeArr[this.day_index];
				
				if (!item.checked) {
					// 计算禁用时间区域
					filteredSlots.forEach(v => {
						v.disabled = true
					})
					item.checked = true
					
					// 保存选择状态
					if (!this.selectedTimeSlots[currentDate]) {
						this.selectedTimeSlots[currentDate] = [];
					}
					this.selectedTimeSlots[currentDate].push(item.timeStamp);
				} else {
					// 释放禁用区域
					filteredSlots.forEach(v => {
						if (v.hasReservation !== 1) v.disabled = false
					})
					item.checked = false
					
					// 移除选择状态
					if (this.selectedTimeSlots[currentDate]) {
						const index = this.selectedTimeSlots[currentDate].indexOf(item.timeStamp);
						if (index > -1) {
							this.selectedTimeSlots[currentDate].splice(index, 1);
						}
					}
				}
				
				this.hosts(item);
			},
			// 点击日期
			dayList(e, index) {
				this.day_index = index
				this.$emit('getByDate', this.timeArr[index])
			},
			// 转换时间戳为毫秒
			ensureMillisecond(timestamp) {
				return timestamp > 9999999999 ? timestamp : timestamp * 1000;
			},

			shouldDisable(item) {
				if (!item) return true;
				
				// 已预约
				if (item.hasReservation === 1) return true;

				const itemTime = this.ensureMillisecond(item.timeStamp);

				// 过去时间
				if (this.nowTimes > itemTime) return true;

				return false;
			},
			hosts(item) {
				const itemTime = this.ensureMillisecond(item.timeStamp);

				this.host_index = item.timeStamp; // 显示用原始值
				this.selectedTime = itemTime;
				this.disableAfterTime = itemTime + (this.businessDuration * 60 * 1000);
				this.$emit('getByTime', {
					...item,
					timeStamp: itemTime // 传递转换后的值
				});
			},

			// 点击立即预约
			sub() {
				if (this.host_index == '') {
					this.$tool.toast('请选择时间');
				} else {
					let day = this.dayArr[this.day_index];
					let time = this.times(this.host_index);
					let comTime = {
						days: day.days,
						weeks: day.weeks,
						hours: this.host_All.hours,
						timeStamp: this.host_All.timeStamp,
						time: time
					};
					this.$emit('getTime', comTime);
				}
			},

			// 格式化时间
			times(data) {
				let date = new Date(data * 1000);
				let h = date.getHours();
				h = h < 10 ? ('0' + h) : h; // 小时补0
				let m = date.getMinutes();
				m = m < 10 ? ('0' + m) : m; // 分钟补0
				return h + ':' + m;
			},
			time(data, type) {
				let date = new Date(data * 1000);
				let y = date.getFullYear();
				let MM = date.getMonth() + 1;
				MM = MM < 10 ? ('0' + MM) : MM; // 月补0
				let d = date.getDate();
				d = d < 10 ? ('0' + d) : d; // 天补0
				let h = date.getHours();
				h = h < 10 ? ('0' + h) : h; // 小时补0
				let m = date.getMinutes();
				m = m < 10 ? ('0' + m) : m; // 分钟补0
				let s = date.getSeconds();
				s = s < 10 ? ('0' + s) : s; // 秒补0
				if (type == 'yymmdd') {
					return y + '-' + MM + '-' + d;
				} else if (type == 'hhmmss') {
					return h + ':' + m + ':' + s;
				} else {
					return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F4F4F4;
	}

	.calendar {
		width: 710rpx;
		height: 460rpx;
		background-color: #FFFFFF;
		margin: 20rpx auto 10rpx;
		border-radius: 8rpx;
	}

	.calendar_day {
		display: flex;
		width: 100%;
		height: 120rpx;

		.day_x {
			display: flex;
			flex-flow: column nowrap;
			justify-content: center;
			align-items: center;
			width: 20%;
			height: 100%;
			font-size: 30rpx;
			color: #333333;
		}
	}

	.calendar_time {
		display: flex;
		width: 100%;
		height: 448rpx;
		flex-flow: row wrap;
		align-content: flex-start;
		margin: 20rpx 0;
		overflow-y: auto;

		.time_x {
			display: flex;
			flex-flow: row;
			justify-content: center;
			align-items: center;
			width: 20%;
			height: 54rpx;
			border-radius: 26rpx;
			margin: 10rpx 0;
			font-size: 30rpx;
			color: #333333;

			display: flex;
			flex-direction: column;

			.hasRe-text {
				font-size: 20rpx;
				color: #999999;
			}
		}

		.time_x_sty {
			background-color: #FFE97B;
			color: #000000 !important;
		}
	}

	.sub {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 710rpx;
		height: 100rpx;
		border-radius: 50rpx;
		margin: 30rpx auto;
		color: #FFFFFF;
		font-size: 36rpx;
		background-color: #FE3B3C;
	}



	.time_x {
	  /* 正常状态样式 */
	  &.disabled-time {
	    background-color: #f2f2f2;
	    color: #999999;
	    pointer-events: none;
	  }
	  
	  &.time_x_sty {
	    background-color: #FFE97B;
	    color: #000000;
	  }
	}
</style>