<template>
	<view class="resource-input-page">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="header-left" @click="goBack">
				<text class="back-icon">←</text>
			</view>
			<text class="header-title">信息录入</text>
			<view class="header-right">
				<text class="more-icon">⋯</text>
			</view>
		</view>

		<scroll-view scroll-y class="content">
			<view class="form-container">
				<!-- 基本信息 -->
				<view class="form-section" :class="{ 'active': activeSection === 'basic' }">
					<view class="section-title">基本信息</view>
					<view class="form-item">
						<text class="form-label">姓名<text class="required">*</text></text>
						<input type="text" class="form-input" placeholder="请输入姓名" v-model="formData.name" />
					</view>
					<view class="form-item">
						<text class="form-label">年龄</text>
						<input type="number" class="form-input" placeholder="请输入年龄" v-model="formData.age" />
					</view>
					<view class="form-item">
						<text class="form-label">性别</text>
						<picker mode="selector" :range="genderOptions" :value="genderIndex" @change="onGenderChange">
							<view class="form-input picker-input">
								<text v-if="formData.gender">{{ genderOptions[genderIndex] }}</text>
								<text v-else class="placeholder">请选择性别</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
					<view class="form-item">
						<text class="form-label">星座</text>
						<picker mode="selector" :range="constellationOptions" :value="constellationIndex" @change="onConstellationChange">
							<view class="form-input picker-input">
								<text v-if="formData.constellation">{{ constellationOptions[constellationIndex] }}</text>
								<text v-else class="placeholder">请选择星座</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
				</view>

				<!-- 身体状况 -->
				<view class="form-section" :class="{ 'active': activeSection === 'physical' }">
					<view class="section-title">身体状况</view>
					<view class="form-item">
						<text class="form-label">身高 (cm)</text>
						<input type="number" class="form-input" placeholder="请输入身高" v-model="formData.height" />
					</view>
					<view class="form-item">
						<text class="form-label">体重 (kg)</text>
						<input type="number" class="form-input" placeholder="请输入体重" v-model="formData.weight" />
					</view>
				</view>

				<!-- 社会属性 -->
				<view class="form-section" :class="{ 'active': activeSection === 'social' }">
					<view class="section-title">社会属性</view>
					<view class="form-item">
						<text class="form-label">婚况</text>
						<picker mode="selector" :range="maritalStatusOptions" :value="maritalStatusIndex >= 0 ? maritalStatusIndex : 0" @change="onMaritalStatusChange">
							<view class="form-input picker-input">
								<text v-if="maritalStatusIndex >= 0 && maritalStatusIndex < maritalStatusOptions.length">{{ maritalStatusOptions[maritalStatusIndex] }}</text>
								<text v-else class="placeholder">请选择婚况</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
					<view class="form-item">
						<text class="form-label">学历</text>
						<picker mode="selector" :range="diplomaOptions" :value="diplomaIndex" @change="onDiplomaChange">
							<view class="form-input picker-input">
								<text v-if="formData.diploma">{{ diplomaOptions[diplomaIndex] }}</text>
								<text v-else class="placeholder">请选择学历</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
					<view class="form-item">
						<text class="form-label">年收入 (万元)</text>
						<input type="text" class="form-input" placeholder="请输入年收入" v-model="formData.income" />
					</view>
					<view class="form-item">
						<text class="form-label">住址</text>
						<input type="text" class="form-input" placeholder="请输入住址" v-model="formData.address" />
					</view>
					<view class="form-item">
						<text class="form-label">户籍地</text>
						<input type="text" class="form-input" placeholder="请输入户籍地" v-model="formData.domicile" />
					</view>
					<view class="form-item">
						<text class="form-label">职业</text>
						<input type="text" class="form-input" placeholder="请输入职业" v-model="formData.occupation" />
					</view>
					<view class="form-item">
						<text class="form-label">购房</text>
						<picker mode="selector" :range="houseOptions" :value="houseIndex" @change="onHouseChange">
							<view class="form-input picker-input">
								<text v-if="formData.house !== null && formData.house !== undefined">{{ houseOptions[houseIndex] }}</text>
								<text v-else class="placeholder">请选择</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
					<view class="form-item">
						<text class="form-label">购车</text>
						<picker mode="selector" :range="carOptions" :value="carIndex" @change="onCarChange">
							<view class="form-input picker-input">
								<text v-if="formData.car !== null && formData.car !== undefined">{{ carOptions[carIndex] }}</text>
								<text v-else class="placeholder">请选择</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
				</view>

				<!-- 联系方式 -->
				<view class="form-section">
					<view class="section-title">联系方式</view>
					<view class="form-item">
						<text class="form-label">手机号<text class="required">*</text></text>
						<input type="text" class="form-input" placeholder="请输入手机号" v-model="formData.phone" />
					</view>
					<view class="form-item">
						<text class="form-label">备用手机号</text>
						<input type="text" class="form-input" placeholder="请输入备用手机号" v-model="formData.backupPhone" />
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部提交按钮 -->
		<view class="submit-bar">
			<button class="submit-btn" @click="handleSubmit">提交</button>
		</view>
	</view>
