<template>
	<view class="container">	
		<!-- 表单卡片 -->
		<view class="form-card">
			<view class="form-content">
				<view class="form-group">
					<text class="form-label">会员名称 *</text>
					<input 
						type="text" 
						v-model="formData.memberName" 
						placeholder="请输入会员名称" 
						class="input"
						@input="validateForm"
					/>
				</view>
				
				<view class="form-group">
					<text class="form-label">手机号 *</text>
					<input 
						type="tel" 
						v-model="formData.memberPhone" 
						placeholder="请输入手机号" 
						class="input"
						@input="validateForm"
					/>
				</view>
				
				<view class="form-group" style="display: none;">
					<text class="form-label">客户类型</text>
					<picker 
						:value="memberTypeIndex" 
						:range="memberTypeOptions" 
						@change="onMemberTypeChange"
					>
						<view class="picker-view">{{ memberTypeOptions[memberTypeIndex] }}</view>
					</picker>
				</view>
				
				<view class="form-group">
					<text class="form-label">客户来源</text>
					<picker 
						:value="memberSourceIndex" 
						:range="memberSourceOptions" 
						@change="onMemberSourceChange"
					>
						
						<view class="picker-view">{{ memberSourceOptions[memberSourceIndex] }}</view>
					</picker>
				</view>
				
				<view class="form-group" v-if="showReferrerGroup">
					<text class="form-label">推荐人 *</text>
					<view class="custom-select" @click="handleSelectClick('referrer')" @tap="handleSelectClick('referrer')">
						<text class="select-text">{{ formData.referrerName || '请选择推荐人' }}</text>
						<text class="select-arrow">▼</text>
					</view>
				</view>
				
				<view class="btn-group">
					<button 
						type="default" 
						size="normal"
						@click="resetForm"
						class="btn btn-secondary"
					>
						重置
					</button>
					<button 
						type="primary" 
						size="normal"
						@click="isSubmitting?'':createMember()"
						class="btn btn-primary"
					>
						{{ isSubmitting ? '建档中...' : '确定建档' }}
					</button>
				</view>
			</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 SearchSelectModal from '@/components/SearchSelectModal.vue'
	
	export default {
		components: {
			SearchSelectModal
		},
		data() {
			return {
				// 表单数据
				formData: {
					memberName: '',
					memberPhone: '',
					memberType: '1',
					memberSource: '自然到店',
					referrerId: '',
					referrerName: ''
				},
				
				// 选项数据
				memberTypeOptions: ['老客', '新客'],
				memberTypeIndex: 0,
				memberSourceOptions: [ '自然到店','嘉宾','售后','直播间','转店顾客','美团','联联','三方拓客','其他','补录'],
				memberSourceIndex: 0,
				
				// 推荐人相关
				showReferrerGroup: false,
				referrerOptions: [],
				
				// 弹窗相关
				showModal: false,
				modalTitle: '选择',
				currentSelectField: '',
				currentOptions: [],
				modalLoading: false,
				hasMoreData: true,
				currentPage: 1,
				pageSize: 20,
				searchKeyword: '',
				searchParam: '',
				
				// 表单验证
				isFormValid: false,
				isSubmitting: false,
				
				
				// 用户信息
				userInfo: null
			}
		},
		
		onLoad() {
			this.initializePage();
		},
		
		methods: {
			// 处理选择器点击
			handleSelectClick(fieldId) {
				this.openSelectModal(fieldId);
			},
			
			// 初始化页面
			async initializePage() {
				try {
					// 获取用户信息
					this.userInfo = uni.getStorageSync('userInfo');
					if (!this.userInfo) {
						uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/login/login'
							});
						}, 1500);
						return;
					}
					
					// 初始化表单
					this.resetForm();
					
				} catch (error) {
					console.error('初始化失败:', error);
					uni.showToast({
						title: '页面初始化失败',
						icon: 'none'
					});
				}
			},
			
			// 重置表单
			resetForm() {
				this.formData = {
					memberName: '',
					memberPhone: '',
					memberType: '1',
					memberSource: '自然到店',
					referrerId: '',
					referrerName: ''
				};
				this.memberTypeIndex = 0;
				this.memberSourceIndex = 0;
				this.showReferrerGroup = false;
				this.validateForm();
			},
			
			// 客户类型变化
			onMemberTypeChange(e) {
				this.memberTypeIndex = e.detail.value;
				this.formData.memberType = this.memberTypeOptions[this.memberTypeIndex];
				this.validateForm();
			},
			
			// 客户来源变化
			onMemberSourceChange(e) {
				this.memberSourceIndex = e.detail.value;
				this.formData.memberSource = this.memberSourceOptions[this.memberSourceIndex];
				
				if (this.formData.memberSource === '嘉宾') {
					this.showReferrerGroup = true;
					
				} else {
					this.showReferrerGroup = false;
					this.formData.referrerId = '';
					this.formData.referrerName = '';
				}
				this.validateForm();
			},
			
			// 打开选择弹窗
			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 'referrer':
						this.searchParam = 'khmc';
						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 'referrer':
						options = await this.getMemberOptions(page, searchKeyword);
						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) {
					if (this.currentSelectField === 'referrer') {
						this.formData.referrerId = selectedOption.value;
						this.formData.referrerName = selectedOption.label;
					}
					this.validateForm();
				}
			},
			
			// 处理加载更多
			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 getMemberOptions(page = 1, searchKeyword = '') {
				try {
					const params = {
						currentPage: page,
						pageSize: this.pageSize
					};
					
					// 如果有搜索关键词，添加搜索参数
					if (searchKeyword && this.searchParam === 'khmc') {
						params.keyword = searchKeyword;
					}
					
					const response = await this.API.getMemberList(params);
					
					if (response.code === 200 && response.data) {
						return response.data.list.map(item => ({
							value: item.id,
							label: item.khmc,
							subtitle:'客户类型：'+(item.khlxName||'无')+'；手机号：'+(item.sjh||'无')+'；健康师：' +(item.mrsName || '无')+'；门店：'+ (item.gsmdName || '无')+'；',
							sjh: item.sjh,
							khlx: item.khlx
						}));
					}
					return [];
				} catch (error) {
					console.error('获取会员选项失败:', error);
					return [];
				}
			},
			
			
			// 验证表单
			validateForm() {
				const { memberName, memberPhone, memberSource, referrerId } = this.formData;
				
				// 基本验证
				if (!memberName || !memberPhone) {
					this.isFormValid = false;
					return;
				}
				
				// 手机号格式验证
				const phoneRegex = /^1[3-9]\d{9}$/;
				if (!phoneRegex.test(memberPhone)) {
					this.isFormValid = false;
					return;
				}
				
				// 如果是嘉宾，必须选择推荐人
				if (memberSource === '嘉宾' && !referrerId) {
					this.isFormValid = false;
					return;
				}
				
				this.isFormValid = true;
			},
			
			// 创建会员
			async createMember() {
				const { memberName, memberPhone, memberType, memberSource, referrerId } = this.formData;
				
				// 验证必填字段
				if (!memberName) {
					uni.showToast({
					title: '请输入会员名称',
					icon: 'none'
				});
					return;
				}
				
				if (!memberPhone) {
					uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				});
					return;
				}
				
				// 验证手机号格式
				const phoneRegex = /^1[3-9]\d{9}$/;
				if (!phoneRegex.test(memberPhone)) {
					uni.showToast({
					title: '请输入正确的手机号格式',
					icon: 'none'
				});
					return;
				}
				// console.error(memberSource)
				// 如果是嘉宾，必须选择推荐人
				if (memberSource === '嘉宾' && !referrerId) {
					uni.showToast({
					title: '选择嘉宾时必须选择推荐人',
					icon: 'none'
				});
					return;
				}
				
				// 构建提交数据
				const memberData = {
					khmc: memberName,
					sjh: memberPhone,
					khlx: memberType,
					jdqd: memberSource,
					tjr: referrerId,
					gsmd: this.userInfo.mdid
				};
				
				try {
					this.isSubmitting = true;
					
					const response = await this.API.createMember(memberData);
					
					console.log(response);
					
					if (response.code === 200) {
						uni.showToast({
							title: '会员建档成功！',
							icon: 'success'
						});
						
						// 延迟重置表单
						setTimeout(() => {
							this.resetForm();
						}, 1500);
					} else {
						uni.showToast({
							title: `建档失败：${response.msg || '未知错误'}`,
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('建档失败:', error);
					uni.showToast({
						title: '网络错误，请检查连接后重试',
						icon: 'none'
					});
				} finally {
					this.isSubmitting = false;
				}
			},
			
			
			// 返回上一页
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.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);
		position: relative;
	}
	
	.header-title {
		color: #fff;
		font-size: 36rpx;
		font-weight: bold;
		letter-spacing: 4rpx;
		margin: 0 0 16rpx 0;
		display: block;
	}
	
	.header-desc {
		color: #e0f2f1;
		font-size: 28rpx;
		margin: 0;
		display: block;
	}
	
	.back-btn {
		position: absolute;
		top: 40rpx;
		left: 40rpx;
		background: rgba(255, 255, 255, 0.2);
		border: none;
		color: #fff;
		padding: 16rpx 24rpx;
		border-radius: 16rpx;
		font-size: 28rpx;
	}
	
	.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;
	}
	
	.input {
		width: 100%;
		padding: 24rpx;
		border: 3rpx solid #c8e6c9;
		border-radius: 20rpx;
		font-size: 28rpx;
		background: #f9fff9;
		color: #2e7d32;
		box-sizing: border-box;
		min-height: 80rpx;
		display: flex;
		align-items: center;
	}
	
	.input:focus {
		border-color: #43a047;
		background: #fff;
	}
	
	.input::placeholder {
		color: #81c784;
	}
	
	.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;
	}
	
	.picker-view {
		width: 100%;
		padding: 24rpx;
		border: 3rpx solid #c8e6c9;
		border-radius: 20rpx;
		font-size: 28rpx;
		background: #f9fff9;
		color: #2e7d32;
		box-sizing: border-box;
	}
	
	.btn-group {
		display: flex;
		gap: 24rpx;
		margin-top: 48rpx;
	}
	
	.btn {
		flex: 1;
		// padding: 28rpx 40rpx;
		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-primary:disabled {
		background: #e0e0e0;
		color: #999;
		box-shadow: none;
	}
	
	.btn-secondary {
		background: #f5f5f5;
		color: #666;
		border: 3rpx solid #ddd;
	}
	
	
	// @media (max-width: 750rpx) {
	// 	.form-content { 
	// 		padding: 40rpx; 
	// 	}
	// 	.btn-group { 
	// 		flex-direction: column; 
	// 	}
	// }
</style>
