<template>
	<view class="page">
		<!-- 固定头部 -->
		<view class="header">
			<view class="center" style="width: 50rpx; height: 50rpx; margin-left: 32rpx;">
				<image src="/static/ic_back.png" @click="back" style="width: 48rpx; height: 48rpx;" mode=""></image>
			</view>
			<text style="font-size: 30rpx;">{{ $t('infoEntry.title') }}</text>
			<view style="width: 50rpx;margin-right: 32rpx;"></view>
		</view>

		<!-- 可滚动内容区域 -->
		<view class="scroll-content">
			<view class="content">
				<!-- 预约登记规则区域 -->
				<view class="booking-rules-box" v-if="bookingRules">
					<view class="rules-title">预约登记规则</view>
					<view class="rules-content">{{ bookingRules }}</view>
				</view>

				<view class="" style="width: 100%; font-size: 40rpx; padding-left: 54rpx; margin-top: 38rpx;">
					{{ $t('infoEntry.personalInfo') }}
				</view>

				<!-- 真实姓名 -->
				<view class="column" :class="{ 'flash-animation': flashingField === 'userName' }"
					style="width: 680rpx; margin-top: 38rpx;" id="fieldUserName">
					<text style="font-size: 30rpx;"><text
							style="color: #FF0000;">*</text>{{ $t('infoEntry.realName') }}</text>
					<up-input :placeholder="$t('infoEntry.realNamePlaceholder')" border="surround"
						v-model="userName"></up-input>
				</view>
				<view class="" style="width: 680rpx; height: 2rpx; background-color: #EAEAEA;"></view>

				<!-- 微信号 -->
				<view class="column" :class="{ 'flash-animation': flashingField === 'contact' }"
					style="width: 680rpx; margin-top: 14rpx;" id="fieldContact">
					<text style="font-size: 30rpx;"><text style="color: #FF0000;">*</text>{{ $t('infoEntry.wechat') }}
						({{ $t('infoEntry.contactMethod') }})</text>
					<up-input :placeholder="$t('infoEntry.wechatPlaceholder')" border="surround"
						v-model="userWechat"></up-input>
				</view>
				<view class="" style="width: 680rpx; height: 2rpx; background-color: #EAEAEA;"></view>

				<!-- 手机号 -->
				<view class="column" :class="{ 'flash-animation': flashingField === 'contact' }"
					style="width: 680rpx; margin-top: 14rpx;">
					<text style="font-size: 30rpx;"><text style="color: #FF0000;">*</text>{{ $t('infoEntry.phone') }}
						({{ $t('infoEntry.contactMethod') }})</text>
					<view class="row" style="margin-top: 10rpx; margin-bottom: 10rpx;">
						<aure-country-picker v-model="selectedDialCode" :title="$t('infoEntry.selectCountry')"
							:height="'70%'" :width="'60vw'" :duration="350" :position="'bottom'" :round="true"
							:radius="'24rpx'" :mask-closable="true"></aure-country-picker>
						<up-input :placeholder="$t('infoEntry.phonePlaceholder')" border="surround"
							v-model="userPhone"></up-input>
					</view>
				</view>
				<view class="" style="width: 680rpx; height: 2rpx; background-color: #EAEAEA;"></view>

				<!-- whatsApp -->
				<view class="column" :class="{ 'flash-animation': flashingField === 'contact' }"
					style="width: 680rpx; margin-top: 14rpx;">
					<text style="font-size: 30rpx;"><text style="color: #FF0000;">*</text>{{ $t('infoEntry.whatsapp') }}
						({{ $t('infoEntry.contactMethod') }})</text>
					<up-input :placeholder="$t('infoEntry.whatsappPlaceholder')" border="surround"
						v-model="userWhats"></up-input>
				</view>
				<view class="" style="width: 680rpx; height: 2rpx; background-color: #EAEAEA;"></view>

				<!-- 备注 -->
				<view class="column" style="width: 680rpx; margin-top: 14rpx;">
					<text style="font-size: 30rpx;">{{ $t('infoEntry.remark') }}</text>
					<up-input :placeholder="$t('infoEntry.remarkPlaceholder')" border="surround"
						v-model="remark"></up-input>
				</view>
				<view class="" style="width: 680rpx; height: 2rpx; background-color: #EAEAEA;"></view>

				<!-- 服务预约信息 -->
				<view class="" style="width: 100%; font-size: 40rpx; padding-left: 54rpx; margin-top: 38rpx;">
					{{ $t('infoEntry.serviceInfo') }}
				</view>

				<!-- 入住日期 -->
				<view class="column" :class="{ 'flash-animation': flashingField === 'checkInDate' }"
					style="width: 680rpx; margin-top: 14rpx;" id="fieldCheckInDate">
					<text style="font-size: 30rpx;"><text style="color: #FF0000;">*</text>入住日期</text>
					<view class="date-item" @click="openCheckInCalendar">
						<text class="date-text" :class="{ 'date-placeholder': !checkInDate }">
							{{ checkInDate || '请选择入住日期' }}
						</text>
						<image src="/static/arrow_right2.png" style="width: 32rpx; height: 32rpx;" mode="aspectFit">
						</image>
					</view>
				</view>
				<view class="" style="width: 680rpx; height: 2rpx; background-color: #EAEAEA;"></view>

				<!-- 退房日期 -->
				<view class="column" :class="{ 'flash-animation': flashingField === 'checkOutDate' }"
					style="width: 680rpx; margin-top: 14rpx;" id="fieldCheckOutDate">
					<text style="font-size: 30rpx;"><text style="color: #FF0000;">*</text>退房日期</text>
					<view class="date-item" @click="openCheckOutCalendar">
						<text class="date-text" :class="{ 'date-placeholder': !checkOutDate }">
							{{ checkOutDate || '请选择退房日期' }}
						</text>
						<image src="/static/arrow_right2.png" style="width: 32rpx; height: 32rpx;" mode="aspectFit">
						</image>
					</view>
				</view>
				<view class="" style="width: 680rpx; height: 2rpx; background-color: #EAEAEA;"></view>

				<!-- 国家/城市 -->
				<view class="column" :class="{ 'flash-animation': flashingField === 'countryCity' }"
					style="width: 680rpx; margin-top: 14rpx;" id="fieldCountryCity">
					<text style="font-size: 30rpx;"><text style="color: #FF0000;">*</text>国家/城市</text>
					<up-input placeholder="请输入国家/城市" border="surround" v-model="countryCity"></up-input>
				</view>
				<view class="" style="width: 680rpx; height: 2rpx; background-color: #EAEAEA;"></view>

				<!-- 酒店名称 -->
				<view class="column" :class="{ 'flash-animation': flashingField === 'hotelName' }"
					style="width: 680rpx; margin-top: 14rpx;" id="fieldHotelName">
					<text style="font-size: 30rpx;"><text style="color: #FF0000;">*</text>酒店名称</text>
					<up-input placeholder="请输入酒店名称" border="surround" v-model="hotelName"></up-input>
				</view>
				<view class="" style="width: 680rpx; height: 2rpx; background-color: #EAEAEA;"></view>

				<!-- 房间数量 -->
				<view class="column" :class="{ 'flash-animation': flashingField === 'roomCount' }"
					style="width: 680rpx; margin-top: 14rpx;" id="fieldRoomCount">
					<text style="font-size: 30rpx;"><text style="color: #FF0000;">*</text>房间数量</text>
					<view class="person-row">
						<view class="person-info">
							<text class="person-title">房间</text>
						</view>
						<view class="person-counter">
							<view class="counter-btn" @click="decreaseRoomCount">
								<text class="counter-icon">－</text>
							</view>
							<text class="counter-value">{{ roomCount }}间</text>
							<view class="counter-btn" @click="increaseRoomCount">
								<text class="counter-icon">＋</text>
							</view>
						</view>
					</view>
				</view>
				<view class="" style="width: 680rpx; height: 2rpx; background-color: #EAEAEA;"></view>

				<!-- 房型 -->
				<view class="column" :class="{ 'flash-animation': flashingField === 'roomType' }"
					style="width: 680rpx; margin-top: 14rpx;" id="fieldRoomType">
					<text style="font-size: 30rpx;"><text style="color: #FF0000;">*</text>房型</text>
					<view class="date-item" @click="showRoomTypePicker = true">
						<text class="date-text">{{ roomTypeText }}</text>
						<image src="/static/arrow_down.png" style="width: 32rpx; height: 32rpx;" mode="aspectFit">
						</image>
					</view>
				</view>
				<view class="" style="width: 680rpx; height: 2rpx; background-color: #EAEAEA;"></view>

				<!-- 是否需要用餐 -->
				<view class="column" style="width: 680rpx; margin-top: 14rpx;" id="fieldNeedMeal">
					<text style="font-size: 30rpx;">是否需要用餐</text>
					<view class="date-item" @click="showMealRequirementPicker = true">
						<text class="date-text">{{ needMealText }}</text>
						<image src="/static/arrow_down.png" style="width: 32rpx; height: 32rpx;" mode="aspectFit">
						</image>
					</view>
				</view>
				<view class="" style="width: 680rpx; height: 2rpx; background-color: #EAEAEA;"></view>

				<!-- 用餐方案 (仅当需要用餐时显示) -->
				<view v-if="needMeal" class="column" :class="{ 'flash-animation': flashingField === 'mealPlan' }"
					style="width: 680rpx; margin-top: 14rpx;" id="fieldMealPlan">
					<text style="font-size: 30rpx;"><text style="color: #FF0000;">*</text>用餐方案</text>
					<view class="date-item" @click="showMealPlanPicker = true">
						<text class="date-text">{{ mealPlanText }}</text>
						<image src="/static/arrow_down.png" style="width: 32rpx; height: 32rpx;" mode="aspectFit">
						</image>
					</view>
				</view>
				<view v-if="needMeal" class="" style="width: 680rpx; height: 2rpx; background-color: #EAEAEA;"></view>

				<view class="center" @click="checkData()"
					style="width: 642rpx; height: 72rpx; background-color: #57C9DD; border-radius: 16rpx; box-shadow: 0 0 10rpx 10rpx rgba(0, 0, 0, 0.1); margin-top: 50rpx; margin-bottom: 100rpx;">
					{{ $t('common.submit') }}
				</view>
			</view>
		</view>
		<!-- 房型选择器 -->
		<up-picker :show="showRoomTypePicker" :columns="roomTypeColumns" @confirm="onRoomTypeConfirm"
			@cancel="showRoomTypePicker = false" @close="showRoomTypePicker = false" :defaultIndex="[roomTypeIndex]"
			keyName="label">
		</up-picker>
		<!-- 是否需要用餐选择器 -->
		<up-picker :show="showMealRequirementPicker" :columns="mealRequirementColumns" @confirm="onMealRequirementConfirm"
			@cancel="showMealRequirementPicker = false" @close="showMealRequirementPicker = false" :defaultIndex="[needMeal ? 0 : 1]"
			keyName="label">
		</up-picker>
		<!-- 用餐方案选择器 -->
		<up-picker :show="showMealPlanPicker" :columns="mealPlanColumns" @confirm="onMealPlanConfirm"
			@cancel="showMealPlanPicker = false" @close="showMealPlanPicker = false" :defaultIndex="[mealPlanIndex]"
			keyName="label">
		</up-picker>
		<!-- 日历选择器 -->
		<up-calendar :show="showCalendar" mode="single" :minDate="minDate" :maxDate="maxDate"
			@confirm="onCalendarConfirm" @close="closeCalendar" :confirmText="$t('common.confirm')" color="#57C9DD">
		</up-calendar>
	</view>