</template>

<script>
import api from '@/utils/api.js'

export default {
	data() {
		return {
			activeSection: 'basic',
			currentUserId: null, // 当前登录用户的用户ID
			formData: {
				name: '',
				age: null,
				gender: null,
				constellation: '',
				height: null,
				weight: null,
				marrStatus: null,
				diploma: '',
				income: '',
				address: '',
				domicile: '',
				occupation: '',
				house: null,
				car: null,
				phone: '',
				backupPhone: ''
			},
			genderOptions: ['男', '女'],
			genderIndex: 0,
			constellationOptions: ['白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座'],
			constellationIndex: 0,
			maritalStatusOptions: ['未婚', '离异', '丧偶'],
			maritalStatusIndex: -1, // -1表示未选择，0-未婚，1-离异，2-丧偶
			diplomaOptions: ['高中', '专科', '本科', '硕士', '博士', '无'],
			diplomaIndex: 0,
			houseOptions: ['无', '有'],
			houseIndex: 0,
			carOptions: ['无', '有'],
			carIndex: 0
		}
	},
	onLoad() {
		// 获取当前登录用户信息
		const userInfo = uni.getStorageSync('userInfo') || {}
		const userId = uni.getStorageSync('userId')
		// 从userInfo中获取用户ID，将作为红娘ID
		this.currentUserId = userInfo.userId || userId || null
		console.log('当前登录用户ID:', this.currentUserId)
	},
	methods: {
		goBack() {
			uni.navigateBack()
		},
		onGenderChange(e) {
			this.genderIndex = e.detail.value
			this.formData.gender = this.genderIndex + 1 // 1-男，2-女
		},
		onConstellationChange(e) {
			this.constellationIndex = e.detail.value
			this.formData.constellation = this.constellationOptions[this.constellationIndex]
		},
		onMaritalStatusChange(e) {
			this.maritalStatusIndex = parseInt(e.detail.value)
			// 0-未婚，1-离异，2-丧偶
			this.formData.marrStatus = this.maritalStatusIndex
			console.log('婚姻状态选择:', this.maritalStatusIndex, '对应值:', this.formData.marrStatus, '选项:', this.maritalStatusOptions[this.maritalStatusIndex])
		},
		onDiplomaChange(e) {
			this.diplomaIndex = e.detail.value
			this.formData.diploma = this.diplomaOptions[this.diplomaIndex]
		},
		onHouseChange(e) {
			this.houseIndex = e.detail.value
			this.formData.house = this.houseIndex // 0-无，1-有
		},
		onCarChange(e) {
			this.carIndex = e.detail.value
			this.formData.car = this.carIndex // 0-无，1-有
		},
		async handleSubmit() {
			// 验证必填项
			if (!this.formData.name || !this.formData.name.trim()) {
				uni.showToast({
					title: '请输入姓名',
					icon: 'none'
				})
				return
			}
			
			if (!this.formData.phone || !this.formData.phone.trim()) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				})
				return
			}

			// 验证手机号格式
			const phoneReg = /^1[3-9]\d{9}$/
			if (!phoneReg.test(this.formData.phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				})
				return
			}

			uni.showLoading({
				title: '提交中...'
			})

			try {
				// 确保婚姻状态已选择
				if (this.maritalStatusIndex < 0 && (this.formData.marrStatus === null || this.formData.marrStatus === undefined)) {
					uni.showToast({
						title: '请选择婚况',
						icon: 'none'
					})
					return
				}
				
				// 转换数据类型
				const submitData = {
					...this.formData,
					age: this.formData.age ? parseInt(this.formData.age) : null,
					height: this.formData.height ? parseInt(this.formData.height) : null,
					weight: this.formData.weight ? parseInt(this.formData.weight) : null,
					// 确保婚姻状态被正确设置（0-未婚，1-离异，2-丧偶）
					marrStatus: this.formData.marrStatus !== null && this.formData.marrStatus !== undefined 
						? parseInt(this.formData.marrStatus) 
						: (this.maritalStatusIndex >= 0 ? parseInt(this.maritalStatusIndex) : null),
					// 确保备用手机号被正确传递（即使是空字符串也要传递）
					backupPhone: this.formData.backupPhone !== null && this.formData.backupPhone !== undefined 
						? this.formData.backupPhone.trim() 
						: null
				}
				
				// 如果婚姻状态仍然为null，但maritalStatusIndex有值，使用maritalStatusIndex
				if (submitData.marrStatus === null && this.maritalStatusIndex >= 0) {
					submitData.marrStatus = parseInt(this.maritalStatusIndex)
				}
				
				console.log('提交数据 - 婚姻状态:', submitData.marrStatus, 'maritalStatusIndex:', this.maritalStatusIndex, '选项:', this.maritalStatusOptions[submitData.marrStatus])
				console.log('提交数据 - 备用手机号:', submitData.backupPhone, '类型:', typeof submitData.backupPhone)
				console.log('完整提交数据:', JSON.stringify(submitData, null, 2))

				// 调用后端接口（通过网关）
				const baseUrl = process.env.NODE_ENV === 'development' 
					? 'http://localhost:8083/api'  // 开发环境 - 通过网关
					: 'https://your-domain.com/api'  // 生产环境
				
				// 构建请求URL，包含当前登录用户的ID作为参数（将作为红娘ID）
				let url = `${baseUrl}/my-resource/add`
				if (this.currentUserId) {
					url += `?currentUserId=${this.currentUserId}`
				}
				
				const res = await uni.request({
					url: url,
					method: 'POST',
					data: submitData,
					header: {
						'Content-Type': 'application/json'
					}
				})

				uni.hideLoading()

				if (res[1].statusCode === 200 && res[1].data.code === 200) {
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					})
					
					// 延迟返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({
						title: res[1].data.message || '提交失败',
						icon: 'none',
						duration: 2000
					})
				}
			} catch (error) {
				uni.hideLoading()
				console.error('提交失败:', error)
				uni.showToast({
					title: '提交失败，请稍后重试',
					icon: 'none'
				})
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.resource-input-page {
	min-height: 100vh;
	background: #FFF9F9;
	display: flex;
	flex-direction: column;
}

.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 25rpx 30rpx;
	padding-top: calc(25rpx + env(safe-area-inset-top));
	background: #FFF9F9;
	border-bottom: 1rpx solid #F0F0F0;

	.header-left {
		width: 60rpx;
	}

	.back-icon {
		font-size: 40rpx;
		color: #333;
	}

	.header-title {
		flex: 1;
		text-align: center;
		font-size: 38rpx;
		font-weight: bold;
		color: #9C27B0;
	}

	.header-right {
		width: 60rpx;
		text-align: right;
	}

	.more-icon {
		font-size: 40rpx;
		color: #333;
	}
}

