<template>
	<view>
		<view class="date-trigger" @tap="open">
			<slot>
				<view class="date-trigger__default">
					<view class="date-trigger__item">
						<text class="date-trigger__label">入住</text>
						<text class="date-trigger__value">{{ checkInText || '请选择' }}</text>
					</view>
					<view class="date-trigger__divider"></view>
					<view class="date-trigger__item">
						<text class="date-trigger__label">离店</text>
						<text class="date-trigger__value">{{ checkOutText || '请选择' }}</text>
					</view>
					<text class="date-trigger__arrow">▾</text>
				</view>
			</slot>
		</view>

		<view v-if="visible" class="date-overlay">
			<view class="date-overlay__mask" @tap="close" />
			<view class="date-sheet" :style="{ paddingBottom: bottomGap + 'px' }" @tap.stop>
				<view class="date-sheet__header">
					<view class="date-sheet__title-bar">
						<text class="date-sheet__title">{{ title }}</text>
						<text class="date-sheet__close" @tap="close">×</text>
					</view>
					<view class="date-sheet__summary">
						<text v-if="checkInDate" class="date-sheet__summary-text">
							入住: {{ checkInText }}
						</text>
						<text v-if="checkOutDate" class="date-sheet__summary-text">
							离店: {{ checkOutText }}
						</text>
						<text v-if="checkInDate && checkOutDate" class="date-sheet__nights">
							共 {{ nights }} 晚
						</text>
					</view>
				</view>

				<view class="date-sheet__content">
					<view class="date-calendar">
						<view class="date-calendar__header">
							<view class="date-calendar__nav" @tap="prevMonth">
								<text class="date-calendar__nav-btn">‹</text>
							</view>
							<text class="date-calendar__month">{{ currentYear }}年{{ currentMonth }}月</text>
							<view class="date-calendar__nav" @tap="nextMonth">
								<text class="date-calendar__nav-btn">›</text>
							</view>
						</view>

						<view class="date-calendar__weekdays">
							<text v-for="day in weekDays" :key="day" class="date-calendar__weekday">{{ day }}</text>
						</view>

						<view class="date-calendar__days">
							<view
								v-for="(day, index) in calendarDays"
								:key="index"
								class="date-calendar__day"
								:class="{
									'date-calendar__day--disabled': day.disabled,
									'date-calendar__day--checkin': isCheckIn(day),
									'date-calendar__day--checkout': isCheckOut(day),
									'date-calendar__day--range': isInRange(day),
									'date-calendar__day--today': isToday(day)
								}"
								@tap="selectDay(day)"
							>
								<text class="date-calendar__day-text">{{ day.date }}</text>
							</view>
						</view>
					</view>
				</view>

				<view class="date-sheet__footer">
					<view class="date-sheet__confirm-btn" @tap="confirm">
						<text class="date-sheet__confirm-text">确认选择</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	name: 'DateRangePicker',
	props: {
		checkIn: { type: String, default: '' },
		checkOut: { type: String, default: '' },
		title: { type: String, default: '选择日期' },
		minDate: { type: String, default: '' },
		maxDate: { type: String, default: '' },
		minNights: { type: Number, default: 1 },
		maxNights: { type: Number, default: 30 }
	},
	data() {
		return {
			visible: false,
			bottomGap: 0,
			checkInDate: '',
			checkOutDate: '',
			currentYear: new Date().getFullYear(),
			currentMonth: new Date().getMonth() + 1,
			weekDays: ['日', '一', '二', '三', '四', '五', '六']
		}
	},
	computed: {
		checkInText() {
			return this.checkInDate ? this.formatDate(this.checkInDate) : ''
		},
		checkOutText() {
			return this.checkOutDate ? this.formatDate(this.checkOutDate) : ''
		},
		nights() {
			if (!this.checkInDate || !this.checkOutDate) return 0
			const start = new Date(this.checkInDate)
			const end = new Date(this.checkOutDate)
			return Math.round((end - start) / (1000 * 60 * 60 * 24))
		},
		calendarDays() {
			const days = []
			const firstDay = new Date(this.currentYear, this.currentMonth - 1, 1)
			const lastDay = new Date(this.currentYear, this.currentMonth, 0)
			const startWeekday = firstDay.getDay()
			const totalDays = lastDay.getDate()
			const minDate = this.minDate ? new Date(this.minDate) : new Date()
			const maxDate = this.maxDate ? new Date(this.maxDate) : new Date(this.currentYear, this.currentMonth + 2, 0)

			for (let i = 0; i < startWeekday; i++) {
				days.push({ date: 0, disabled: true, fullDate: '' })
			}

			for (let i = 1; i <= totalDays; i++) {
				const fullDate = `${this.currentYear}-${String(this.currentMonth).padStart(2, '0')}-${String(i).padStart(2, '0')}`
				const currentDate = new Date(fullDate)
				const disabled = currentDate < minDate || currentDate > maxDate
				days.push({
					date: i,
					disabled,
					fullDate,
					timestamp: currentDate.getTime()
				})
			}

			return days
		}
	},
	created() {
		if (this.checkIn) {
			this.checkInDate = this.checkIn
		}
		if (this.checkOut) {
			this.checkOutDate = this.checkOut
		}
	},
	methods: {
		open() {
			this.visible = true
			const sys = uni.getSystemInfoSync()
			const insetBottom = (sys.safeAreaInsets && sys.safeAreaInsets.bottom) || 0
			this.bottomGap = insetBottom
		},
		close() {
			this.visible = false
		},
		prevMonth() {
			if (this.currentMonth === 1) {
				this.currentYear--
				this.currentMonth = 12
			} else {
				this.currentMonth--
			}
		},
		nextMonth() {
			if (this.currentMonth === 12) {
				this.currentYear++
				this.currentMonth = 1
			} else {
				this.currentMonth++
			}
		},
		selectDay(day) {
			if (day.disabled) return

			if (!this.checkInDate || (this.checkInDate && this.checkOutDate)) {
				this.checkInDate = day.fullDate
				this.checkOutDate = ''
			} else {
				const checkIn = new Date(this.checkInDate)
				const selected = new Date(day.fullDate)
				const nights = Math.round((selected - checkIn) / (1000 * 60 * 60 * 24))

				if (nights < this.minNights) {
					uni.showToast({
						title: `至少入住${this.minNights}晚`,
						icon: 'none'
					})
					return
				}

				if (nights > this.maxNights) {
					uni.showToast({
						title: `最多入住${this.maxNights}晚`,
						icon: 'none'
					})
					return
				}

				if (selected < checkIn) {
					this.checkInDate = day.fullDate
					this.checkOutDate = ''
				} else {
					this.checkOutDate = day.fullDate
				}
			}
		},
		isCheckIn(day) {
			return day.fullDate === this.checkInDate
		},
		isCheckOut(day) {
			return day.fullDate === this.checkOutDate
		},
		isInRange(day) {
			if (!this.checkInDate || !this.checkOutDate) return false
			const timestamp = day.timestamp
			const checkIn = new Date(this.checkInDate).getTime()
			const checkOut = new Date(this.checkOutDate).getTime()
			return timestamp > checkIn && timestamp < checkOut
		},
		isToday(day) {
			if (!day.fullDate) return false
			const today = new Date()
			const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
			return day.fullDate === todayStr
		},
		confirm() {
			if (!this.checkInDate) {
				uni.showToast({
					title: '请选择入住日期',
					icon: 'none'
				})
				return
			}
			if (!this.checkOutDate) {
				uni.showToast({
					title: '请选择离店日期',
					icon: 'none'
				})
				return
			}
			this.$emit('confirm', {
				checkIn: this.checkInDate,
				checkOut: this.checkOutDate,
				nights: this.nights
			})
			this.close()
		},
		formatDate(dateStr) {
			if (!dateStr) return ''
			const date = new Date(dateStr)
			const month = date.getMonth() + 1
			const day = date.getDate()
			const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
			const weekDay = weekDays[date.getDay()]
			return `${month}月${day}日 ${weekDay}`
		}
	}
}
</script>