</template>


<script>
	import { AppServer } from '@/modules/api/AppServer.js'
	import bookingRulesMixin from '@/mixins/bookingRulesMixin.js'
	const appServer = new AppServer()
	
	export default {
		mixins: [bookingRulesMixin],
		data() {
			return {
				serviceId: "",
				hotServiceId: "",
				source: "",
				serviceTitle: "",
				userName: "",
				userWechat: "",
				userPhone: "",
				userWhats: "",
				remark: "",
				checkInDate: "",
				checkOutDate: "",
				countryCity: "",
				hotelName: "",
				roomCount: 1,
				roomType: "standard",
				roomTypeIndex: 0,
				needMeal: false,
				mealPlan: "breakfast",
				mealPlanIndex: 0,
				submitting: false,
				flashingField: '',
				selectedDialCode: '86',
				showCalendar: false,
				calendarType: "checkIn",
				showRoomTypePicker: false,
				showMealRequirementPicker: false,
				showMealPlanPicker: false,
				minDate: '',
				maxDate: '',
				roomTypeColumns: [
					[{
							label: '标准间',
							value: 'standard'
						},
						{
							label: '大床房',
							value: 'king'
						},
						{
							label: '双床房',
							value: 'twin'
						},
						{
							label: '套房',
							value: 'suite'
						},
						{
							label: '家庭房',
							value: 'family'
						}
					]
				],
				mealRequirementColumns: [
					[{
							label: '是',
							value: true
						},
						{
							label: '否',
							value: false
						}
					]
				],
				mealPlanColumns: [
					[{
							label: '早餐',
							value: 'breakfast'
						},
						{
							label: '三餐',
							value: 'three_meals'
						},
						{
							label: '全包',
							value: 'all_inclusive'
						}
					]
				]
			}
		},
		computed: {
			roomTypeText() {
				const item = this.roomTypeColumns[0].find(t => t.value === this.roomType)
				return item ? item.label : '标准间'
			},
			needMealText() {
				return this.needMeal ? '是' : '否'
			},
			mealPlanText() {
				const item = this.mealPlanColumns[0].find(t => t.value === this.mealPlan)
				return item ? item.label : '早餐'
			}
		},
		onLoad(options) {
			this.initDateRange()
			if (options.id) {
				this.source = options.source || ''
				if (this.source === 'hot') {
					this.hotServiceId = options.id
				} else {
					this.serviceId = options.id
				}
			}
			if (options.title) {
				this.serviceTitle = decodeURIComponent(options.title)
			}
			// 加载预约规则
			this.loadBookingRules('hotel')
		},
		methods: {
			initDateRange() {
				const now = new Date()
				const year = now.getFullYear()
				const month = String(now.getMonth() + 1).padStart(2, '0')
				const day = String(now.getDate()).padStart(2, '0')
				this.minDate = `${year}-${month}-${day}`
				this.maxDate = `${year + 2}-12-31`
			},
			openCheckInCalendar() {
				this.calendarType = 'checkIn'
				this.initDateRange()
				this.$nextTick(() => {
					this.showCalendar = true
				})
			},
			openCheckOutCalendar() {
				this.calendarType = 'checkOut'
				// 退房日期最小值为入住日期
				if (this.checkInDate) {
					this.minDate = this.checkInDate
				} else {
					this.initDateRange()
				}
				this.$nextTick(() => {
					this.showCalendar = true
				})
			},
			closeCalendar() {
				this.showCalendar = false
				this.initDateRange()
			},
			onCalendarConfirm(dates) {
				if (dates && dates.length > 0) {
					if (this.calendarType === 'checkIn') {
						this.checkInDate = dates[0]
						// 如果退房日期早于入住日期，清空退房日期
						if (this.checkOutDate && this.checkOutDate < dates[0]) {
							this.checkOutDate = ''
						}
					} else {
						this.checkOutDate = dates[0]
					}
				}
				this.showCalendar = false
				this.initDateRange()
			},
			onRoomTypeConfirm(e) {
				const selected = e.value[0]
				this.roomType = selected.value
				this.roomTypeIndex = this.roomTypeColumns[0].findIndex(t => t.value === selected.value)
				this.showRoomTypePicker = false
			},
			onMealRequirementConfirm(e) {
				const selected = e.value[0]
				this.needMeal = selected.value
				this.showMealRequirementPicker = false
			},
			onMealPlanConfirm(e) {
				const selected = e.value[0]
				this.mealPlan = selected.value
				this.mealPlanIndex = this.mealPlanColumns[0].findIndex(t => t.value === selected.value)
				this.showMealPlanPicker = false
			},
			increaseRoomCount() {
				this.roomCount++
			},
			decreaseRoomCount() {
				if (this.roomCount > 1) {
					this.roomCount--
				}
			},
			checkData() {
				const validations = [{
						field: 'userName',
						selector: '#fieldUserName',
						check: () => !this.userName.trim(),
						message: '请输入真实姓名'
					},
					{
						field: 'contact',
						selector: '#fieldContact',
						check: () => !this.userWechat.trim() && !this.userPhone.trim() && !this.userWhats.trim(),
						message: '请至少填写一种联系方式（微信号/手机号/WhatsApp）'
					},
					{
						field: 'checkInDate',
						selector: '#fieldCheckInDate',
						check: () => !this.checkInDate,
						message: '请选择入住日期'
					},
					{
						field: 'checkOutDate',
						selector: '#fieldCheckOutDate',
						check: () => !this.checkOutDate,
						message: '请选择退房日期'
					},
					{
						field: 'checkOutDate',
						selector: '#fieldCheckOutDate',
						check: () => this.checkInDate && this.checkOutDate && this.checkOutDate < this.checkInDate,
						message: '退房日期不能早于入住日期'
					},
					{
						field: 'countryCity',
						selector: '#fieldCountryCity',
						check: () => !this.countryCity.trim(),
						message: '请输入国家/城市'
					},
					{
						field: 'hotelName',
						selector: '#fieldHotelName',
						check: () => !this.hotelName.trim(),
						message: '请输入酒店名称'
					},
					{
						field: 'roomCount',
						selector: '#fieldRoomCount',
						check: () => this.roomCount < 1,
						message: '房间数量至少为1'
					},
					{
						field: 'mealPlan',
						selector: '#fieldMealPlan',
						check: () => this.needMeal && !this.mealPlan,
						message: '请选择用餐方案'
					}
				]

				for (const validation of validations) {
					if (validation.check()) {
						uni.showToast({
							title: validation.message,
							icon: 'none'
						})
						this.scrollToElement(validation.selector)
						this.flashingField = validation.field
						setTimeout(() => {
							this.flashingField = ''
						}, 1500)
						return
					}
				}

				this.submitAppointment()
			},
			async submitAppointment() {
				if (this.submitting) return
				this.submitting = true
				
				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				
				try {
					const appointmentData = {
						serviceId: this.serviceId || null,
						hotServiceId: this.hotServiceId ? parseInt(this.hotServiceId) : null,
						serviceType: 'hotel',
						realName: this.userName.trim(),
						wechatId: this.userWechat.trim() || null,
						phone: this.userPhone.trim() || null,
						phoneCountryCode: this.userPhone.trim() ? this.selectedDialCode : null,
						whatsapp: this.userWhats.trim() || null,
						notes: this.remark.trim() || null,
						checkInDate: this.checkInDate,
						checkOutDate: this.checkOutDate,
						countryCity: this.countryCity.trim(),
						hotelName: this.hotelName.trim(),
						roomCount: this.roomCount,
						roomType: this.roomType,
						needMeal: this.needMeal,
						mealPlan: this.needMeal ? this.mealPlan : null,
					}
					
					const result = await appServer.CreateAppointment(appointmentData)
					
					uni.hideLoading()
					
					if (result.success || result.code === 0) {
						uni.showToast({
							title: '预约提交成功',
							icon: 'success'
						})
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							})
						}, 1500)
					} else {
						uni.showToast({
							title: result.error?.message || '提交失败，请重试',
							icon: 'none'
						})
					}
				} catch (error) {
					uni.hideLoading()
					console.error('提交预约失败:', error)
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					})
				} finally {
					this.submitting = false
				}
			},
			scrollToElement(selector) {
				const systemInfo = uni.getSystemInfoSync()
				const screenHeight = systemInfo.windowHeight
				const query = uni.createSelectorQuery().in(this)
				query.select(selector).boundingClientRect()
				query.selectViewport().scrollOffset()
				query.exec((res) => {
					if (res[0] && res[1]) {
						const rect = res[0]
						const scrollInfo = res[1]
						const targetScrollTop = scrollInfo.scrollTop + rect.top - (screenHeight / 2) + (rect.height / 2)
						uni.pageScrollTo({
							scrollTop: Math.max(0, targetScrollTop),
							duration: 300
						})
					}
				})
			},
			back() {
				uni.navigateBack({
					delta: 1
				});
			}
		}
	}