.content {
	flex: 1;
	padding-bottom: 120rpx;
}

.form-container {
	padding: 20rpx;
}

.form-section {
	background: #FFFFFF;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	border: 2rpx solid transparent;

	&.active {
		border-color: #FF4081;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
		padding-bottom: 15rpx;
		border-bottom: 2rpx solid #F0F0F0;
	}
}

.form-item {
	margin-bottom: 30rpx;

	&:last-child {
		margin-bottom: 0;
	}

	.form-label {
		display: block;
		font-size: 28rpx;
		color: #666;
		margin-bottom: 15rpx;

		.required {
			color: #FF4444;
			margin-left: 5rpx;
		}
	}

	.form-input {
		width: 100%;
		height: 80rpx;
		background: #F8F8F8;
		border: 2rpx solid #E0E0E0;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #333;
		box-sizing: border-box;

		&:focus {
			border-color: #9C27B0;
			background: #FFFFFF;
		}
	}

	.picker-input {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.placeholder {
			color: #999;
		}

		.picker-arrow {
			font-size: 24rpx;
			color: #999;
		}
	}
}

.submit-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx 30rpx;
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	background: #FFFFFF;
	border-top: 1rpx solid #F0F0F0;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

	.submit-btn {
		width: 100%;
		height: 88rpx;
		background: linear-gradient(135deg, #9C27B0 0%, #BA68C8 100%);
		color: #FFFFFF;
		font-size: 32rpx;
		font-weight: bold;
		border-radius: 44rpx;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
	}
}
</style>