<style lang="scss" scoped>
.date-trigger {
	display: inline-flex;
	align-items: center;
}

.date-trigger__default {
	display: flex;
	align-items: center;
	padding: 12rpx 20rpx;
	background-color: #f5f5f5;
	border-radius: 30rpx;
}

.date-trigger__item {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 0 16rpx;
}

.date-trigger__label {
	font-size: 20rpx;
	color: #999;
	margin-bottom: 4rpx;
}

.date-trigger__value {
	font-size: 26rpx;
	color: #333;
	font-weight: 500;
}

.date-trigger__divider {
	width: 1rpx;
	height: 40rpx;
	background-color: #ddd;
	margin: 0 8rpx;
}

.date-trigger__arrow {
	font-size: 20rpx;
	color: #999;
	margin-left: 8rpx;
}

.date-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 9990;
}

.date-overlay__mask {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
}

.date-sheet {
	position: absolute;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: #fff;
	border-top-left-radius: 24rpx;
	border-top-right-radius: 24rpx;
	max-height: 85vh;
	display: flex;
	flex-direction: column;
}

.date-sheet__header {
	padding: 24rpx 30rpx 20rpx;
	border-bottom: 1rpx solid #eee;
}

.date-sheet__title-bar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16rpx;
}

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

.date-sheet__close {
	font-size: 40rpx;
	color: #999;
	padding: 10rpx;
}