</script>


<style lang="scss">
	.page {
		min-height: 100vh;
		background-color: #F3F3F3;
	}

	.header {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		padding-top: 88rpx;
		padding-bottom: 20rpx;
		background-color: #F3F3F3;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 100;
	}

	.scroll-content {
		padding-top: 140rpx;
		background-color: #F3F3F3;
		min-height: 100vh;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #F3F3F3;
		min-height: 100%;
	}

	.date-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		height: 80rpx;
		padding: 0 10rpx;
		box-sizing: border-box;
	}

	.date-text {
		font-size: 28rpx;
		color: #333;
	}

	.date-placeholder {
		color: #c0c4cc;
	}

	@keyframes flash {
		0% {
			background-color: #F3F3F3;
		}

		50% {
			background-color: #ff6666;
		}

		100% {
			background-color: #F3F3F3;
		}
	}

	.flash-animation {
		animation: flash 0.5s ease-in-out 3;
	}

	.person-row {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		padding: 20rpx 10rpx;
	}

	.person-info {
		display: flex;
		flex-direction: column;
	}

	.person-title {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}

	.person-desc {
		font-size: 24rpx;
		color: #999;
		margin-top: 6rpx;
	}

	.person-counter {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.counter-btn {
		width: 50rpx;
		height: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #BFBFBF;
		border-radius: 8rpx;
	}

	.counter-icon {
		font-size: 28rpx;
		color: #fff;
		font-weight: bold;
		line-height: 50rpx;
		text-align: center;
		color: #FFFFFF;
	}

	.counter-value {
		font-size: 28rpx;
		color: #333;
		min-width: 80rpx;
		text-align: center;
	}

	/* 预约登记规则样式 */
	.booking-rules-box {
		width: 680rpx;
		height: 396rpx;
		margin-top: 32rpx;
		padding: 30rpx;
		background-image: linear-gradient(-45deg, #60D7FF, #68BBD7);
		border-radius: 20rpx;
		box-shadow: 0 0 10rpx 10rpx rgba(0, 0, 0, 0.1);
		box-sizing: border-box;
		overflow-y: auto;
	}

	.rules-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #fff;
		margin-bottom: 20rpx;
	}

	.rules-content {
		font-size: 26rpx;
		color: #fff;
		line-height: 1.6;
		white-space: pre-wrap;
	}
</style>
