<template>
	<view class="appointment-container">
		<view class="form-card">
			<view class="form-content">
				<form @submit="handleFormSubmit">
					<view class="form-group">
						<text class="form-label">预约体验项目</text>
						<view class="custom-select" @click="handleSelectClick('yytyxm')" @tap="handleSelectClick('yytyxm')">
							<text class="select-text">{{ formData.yytyxm || '请选择体验项目' }}</text>
							<text class="select-arrow">▼</text>
						</view>
					</view>
					
					<view class="form-group">
						<text class="form-label">顾客姓名</text>
						<view class="custom-select" @click="handleSelectClick('gkxm')" @tap="handleSelectClick('gkxm')">
							<text class="select-text">{{ formData.gkxm || '请选择顾客姓名' }}</text>
							<text class="select-arrow">▼</text>
						</view>
					</view>
					
					<view class="form-group">
						<text class="form-label">预约健康师</text>
						<view class="custom-select" @click="handleSelectClick('yyjks')" @tap="handleSelectClick('yyjks')">
							<text class="select-text">{{ formData.yyjks || '请选择健康师' }}</text>
							<text class="select-arrow">▼</text>
						</view>
					</view>
					
					<view class="form-group">
						<text class="form-label">预约日期</text>
						<view class="custom-select" @click="handleSelectClick('yyrq')" @tap="handleSelectClick('yyrq')">
							<text class="select-text">{{ formData.yyrq || '请选择预约日期' }}</text>
							<text class="select-arrow">▼</text>
						</view>
					</view>
					
					<view class="form-group">
						<text class="form-label">预约时间</text>
						<view class="custom-select" @click="handleSelectClick('yysj')" @tap="handleSelectClick('yysj')">
							<text class="select-text">{{ formData.yysj || '请选择预约时间' }}</text>
							<text class="select-arrow">▼</text>
						</view>
					</view>
					
					<view class="btn-group">
						<button 
							type="default" 
							size="normal"
							@click="cancelAppointment"
							class="btn btn-secondary"
						>
							取消预约
						</button>
						<button 
							type="primary" 
							size="normal"
							@click="submitAppointment"
							class="btn btn-primary"
						>
							保存
						</button>
					</view>
				</form>
			</view>
		</view>
		
		<!-- 选择弹窗 -->
		<SearchSelectModal
			:show="showModal"
			:title="modalTitle"
			:options="currentOptions"
			:loading="modalLoading"
			:has-more="hasMoreData"
			:search-param="searchParam"
			@confirm="handleModalConfirm"
			@close="closeModal"
			@load-more="handleLoadMore"
			@refresh="handleRefresh"
			@search="handleSearch"
		/>
	</view>
</template>