.date-sheet__summary {
	display: flex;
	align-items: center;
	gap: 20rpx;
	flex-wrap: wrap;
}

.date-sheet__summary-text {
	font-size: 26rpx;
	color: #666;
}

.date-sheet__nights {
	font-size: 26rpx;
	color: #007aff;
	font-weight: 500;
}

.date-sheet__content {
	flex: 1;
	overflow-y: auto;
	padding: 20rpx 0;
}

.date-calendar {
	padding: 0 30rpx;
}

.date-calendar__header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.date-calendar__nav-btn {
	font-size: 40rpx;
	color: #333;
	padding: 10rpx 20rpx;
}

.date-calendar__month {
	font-size: 30rpx;
	font-weight: 600;
	color: #333;
}

.date-calendar__weekdays {
	display: flex;
	justify-content: space-around;
	margin-bottom: 16rpx;
}

.date-calendar__weekday {
	flex: 1;
	text-align: center;
	font-size: 24rpx;
	color: #999;
	padding: 10rpx 0;
}

.date-calendar__days {
	display: flex;
	flex-wrap: wrap;
}

.date-calendar__day {
	width: 14.28%;
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 16rpx 0;
}

.date-calendar__day-text {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 28rpx;
	color: #333;
	border-radius: 50%;
}

.date-calendar__day--disabled {
	opacity: 0.3;
}

.date-calendar__day--disabled .date-calendar__day-text {
	color: #ccc;
}

.date-calendar__day--today .date-calendar__day-text {
	border: 2rpx solid #007aff;
}

.date-calendar__day--checkin .date-calendar__day-text,
.date-calendar__day--checkout .date-calendar__day-text {
	background-color: #007aff;
	color: #fff;
}

.date-calendar__day--range .date-calendar__day-text {
	background-color: #e6f2ff;
	color: #007aff;
}

.date-sheet__footer {
	padding: 20rpx 30rpx;
	padding-bottom: 40rpx;
	border-top: 1rpx solid #eee;
}

.date-sheet__confirm-btn {
	background-color: #007aff;
	border-radius: 40rpx;
	padding: 24rpx 0;
	text-align: center;
}

.date-sheet__confirm-text {
	font-size: 30rpx;
	color: #fff;
	font-weight: 500;
}
</style>