<template>
	<view class="invite-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" @tap="openDateTimePicker">
							<text class="select-text">{{ formData.yysj?utils.formatTime(formData.yysj):'请选择邀约时间'}}</text>
							<text class="select-arrow">▼</text>
						</view>
					</view> -->

					<view class="form-group">
						<text class="form-label">预约客户</text>
						<view class="custom-select" @click="iskh?handleSelectClick('yykh'):''">
							<text class="select-text">{{ formData.yykh || '请选择预约客户' }}</text>
							<text class="select-arrow">▼</text>
						</view>
					</view>

					<view class="form-group">
						<text class="form-label">联系电话</text>
						<view class="custom-select" >
							<text class="select-text">{{ formData.dh?formData.dh:'电话号码'}}</text>
							<!-- <text class="select-arrow">▼</text> -->
						</view>
						<!-- <u-input v-model="" placeholder="电话号码" class="select-input" /> -->
					</view>

					<view class="form-group">
						<text class="form-label">电话是否有效</text>
						<view class="custom-select" @tap="openYesNoPicker">
							<text class="select-text">{{ formData.dhsfyx || '请选择是否有效' }}</text>
							<text class="select-arrow">▼</text>
						</view>
					</view>

					<view class="form-group">
						<text class="form-label">联系记录</text>
						<textarea v-model="formData.lxjl" placeholder="请输入联系记录" :maxlength="500" :count="true"
							class="textarea-input" />
					</view>

					<button type="primary" size="normal" @click="isSubmit?submitInvite():''" class="submit-btn">
						{{isSubmit?'提交':'提交中...'}}
					</button>
				</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"
		/>
		<u-datetime-picker v-if="showDateTimePicker" :show="showDateTimePicker" :value="formData.yysj" mode="datetime" :min-date="minDate"
			:max-date="maxDate" @confirm="onDateTimeConfirm" @close="closeDateTimePicker" @cancel="closeDateTimePicker" :show-toolbar="true"
			:close-on-click-overlay="true" confirm-color="#43e97b" title="选择邀约时间" class="datetime-picker" />
		<u-picker v-if="showYesNoPicker" :show="showYesNoPicker" :columns="[yesNoOptions]" :show-toolbar="true" :close-on-click-overlay="true"
			confirm-color="#43e97b" title="选择是否有效" @confirm="onYesNoConfirm" @close="closeYesNoPicker" @cancel="closeYesNoPicker"
			class="select-input" />
	</view>
</template>

