<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 class="required">*</text></text>
						<input type="number" class="form-input" placeholder="请输入年龄" v-model="formData.age" />
					</view>
					<view class="form-item">
						<text class="form-label">性别<text class="required">*</text></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 class="required">*</text></text>
						<input type="number" class="form-input" placeholder="请输入身高" v-model="formData.height" />
					</view>
					<view class="form-item">
						<text class="form-label">体重 (kg)<text class="required">*</text></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 class="required">*</text></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 class="required">*</text></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>
						<input type="text" class="form-input" placeholder="请输入择偶要求，如：176+本科" v-model="formData.mateSelectionCriteria" />
					</view>
				</view>

				<!-- 客户标签 -->
				<view class="form-section">
					<view class="section-title">客户标签</view>
					<view class="form-item">
						<text class="form-label">选择标签</text>
						<view class="tags-container">
							<view 
								class="tag-item" 
								:class="{ 'selected': selectedTagIds.includes(tag.id) }"
								v-for="tag in tagList" 
								:key="tag.id"
								@click="toggleTag(tag.id)"
							>
								<text class="tag-text">{{ tag.name }}</text>
							</view>
							<view v-if="tagList.length === 0" class="tag-loading">
								<text>加载中...</text>
							</view>
						</view>
					</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,
				mateSelectionCriteria: '',
				phone: '',
				backupPhone: ''
			},
			genderOptions: ['男', '女'],
			genderIndex: 0,
			constellationOptions: ['白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座'],
			constellationIndex: 0,
			maritalStatusOptions: ['未婚', '离异', '丧偶'],
			maritalStatusIndex: -1, // -1表示未选择，0-未婚，1-离异，2-丧偶
			diplomaOptions: ['高中', '专科', '本科', '硕士', '博士', '无'],
			diplomaIndex: 0,
			houseOptions: ['无', '有'],
			houseIndex: 0,
			carOptions: ['无', '有'],
			carIndex: 0,
			tagList: [], // 标签列表
			selectedTagIds: [] // 选中的标签ID列表
		}
	},
	onLoad() {
		// 获取当前登录用户信息
		const userInfo = uni.getStorageSync('userInfo') || {}
		const userId = uni.getStorageSync('userId')
		// 从userInfo中获取用户ID，将作为红娘ID
		let rawUserId = userInfo.userId || userId || null
		// 验证并转换currentUserId为有效的整数
		if (rawUserId !== null && rawUserId !== undefined) {
			rawUserId = parseInt(rawUserId)
			if (isNaN(rawUserId) || rawUserId <= 0) {
				rawUserId = null
			}
		}
		this.currentUserId = rawUserId
		console.log('当前登录用户ID:', this.currentUserId)
		
		// 加载标签列表
		this.loadTags()
	},
	methods: {
		goBack() {
			uni.navigateBack()
		},
		// 加载标签列表
		async loadTags() {
			try {
				const baseUrl = process.env.NODE_ENV === 'development' 
					? 'http://localhost:8083/api'  // 开发环境 - 通过网关
					: 'https://your-domain.com/api'  // 生产环境
				
				const [error, res] = await uni.request({
					url: `${baseUrl}/tag/list`,
					method: 'GET',
					timeout: 10000
				})
				
				if (error) {
					console.error('加载标签失败:', error)
					return
				}
				
				if (res.statusCode === 200 && res.data && res.data.code === 200) {
					this.tagList = res.data.data || []
					console.log('标签列表加载成功:', this.tagList)
				} else {
					console.error('加载标签失败:', res.data.message)
				}
			} catch (e) {
				console.error('加载标签异常:', e)
			}
		},
		// 切换标签选择状态
		toggleTag(tagId) {
			const index = this.selectedTagIds.indexOf(tagId)
			if (index > -1) {
				// 已选中，取消选择
				this.selectedTagIds.splice(index, 1)
			} else {
				// 未选中，添加到选中列表
				this.selectedTagIds.push(tagId)
			}
			console.log('选中的标签ID:', this.selectedTagIds)
		},
		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-丧偶
			// 直接使用索引值作为marrStatus的值
			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.age === null || this.formData.age === undefined || this.formData.age === '') {
				uni.showToast({
					title: '请输入年龄',
					icon: 'none'
				})
				return
			}
			
			// 验证性别
			if (this.formData.gender === null || this.formData.gender === undefined) {
				uni.showToast({
					title: '请选择性别',
					icon: 'none'
				})
				return
			}
			
			// 验证身高
			if (this.formData.height === null || this.formData.height === undefined || this.formData.height === '') {
				uni.showToast({
					title: '请输入身高',
					icon: 'none'
				})
				return
			}
			
			// 验证体重
			if (this.formData.weight === null || this.formData.weight === undefined || this.formData.weight === '') {
				uni.showToast({
					title: '请输入体重',
					icon: 'none'
				})
				return
			}
			
			// 验证婚况
			if ((this.maritalStatusIndex < 0 || this.maritalStatusIndex === null || this.maritalStatusIndex === undefined) 
				&& (this.formData.marrStatus === null || this.formData.marrStatus === undefined)) {
				uni.showToast({
					title: '请选择婚况',
					icon: 'none'
				})
				return
			}
			
			// 验证住址
			if (!this.formData.address || !this.formData.address.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.maritalStatusIndex === null || this.maritalStatusIndex === undefined) 
					&& (this.formData.marrStatus === null || this.formData.marrStatus === undefined)) {
					uni.showToast({
						title: '请选择婚况',
						icon: 'none'
					})
					return
				}
				
				// 调试：打印原始值
				console.log('=== 提交前的原始数据 ===')
				console.log('formData.marrStatus:', this.formData.marrStatus, '类型:', typeof this.formData.marrStatus)
				console.log('maritalStatusIndex:', this.maritalStatusIndex, '类型:', typeof this.maritalStatusIndex)
				console.log('formData.backupPhone:', this.formData.backupPhone, '类型:', typeof this.formData.backupPhone)
				console.log('formData.mateSelectionCriteria:', this.formData.mateSelectionCriteria, '类型:', typeof this.formData.mateSelectionCriteria)
				
				// 确定婚姻状态的值：优先使用formData.marrStatus，如果没有则使用maritalStatusIndex
				let marrStatusValue = null
				if (this.formData.marrStatus !== null && this.formData.marrStatus !== undefined && this.formData.marrStatus !== 'undefined' && this.formData.marrStatus !== 'null' && this.formData.marrStatus !== '') {
					const parsed = parseInt(this.formData.marrStatus)
					marrStatusValue = isNaN(parsed) ? null : parsed
					console.log('婚姻状态处理: formData.marrStatus ->', marrStatusValue)
				} else if (this.maritalStatusIndex !== null && this.maritalStatusIndex !== undefined && this.maritalStatusIndex >= 0) {
					const parsed = parseInt(this.maritalStatusIndex)
					marrStatusValue = isNaN(parsed) ? null : parsed
					console.log('婚姻状态处理: maritalStatusIndex ->', marrStatusValue)
				} else {
					console.log('婚姻状态处理: 未找到有效值')
				}
				
				// 处理备用手机号：保留有效值，空字符串转为null
				let backupPhoneValue = null
				const backupPhoneRaw = this.formData.backupPhone
				if (backupPhoneRaw !== null && backupPhoneRaw !== undefined && backupPhoneRaw !== 'undefined' && backupPhoneRaw !== 'null') {
					const trimmed = String(backupPhoneRaw).trim()
					if (trimmed !== '' && trimmed !== 'undefined' && trimmed !== 'null') {
						backupPhoneValue = trimmed
						console.log('备用手机号处理: 保留值 ->', backupPhoneValue)
					} else {
						console.log('备用手机号处理: 空值，转为null')
					}
				} else {
					console.log('备用手机号处理: 原始值为null/undefined')
				}
				
				// 处理择偶标准：保留有效值，空字符串转为null
				let mateSelectionCriteriaValue = null
				const mateSelectionCriteriaRaw = this.formData.mateSelectionCriteria
				if (mateSelectionCriteriaRaw !== null && mateSelectionCriteriaRaw !== undefined && mateSelectionCriteriaRaw !== 'undefined' && mateSelectionCriteriaRaw !== 'null') {
					const trimmed = String(mateSelectionCriteriaRaw).trim()
					if (trimmed !== '' && trimmed !== 'undefined' && trimmed !== 'null') {
						mateSelectionCriteriaValue = trimmed
						console.log('择偶标准处理: 保留值 ->', mateSelectionCriteriaValue)
					} else {
						console.log('择偶标准处理: 空值，转为null')
					}
				} else {
					console.log('择偶标准处理: 原始值为null/undefined')
				}
				
				// 辅助函数：安全地将值转换为整数，无效值返回null
				const safeParseInt = (value) => {
					if (value === null || value === undefined || value === '' || value === 'undefined' || value === 'null') {
						return null
					}
					const parsed = parseInt(value)
					return isNaN(parsed) ? null : parsed
				}
				
				// 辅助函数：安全地获取字符串值，无效值返回null
				const safeString = (value) => {
					if (value === null || value === undefined || value === '' || value === 'undefined' || value === 'null') {
						return null
					}
					const str = String(value).trim()
					return str === '' ? null : str
				}
				
				// 转换数据类型，明确构建提交数据对象
				const submitData = {
					name: safeString(this.formData.name),
					age: safeParseInt(this.formData.age),
					gender: safeParseInt(this.formData.gender),
					constellation: safeString(this.formData.constellation),
					height: safeParseInt(this.formData.height),
					weight: safeParseInt(this.formData.weight),
					// 确保婚姻状态被正确设置（0-未婚，1-离异，2-丧偶）
					marrStatus: marrStatusValue, // 直接使用处理后的值，不需要再次转换
					diploma: safeString(this.formData.diploma),
					income: safeString(this.formData.income),
					address: safeString(this.formData.address),
					domicile: safeString(this.formData.domicile),
					occupation: safeString(this.formData.occupation),
					house: safeParseInt(this.formData.house),
					car: safeParseInt(this.formData.car),
					phone: safeString(this.formData.phone),
					// 确保备用手机号被正确传递（保留有效值，null表示空）
					backupPhone: backupPhoneValue,
					// 确保择偶标准被正确传递（保留有效值，null表示空）
					mateSelectionCriteria: mateSelectionCriteriaValue,
					// 选中的标签ID列表
					tagIds: this.selectedTagIds.length > 0 ? this.selectedTagIds : null
				}
				
				console.log('提交数据 - 婚姻状态:', submitData.marrStatus, 'maritalStatusIndex:', this.maritalStatusIndex, 'formData.marrStatus:', this.formData.marrStatus, '选项:', submitData.marrStatus !== null ? this.maritalStatusOptions[submitData.marrStatus] : '未选择')
				console.log('提交数据 - 备用手机号:', submitData.backupPhone, '类型:', typeof submitData.backupPhone)
				console.log('提交数据 - 择偶标准:', submitData.mateSelectionCriteria, '类型:', typeof submitData.mateSelectionCriteria)
				console.log('提交数据 - 标签ID列表:', submitData.tagIds)
				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`
				// 确保currentUserId是有效的整数才添加到URL中
				if (this.currentUserId !== null && this.currentUserId !== undefined) {
					const userId = parseInt(this.currentUserId)
					if (!isNaN(userId) && userId > 0) {
						url += `?currentUserId=${userId}`
					}
				}
				
				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'
					})
					
					// 发送刷新事件，通知我的资源页面刷新列表
					uni.$emit('refreshResourceList')
					
					// 延迟返回上一页
					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;
			}
		}
		
		.tags-container {
			display: flex;
			flex-wrap: wrap;
			gap: 15rpx;
			margin-top: 10rpx;
			
			.tag-item {
				padding: 12rpx 24rpx;
				background: #F8F8F8;
				border: 2rpx solid #E0E0E0;
				border-radius: 24rpx;
				font-size: 26rpx;
				color: #666;
				transition: all 0.3s;
				
				&.selected {
					background: linear-gradient(135deg, #F3E5F5 0%, #E1BEE7 100%);
					border-color: #9C27B0;
					color: #7B1FA2;
					font-weight: 600;
					box-shadow: 0 2rpx 8rpx rgba(156, 39, 176, 0.2);
				}
				
				.tag-text {
					font-size: 26rpx;
				}
			}
			
			.tag-loading {
				padding: 20rpx;
				color: #999;
				font-size: 26rpx;
			}
		}

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