<script>
	import appointmentApi from '@/apis/modules/appointment.js'
	import SearchSelectModal from '@/components/SearchSelectModal.vue'
	
	export default {
		components: {
			SearchSelectModal
		},
		data() {
			return {
				// 表单数据
				formData: {
					yytyxm: '',
					gkxm: '',
					yyjks: '',
					yyrq: '',
					yysj: '',
					gklx: ''
				},
				
				// 弹窗相关
				showModal: false,
				modalTitle: '',
				currentSelectField: '',
				currentOptions: [],
				modalLoading: false,
				hasMoreData: true,
				currentPage: 1,
				pageSize: 20,
				searchKeyword: '',
				searchParam: '',
				
				// 用户信息
				userInfo: null,
				
				// 选中的值
				selectedValues: {
					yytyxm: null,
					gkxm: null,
					gklx: null,
					yyjks: null,
					yyrq: null,
					yysj: null
				}
			}
		},
		onLoad(options) {
			this.initializePage(options);
		},
		methods: {
			// 处理选择器点击
			handleSelectClick(fieldId) {
				this.openSelectModal(fieldId);
			},
			
			// 初始化页面
			async initializePage(options) {
				try {
					// 获取用户信息
					this.userInfo = uni.getStorageSync('userInfo');
					if (!this.userInfo || Object.keys(this.userInfo).length === 0) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/login/login'
							});
						}, 1500);
						return;
					}
					
					// 设置默认日期
					this.setDefaultDate();
					
					// 填充URL参数中的客户信息
					this.fillCustomerInfoFromUrl(options);
				} catch (error) {
					console.error('页面初始化失败:', error);
					uni.showToast({
						title: '页面初始化失败',
						icon: 'none'
					});
				}
			},
			
			// 设置默认日期为今天
			setDefaultDate() {
				const today = new Date();
				const year = today.getFullYear();
				const month = (today.getMonth() + 1).toString().padStart(2, '0');
				const day = today.getDate().toString().padStart(2, '0');
				
				const dateString = `${year}-${month}-${day}`;
				const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				const weekDay = weekDays[today.getDay()];
				
				const label = `${month}月${day}日 ${weekDay} (今天)`;
				
				this.formData.yyrq = label;
				this.selectedValues.yyrq = dateString;
			},
			
			// 填充URL参数中的客户信息
			fillCustomerInfoFromUrl(options) {
				const name = options.name;
				const type = options.type;
				const id = options.id;
				const phone = options.phone;
				
				// 如果有客户信息，填充到客户字段
				if (name && id) {
					this.formData.gkxm = name;
					this.selectedValues.gkxm = id;
					
					// 如果有客户类型信息，也填充
					if (type) {
						this.formData.gklx = type;
						this.selectedValues.gklx = type;
					}
				}
			},
			
			// 打开选择弹窗
			async openSelectModal(fieldId) {
				this.currentSelectField = fieldId;
				this.showModal = true;
				this.modalTitle = '加载中...';
				this.modalLoading = true;
				this.currentPage = 1;
				this.hasMoreData = true;
				this.searchKeyword = '';
				
				// 设置搜索参数
				switch(fieldId) {
					case 'yytyxm':
						this.searchParam = 'xmmc';
						this.modalTitle = '选择体验项目';
						break;
					case 'gkxm':
						this.searchParam = 'khmc';
						this.modalTitle = '选择顾客姓名';
						break;
					case 'yyjks':
						this.searchParam = '';
						this.modalTitle = '选择健康师';
						break;
					case 'yyrq':
						this.searchParam = '';
						this.modalTitle = '选择预约日期';
						break;
					case 'yysj':
						this.searchParam = '';
						this.modalTitle = '选择预约时间';
						break;
				}
				
				try {
					await this.loadOptionsData(fieldId, 1);
				} catch (error) {
					console.error('获取选项数据失败:', error);
					this.modalTitle = '加载失败';
					this.currentOptions = [];
					uni.showToast({
						title: '数据加载失败，请检查网络连接',
						icon: 'none'
					});
				} finally {
					this.modalLoading = false;
				}
			},
			
			// 关闭弹窗
			closeModal() {
				this.showModal = false;
				this.currentSelectField = '';
				this.currentOptions = [];
				this.modalLoading = false;
			},
			
			// 加载选项数据
			async loadOptionsData(fieldId, page = 1, searchKeyword = '') {
				let options = [];
				
				switch(fieldId) {
					case 'yytyxm':
						options = await this.getProjectOptions(page, searchKeyword);
						break;
					case 'gkxm':
						options = await this.getCustomerOptions(page, searchKeyword);
						break;
					case 'yyjks':
						options = await this.getHealthWorkerOptions(page, searchKeyword);
						break;
					case 'yyrq':
						options = this.getDateOptions();
						this.hasMoreData = false; // 日期选项不需要分页
						break;
					case 'yysj':
						options = this.getTimeSlotOptions();
						this.hasMoreData = false; // 时间段选项不需要分页
						break;
				}
				
				if (page === 1) {
					this.currentOptions = options;
				} else {
					this.currentOptions = [...this.currentOptions, ...options];
				}
				
				// 检查是否还有更多数据
				if (options.length < this.pageSize) {
					this.hasMoreData = false;
				}
			},
			
			// 处理弹窗确认选择
			handleModalConfirm(selectedOption) {
				if (this.currentSelectField && selectedOption) {
					this.formData[this.currentSelectField] = selectedOption.label;
					this.selectedValues[this.currentSelectField] = selectedOption.value;
					
					// 如果是选择客户，同时保存客户类型
					if (this.currentSelectField === 'gkxm' && selectedOption.khlx) {
						this.formData.gklx = selectedOption.khlx;
						this.selectedValues.gklx = selectedOption.khlx;
					}
				}
			},
			
			// 处理加载更多
			async handleLoadMore(page) {
				if (this.currentSelectField && this.hasMoreData && !this.modalLoading) {
					this.modalLoading = true;
					try {
						await this.loadOptionsData(this.currentSelectField, page, this.searchKeyword);
					} catch (error) {
						console.error('加载更多数据失败:', error);
						uni.showToast({
							title: '加载失败',
							icon: 'none'
						});
					} finally {
						this.modalLoading = false;
					}
				}
			},
			
			// 处理刷新
			async handleRefresh() {
				if (this.currentSelectField) {
					this.currentPage = 1;
					this.hasMoreData = true;
					this.searchKeyword = '';
					await this.loadOptionsData(this.currentSelectField, 1);
				}
			},
			
			// 处理搜索
			async handleSearch(searchKeyword) {
				if (this.currentSelectField) {
					this.searchKeyword = searchKeyword;
					this.currentPage = 1;
					this.hasMoreData = true;
					this.modalLoading = true;
					
					try {
						await this.loadOptionsData(this.currentSelectField, 1, searchKeyword);
					} catch (error) {
						console.error('搜索失败:', error);
						uni.showToast({
							title: '搜索失败',
							icon: 'none'
						});
					} finally {
						this.modalLoading = false;
					}
				}
			},
			
			
			// 获取体验项目选项
			async getProjectOptions(page = 1, searchKeyword = '') {
				try {
					const params = {
						currentPage: page,
						pageSize: this.pageSize
					};
					
					// 如果有搜索关键词，添加搜索参数
					if (searchKeyword && this.searchParam === 'xmmc') {
						params.xmmc = searchKeyword;
					}
					
					const result = await appointmentApi.getProjectList(params);
					if (result.code === 200 && result.data) {
						return result.data.list.map(item => ({
							value: item.id,
							label: item.xmmc,
							subtitle: item.description || ''
						}));
					}
					return this.getDefaultProjectOptions();
				} catch (error) {
					console.error('获取项目列表出错:', error);
					return this.getDefaultProjectOptions();
				}
			},
			
			// 获取顾客选项
			async getCustomerOptions(page = 1, searchKeyword = '') {
				try {
					const params = {
						currentPage: page,
						pageSize: this.pageSize
					};
					
					// 如果有搜索关键词，添加搜索参数
					if (searchKeyword && this.searchParam === 'khmc') {
						params.keyword = searchKeyword;
					}
					
					const result = await appointmentApi.getCustomerList(params);
					if (result.code === 200 && result.data) {
						return result.data.list.map(item => ({
							value: item.id,
							label: item.khmc,
							subtitle:'客户类型：'+(item.khlxName||'无')+'；手机号：'+(item.sjh||'无')+'；健康师：' +(item.mrsName || '无')+'；门店：'+ (item.gsmdName || '无')+'；',
							khlx: item.khlx,
							khmc: item.khmc
						}));
					}
					return this.getDefaultCustomerOptions();
				} catch (error) {
					console.error('获取顾客列表出错:', error);
					return this.getDefaultCustomerOptions();
				}
			},
			
			// 获取健康师选项
			async getHealthWorkerOptions(page = 1, searchKeyword = '') {
				try {
					const params = {
						mdid: this.userInfo.mdid,
						gw: '健康师',
						currentPage: page,
						pageSize: this.pageSize
					};
					
					// 健康师暂时不支持搜索，保持原有逻辑
					
					const result = await appointmentApi.getHealthWorkerList(params);
					if (result.code === 200 && result.data) {
						return result.data.list.map(item => ({
							value: item.id,
							label: item.realName,
							subtitle: item.department || '健康师'
						}));
					}
					return this.getDefaultHealthWorkerOptions();
				} catch (error) {
					console.error('获取健康师列表出错:', error);
					return this.getDefaultHealthWorkerOptions();
				}
			},
			
			// 生成时间段选项
			getTimeSlotOptions() {
				const timeSlots = [];
				const startHour = 9;
				const endHour = 21;
				
				for (let hour = startHour; hour < endHour; hour++) {
					for (let minute = 0; minute < 60; minute += 30) {
						const timeString = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
						const nextMinute = minute + 30;
						const nextHour = nextMinute >= 60 ? hour + 1 : hour;
						const nextMinuteStr = nextMinute >= 60 ? '00' : nextMinute.toString().padStart(2, '0');
						const nextTimeString = `${nextHour.toString().padStart(2, '0')}:${nextMinuteStr}`;
						
						const timeRange = `${timeString}-${nextTimeString}`;
						
						timeSlots.push({
							value: timeRange,
							label: timeRange
						});
					}
				}
				
				return timeSlots;
			},
			
			// 生成日期选项
			getDateOptions() {
				const dateOptions = [];
				const today = new Date();
				
				for (let i = 0; i < 30; i++) {
					const date = new Date(today);
					date.setDate(today.getDate() + i);
					
					const year = date.getFullYear();
					const month = (date.getMonth() + 1).toString().padStart(2, '0');
					const day = date.getDate().toString().padStart(2, '0');
					
					const dateString = `${year}-${month}-${day}`;
					const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
					const weekDay = weekDays[date.getDay()];
					
					let label = `${month}月${day}日 ${weekDay}`;
					if (i === 0) {
						label += ' (今天)';
					} else if (i === 1) {
						label += ' (明天)';
					}
					
					dateOptions.push({
						value: dateString,
						label: label
					});
				}
				
				return dateOptions;
			},
			
			// 默认项目选项
			getDefaultProjectOptions() {
				return [
					{ value: 'proj001', label: '基础护理', subtitle: '基础皮肤护理服务' },
					{ value: 'proj002', label: '深度清洁', subtitle: '深层清洁毛孔服务' },
					{ value: 'proj003', label: '美白护理', subtitle: '美白亮肤护理服务' },
					{ value: 'proj004', label: '抗衰护理', subtitle: '抗衰老护理服务' },
					{ value: 'proj005', label: '补水保湿', subtitle: '深层补水保湿服务' }
				];
			},
			
			// 默认顾客选项
			getDefaultCustomerOptions() {
				return [
					{ value: 'cust001', label: '张三', subtitle: 'VIP会员', khlx: 'VIP' },
					{ value: 'cust002', label: '李四', subtitle: '普通会员', khlx: '普通' },
					{ value: 'cust003', label: '王五', subtitle: 'VIP会员', khlx: 'VIP' },
					{ value: 'cust004', label: '赵六', subtitle: '普通会员', khlx: '普通' },
					{ value: 'cust005', label: '钱七', subtitle: 'VIP会员', khlx: 'VIP' }
				];
			},
			
			// 默认健康师选项
			getDefaultHealthWorkerOptions() {
				return [
					{ value: 'jks001', label: '张健康师', subtitle: '美容科' },
					{ value: 'jks002', label: '李健康师', subtitle: '护理科' },
					{ value: 'jks003', label: '王健康师', subtitle: '美容科' },
					{ value: 'jks004', label: '赵健康师', subtitle: '护理科' },
					{ value: 'jks005', label: '钱健康师', subtitle: '美容科' }
				];
			},
			
			// 处理表单提交
			handleFormSubmit(event) {
				event.preventDefault();
				this.submitAppointment();
			},
			
			// 提交预约
			async submitAppointment() {
				// 验证表单
				if (!this.selectedValues.yytyxm) {
					uni.showToast({
						title: '请选择体验项目',
						icon: 'none'
					});
					return;
				}
				if (!this.selectedValues.gkxm) {
					uni.showToast({
						title: '请选择顾客姓名',
						icon: 'none'
					});
					return;
				}
				if (!this.selectedValues.yyjks) {
					uni.showToast({
						title: '请选择健康师',
						icon: 'none'
					});
					return;
				}
				if (!this.selectedValues.yyrq) {
					uni.showToast({
						title: '请选择预约日期',
						icon: 'none'
					});
					return;
				}
				if (!this.selectedValues.yysj) {
					uni.showToast({
						title: '请选择预约时间',
						icon: 'none'
					});
					return;
				}
				
				try {
					// 收集表单数据
					const selectedDate = this.selectedValues.yyrq;
					const selectedTimeRange = this.selectedValues.yysj;
					
					// 解析时间段，获取开始时间和结束时间
					const [startTime, endTime] = selectedTimeRange.split('-');
					
					// 组合成完整的开始时间和结束时间
					const startDateTime = `${selectedDate} ${startTime}`;
					const endDateTime = `${selectedDate} ${endTime}`;
					
					const formData = {
						djmd: this.userInfo.mdid || "",
						yyr: this.userInfo.userId || "",
						yytyxm: this.selectedValues.yytyxm,
						gk: this.selectedValues.gkxm,
						gklx: this.selectedValues.gklx || '',
						gkxm: this.formData.gkxm,
						yyjks: this.selectedValues.yyjks,
						yysj: startDateTime,
						yyjs: endDateTime,
						f_Status: "已预约"
					};
					
					uni.showLoading({
						title: '正在提交...'
					});
					
					const result = await appointmentApi.createAppointment(formData);
					
					uni.hideLoading();
					
					if (result.code === 200) {
						uni.showToast({
							title: '预约添加成功！',
							icon: 'success'
						});
						this.clearForm();
					} else {
						uni.showToast({
							title: `添加失败：${result.message || '未知错误'}`,
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					console.error('提交失败:', error);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				}
			},
			
			// 清空表单
			clearForm() {
				this.formData = {
					yytyxm: '',
					gkxm: '',
					gklx: '',
					yyjks: '',
					yyrq: '',
					yysj: ''
				};
				
				this.selectedValues = {
					yytyxm: null,
					gkxm: null,
					gklx: null,
					yyjks: null,
					yyrq: null,
					yysj: null
				};
				
				// 重新设置默认日期
				this.setDefaultDate();
			},
			
			// 取消预约
			cancelAppointment() {
				this.clearForm();
				uni.navigateBack({
					delta: 1
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.appointment-container {
		height: 100vh;
		background: linear-gradient(135deg, #e8f5e9 0%, #b2dfdb 100%);
		padding: 20rpx;
		box-sizing: border-box;
	}
	
	.header {
		background: linear-gradient(120deg, #43e97b 0%, #38f9d7 100%);
		border-radius: 36rpx;
		padding: 48rpx;
		text-align: center;
		margin-bottom: 48rpx;
		box-shadow: 0 8rpx 48rpx 0 rgba(76, 175, 80, 0.10);
	}
	
	.header-title {
		color: #fff;
		font-size: 36rpx;
		font-weight: bold;
		letter-spacing: 4rpx;
	}
	
	.form-card {
		background: #fff;
		border-radius: 36rpx;
		box-shadow: 0 8rpx 48rpx 0 rgba(76, 175, 80, 0.10);
		border: 3rpx solid #c8e6c9;
		overflow: hidden;
	}
	
	.form-content {
		padding: 48rpx;
	}
	
	.form-group {
		margin-bottom: 40rpx;
	}
	
	.form-group:last-child {
		margin-bottom: 0;
	}
	
	.form-label {
		display: block;
		margin-bottom: 16rpx;
		font-weight: bold;
		color: #388e3c;
		letter-spacing: 2rpx;
		font-size: 28rpx;
	}
	
	.custom-select {
		position: relative;
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 20rpx;
		padding: 24rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		cursor: pointer;
		z-index: 10;
		min-height: 80rpx;
		box-sizing: border-box;
	}
	
	.select-text {
		font-size: 28rpx;
		color: #2e7d32;
		flex: 1;
	}
	
	.select-input-wrapper {
		position: relative;
		cursor: pointer;
		z-index: 10;
		background: transparent;
	}
	
	.select-input {
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 20rpx;
		padding: 24rpx;
		font-size: 28rpx;
		color: #2e7d32;
		width: 100%;
	}
	
	.select-arrow {
		position: absolute;
		right: 24rpx;
		top: 50%;
		transform: translateY(-50%);
		color: #6a9c6a;
		font-size: 24rpx;
		pointer-events: none;
	}
	
	.btn-group {
		display: flex;
		gap: 24rpx;
		margin-top: 48rpx;
	}
	
	.btn {
		flex: 1;
		padding: 10rpx 0;
		border-radius: 20rpx;
		font-size: 28rpx;
		font-weight: bold;
		letter-spacing: 2rpx;
	}
	
	.btn-primary {
		background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
		color: #fff;
		box-shadow: 0 4rpx 16rpx rgba(67, 233, 123, 0.3);
	}
	
	.btn-secondary {
		background: #f5f5f5;
		color: #666;
		// border: 3rpx solid #ddd;
	}
	
	
	// @media (max-width: 750rpx) {
	// 	.form-content { padding: 40rpx; }
	// 	.btn-group { flex-direction: column; }
	// }
</style>