<script>
	import inviteApi from '@/apis/modules/invite.js'
	import SearchSelectModal from '@/components/SearchSelectModal.vue'
	import clueApi from '@/apis/modules/clue.js'
	export default {
		components: {
			SearchSelectModal
		},
		data() {
			return {
				iskh:true,
				isSubmit:true,
				// 表单数据
				formData: {
					yysj: '',
					yykh: '',
					dh: '',
					dhsfyx: '',
					lxjl: ''
				},

				// 弹窗相关
				showModal: false,
				modalTitle: '',
				currentSelectField: '',
				currentOptions: [],
				modalLoading: false,
				hasMoreData: true,
				currentPage: 1,
				pageSize: 20,
				searchKeyword: '',
				searchParam: '',

				// 用户信息
				userInfo: null,

				// 选中的值
				selectedValues: {
					yykh: null
				},

				// 日期范围
				minDate: 0,
				maxDate: 0,

				// 是否有效选项
				yesNoOptions: [{
						text: '是',
						value: '是'
					},
					{
						text: '否',
						value: '否'
					}
				],

				// 是否有效选择器显示状态
				showYesNoPicker: false,

				// 日期时间选择器显示状态
				showDateTimePicker: false,
				tkbh: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.setDateRange();

					// 设置默认时间
					this.setDefaultDateTime();

					// 填充URL参数中的客户信息
					this.fillCustomerInfoFromUrl(options);
				} catch (error) {
					console.error('页面初始化失败:', error);
					uni.showToast({
						title: '页面初始化失败',
						icon: 'none'
					});
				}
			},

			// 设置日期范围
			setDateRange() {
				const now = new Date();
				this.minDate = now.getTime();

				// 最大日期为一年后
				const maxDate = new Date(now);
				maxDate.setFullYear(now.getFullYear() + 1);
				this.maxDate = maxDate.getTime();
			},

			// 设置默认时间
			setDefaultDateTime() {
				const now = new Date();
				this.formData.yysj = now.getTime();
			},

			// 填充URL参数中的客户信息
			async fillCustomerInfoFromUrl(options) {
				const name = options.name;
				const phone = options.phone;
				const id = options.id;
				const tkbh = options.tkbh;
				const customerPhone = options.customerPhone;
				// 如果有客户信息，填充到客户字段
				if (name && id) {
					this.formData.yykh = name;
					this.selectedValues.yykh = id;
				}

				// 如果有电话信息，填充到电话字段
				if (phone) {
					this.formData.dh = phone;
				}
				if(tkbh){
					this.tkbh = tkbh;
				}
				if(customerPhone){
					this.iskh = false
					let params = {
						currentPage: 1,
						pageSize: 1,
						keyword: customerPhone
					};
					const result = await clueApi.getCustomerClues(params);
					if(result.code === 200 && result.data.list.length > 0){
						this.formData.yykh = result.data.list[0].khmc;
						this.selectedValues.yykh = result.data.list[0].id;
						this.formData.dh = result.data.list[0].sjh;
					}
				}
			},


			// 打开日期时间选择器
			openDateTimePicker() {
				this.showDateTimePicker = true;
			},

			// 关闭日期时间选择器
			closeDateTimePicker() {
				this.showDateTimePicker = false;
			},

			// 确认日期时间选择
			onDateTimeConfirm(e) {
				const {
					value
				} = e;
				if (value) {
					this.formData.yysj = value;
				}
				this.showDateTimePicker = false;
			},


			// 打开是否有效选择器
			openYesNoPicker() {
				this.showYesNoPicker = true;
			},

			// 关闭是否有效选择器
			closeYesNoPicker() {
				this.showYesNoPicker = false;
			},

			// 确认是否有效选择
			onYesNoConfirm(e) {
				const {
					value
				} = e;
				if (value && value[0]) {
					this.formData.dhsfyx = value[0].text;
				}
				this.showYesNoPicker = false;
			},


			// 打开选择弹窗
			async openSelectModal(fieldId) {
				this.currentSelectField = fieldId;
				this.showModal = true;
				this.modalTitle = '加载中...';
				this.modalLoading = true;
				this.currentPage = 1;
				this.hasMoreData = true;
				this.searchKeyword = '';
				this.currentOptions = [];

				try {
					// 设置搜索参数
					switch (fieldId) {
						case 'yykh':
							this.searchParam = 'khmc';
							this.modalTitle = '选择预约客户';
							break;
					}

					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;
				this.hasMoreData = true;
				this.currentPage = 1;
				this.searchKeyword = '';
			},

			// 加载选项数据
			async loadOptionsData(fieldId, page = 1, searchKeyword = '') {
				let options = [];
				
				switch(fieldId) {
					case 'yykh':
						options = await this.getCustomerOptions(page, searchKeyword);
						break;
				}
				console.error(options);
				// 为每个选项添加全局唯一的 key，避免重复
				options = options.map((option, index) => ({
					...option,
					sjh: option.sjh,
					uniqueKey: `${fieldId}_${page}_${index}_${Date.now()}`
				}));
				console.log(options);
				if (page === 1) {
					this.currentOptions = options;
				} else {
					this.currentOptions = [...this.currentOptions, ...options];
				}
				
				// 检查是否还有更多数据
				if (options.length < this.pageSize) {
					this.hasMoreData = false;
				}
			},

			// 处理弹窗确认
			handleModalConfirm(selectedOption) {
				console.log(selectedOption);
				if (this.currentSelectField && selectedOption) {
					this.formData[this.currentSelectField] = selectedOption.label;
					this.selectedValues[this.currentSelectField] = selectedOption.value;
					if(this.currentSelectField === 'yykh'){
						this.formData.dh = selectedOption.sjh;
						this.selectedValues.dh = selectedOption.sjh;
					}
				}
			},

			// 处理加载更多
			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 getCustomerOptions(page = 1, searchKeyword = '') {
				try {
					const params = {
						currentPage: page,
						pageSize: this.pageSize
					};
					
					// 添加搜索参数
					if (searchKeyword && this.searchParam === 'khmc') {
						params.keyword = searchKeyword;
					}

					const result = await inviteApi.getCustomerList(params);
					if (result.code === 200 && result.data) {
						return result.data.list.map((item, index) => {
							// 确保每个选项都有唯一的 value
							let value = item.yykh || item.id;
							if (!value || value === '') {
								value = `customer_${page}_${index}`;
							}
							return {
								value: value,
								label: item.khmc,
								yykhxm: item.khmc,
								sjh: item.sjh,
								subtitle:'客户类型：'+(item.khlxName||'无')+'；手机号：'+(item.sjh||'无')+'；健康师：' +(item.mrsName || '无')+'；门店：'+ (item.gsmdName || '无')+'；',
							};
						});
					}
					return [];
				} catch (error) {
					console.error('获取客户列表出错:', error);
					return [];
				}
			},

			// 默认顾客选项
			getDefaultCustomerOptions() {
				return [{
						value: 'GK2020082101170',
						label: '张三'
					},
					{
						value: 'GK2020082101171',
						label: '李四'
					},
					{
						value: 'GK2020082101172',
						label: '王五'
					},
					{
						value: 'GK2020082101173',
						label: '赵六'
					},
					{
						value: 'GK2020082101174',
						label: '钱七'
					}
				];
			},

			// 处理表单提交
			handleFormSubmit(event) {
				event.preventDefault();
				this.submitInvite();
			},

			// 提交邀约
			async submitInvite() {
				// 验证表单
				if (!this.formData.yysj) {
					uni.showToast({
						title: '请选择邀约时间',
						icon: 'none'
					});
					return;
				}
				if (!this.selectedValues.yykh) {
					uni.showToast({
						title: '请选择预约客户',
						icon: 'none'
					});
					return;
				}
				if (!this.formData.dhsfyx) {
					uni.showToast({
						title: '请选择电话是否有效',
						icon: 'none'
					});
					return;
				}
				if (!this.formData.lxjl.trim()) {
					uni.showToast({
						title: '请输入联系记录',
						icon: 'none'
					});
					return;
				}
			
				

				try {
					// 收集表单数据
					const formData = {
						yyr: this.userInfo.userId,
						dhsfyx: this.formData.dhsfyx,
						lxjl: this.formData.lxjl.trim(),
						lxsj: new Date().getTime(), // 联系时间使用当前时间戳
						yykh: this.selectedValues.yykh,
						yysj: this.formData.yysj, // 邀约时间直接使用时间戳
						yykhxm: this.formData.yykh
					};
					if(this.tkbh){
						formData.tkbh = this.tkbh;
					}
					this.isSubmit = false;
					uni.showLoading({
						title: '正在提交...'
					});

					const result = await inviteApi.createInvite(formData);

					uni.hideLoading();

					if (result.code === 200) {
						uni.showToast({
							title: '邀请添加成功！',
							icon: 'success'
						});
						this.clearForm();
					} else {
						uni.showToast({
							title: `添加失败：${result.message || '未知错误'}`,
							icon: 'none'
						});
					}
					this.isSubmit = true;
				} catch (error) {
					uni.hideLoading();
					console.error('提交失败:', error);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
					this.isSubmit = true;
				}
			},

			// 清空表单
			clearForm() {
				this.formData = {
					yysj: '',
					yykh: '',
					dh: '',
					dhsfyx: '',
					lxjl: ''
				};

				this.selectedValues = {
					yykh: null
				};

				// 重新设置默认时间
				this.setDefaultDateTime();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.invite-container {
		min-height: 100vh;
		background: linear-gradient(135deg, #e8f5e9 0%, #b2dfdb 100%);
		padding: 20rpx;
	}

	.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;
	}

	.datetime-picker {
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 20rpx;
		padding: 24rpx;
		font-size: 28rpx;
		color: #2e7d32;
	}

	.select-input {
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 20rpx;
		padding: 24rpx;
		font-size: 28rpx;
		color: #2e7d32;
	}

	.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-arrow {
		position: absolute;
		right: 24rpx;
		top: 50%;
		transform: translateY(-50%);
		color: #6a9c6a;
		font-size: 24rpx;
		pointer-events: none;
	}

	.clickable-input {
		cursor: pointer;
		transition: all 0.2s ease;
	}

	.clickable-input:active {
		background: #e8f5e9;
		transform: scale(0.98);
	}

	.input-text {
		color: #2e7d32;
		font-size: 28rpx;
	}

	.placeholder-text {
		color: #999;
		font-size: 28rpx;
	}

	.readonly-input {
		background: #f5f5f5;
		border: 3rpx solid #ddd;
		border-radius: 20rpx;
		padding: 24rpx;
		font-size: 28rpx;
		color: #666;
	}

	.textarea-input {
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 20rpx;
		padding: 24rpx;
		font-size: 28rpx;
		color: #2e7d32;
		min-height: 200rpx;
		box-sizing: border-box;
	}

	.submit-btn {
		width: 100%;
		padding: 10rpx 40rpx;
		border-radius: 24rpx;
		font-size: 32rpx;
		font-weight: 600;
		letter-spacing: 2rpx;
		background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
		color: #fff;
		box-shadow: 0 8rpx 32rpx rgba(67, 233, 123, 0.3);
		margin-top: 64rpx;
		border-color: #43e97b;
	}


	// @media (max-width: 750rpx) {
	// 	.form-content {
	// 		padding: 40rpx;
	// 	}

	// 	.modal-content {
	// 		width: 90vw;
	// 	}
	// }
</style>