<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">{{ isEditMode ? '编辑信息' : '信息录入' }}</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>
						<!-- 省市区三级联动选择器 -->
						<picker mode="multiSelector" :range="addressMultiArray" :value="addressMultiIndex" @columnchange="onAddressColumnChange" @change="onAddressChange">
							<view class="form-input picker-input">
								<text v-if="addressDisplayText" class="picker-text">{{ addressDisplayText }}</text>
								<text v-else class="placeholder">请选择省市区</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
						<!-- 详细地址输入框 -->
						<input type="text" class="form-input address-detail-input" placeholder="请输入详细地址（街道、门牌号等）" v-model="formData.addressDetail" style="margin-top: 15rpx;" />
					</view>
					<view class="form-item">
						<text class="form-label">户籍地</text>
						<!-- 省市区三级联动选择器 -->
						<picker mode="multiSelector" :range="domicileMultiArray" :value="domicileMultiIndex" @columnchange="onDomicileColumnChange" @change="onDomicileChange">
							<view class="form-input picker-input">
								<text v-if="domicileDisplayText" class="picker-text">{{ domicileDisplayText }}</text>
								<text v-else class="placeholder">请选择省市区</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
						<!-- 详细地址输入框 -->
						<input type="text" class="form-input address-detail-input" placeholder="请输入详细地址（街道、门牌号等）" v-model="formData.domicileDetail" style="margin-top: 15rpx;" />
					</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="category-buttons">
							<view 
								class="category-btn" 
								:class="{ 'active': selectedCategoryId === category.id }"
								v-for="category in categoryList" 
								:key="category.id"
								@click="selectCategory(category.id)"
							>
								<text class="category-btn-text">{{ category.name }}</text>
							</view>
						</view>
						<!-- 标签列表 -->
						<view class="tags-container">
							<view 
								class="tag-item" 
								:class="{ 'selected': selectedTagIds.includes(tag.id) }"
								v-for="tag in filteredTagList" 
								:key="tag.id || tag.tag_id"
								@click="toggleTag(tag.id || tag.tag_id)"
							>
								<text class="tag-text">{{ tag.name || tag.tag_name }}</text>
							</view>
							<view v-if="filteredTagList.length === 0 && !isLoadingTags" class="tag-empty">
								<text>暂无标签</text>
							</view>
							<view v-if="isLoadingTags" 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">{{ isEditMode ? '确认修改' : '提交' }}</button>
		</view>
	</view>
</template>

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

export default {
	data() {
		return {
			activeSection: 'basic',
			currentUserId: null, // 当前登录用户的用户ID
			resourceId: null, // 编辑模式下的资源ID
			isEditMode: false, // 是否为编辑模式
			formData: {
				name: '',
				age: null,
				gender: null,
				constellation: '',
				height: null,
				weight: null,
				marrStatus: null,
				diploma: '',
				income: '',
				address: '', // 住址（省市区+详细地址组合）
				addressDetail: '', // 住址详细地址
				domicile: '', // 户籍地（省市区+详细地址组合）
				domicileDetail: '', // 户籍地详细地址
				occupation: '',
				house: null,
				car: null,
				mateSelectionCriteria: '',
				phone: '',
				backupPhone: ''
			},
			// 住址省市区数据
			addressProvinces: [],
			addressCities: [],
			addressAreas: [],
			addressMultiArray: [[], [], []], // 三级联动数据
			addressMultiIndex: [0, 0, 0], // 三级联动索引
			addressDisplayText: '', // 住址显示文本
			// 户籍地省市区数据
			domicileProvinces: [],
			domicileCities: [],
			domicileAreas: [],
			domicileMultiArray: [[], [], []], // 三级联动数据
			domicileMultiIndex: [0, 0, 0], // 三级联动索引
			domicileDisplayText: '', // 户籍地显示文本
			genderOptions: ['男', '女'],
			genderIndex: 0,
			constellationOptions: ['白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座'],
			constellationIndex: 0,
			maritalStatusOptions: ['未婚', '离异', '丧偶'],
			maritalStatusIndex: -1, // -1表示未选择，0-未婚，1-离异，2-丧偶
			diplomaOptions: ['高中', '专科', '本科', '硕士', '博士', '无'],
			diplomaIndex: 0,
			houseOptions: ['无', '有'],
			houseIndex: 0,
			carOptions: ['无', '有'],
			carIndex: 0,
			tagList: [], // 所有标签列表
			categoryList: [], // 标签分类列表
			selectedCategoryId: 1, // 当前选中的分类ID，默认显示职业分类（category_id = 1）
			selectedTagIds: [], // 选中的标签ID列表
			isLoadingTags: false // 是否正在加载标签
		}
	},
	computed: {
		// 根据选中的分类筛选标签（只显示当前分类的标签，不显示全部）
		filteredTagList() {
			// 如果没有选中分类，返回空数组（不显示任何标签）
			if (this.selectedCategoryId === null || this.selectedCategoryId === undefined) {
				return []
			}
			
			// 确保selectedCategoryId是数字类型
			const selectedId = parseInt(this.selectedCategoryId)
			if (isNaN(selectedId)) {
				
				return []
			}
			
			// 筛选标签，只显示当前分类的标签
			const filtered = this.tagList.filter(tag => {
				// 获取标签的分类ID，优先使用 category_id（后端返回的字段名）
				const tagCategoryId = tag.category_id !== null && tag.category_id !== undefined 
					? parseInt(tag.category_id) 
					: (tag.categoryId !== null && tag.categoryId !== undefined 
						? parseInt(tag.categoryId) 
						: null)
				
				// 如果tagCategoryId是NaN或null，说明数据有问题或未分类，不显示
				if (isNaN(tagCategoryId) || tagCategoryId === null) {
					return false
				}
				
				// 只返回匹配当前分类的标签
				return tagCategoryId === selectedId
			})
			
			return filtered
		}
	},
	onLoad(options) {
		// 获取当前登录用户信息
		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
	
		
		// 检查是否为编辑模式
		if (options && options.resourceId) {
			this.resourceId = parseInt(options.resourceId)
			this.isEditMode = true
			
			// 加载资源详情
			this.loadResourceDetail()
		}
		
		// 加载标签分类和标签列表
		this.loadCategories()
		this.loadTags()
		
		// 加载省市区数据
		this.loadAddressProvinces()
		this.loadDomicileProvinces()
	},
	methods: {
		goBack() {
			uni.navigateBack()
		},
		// 加载资源详情（编辑模式）
		async loadResourceDetail() {
			if (!this.resourceId) return
			
			try {
				uni.showLoading({ title: '加载中...' })
				const baseUrl = process.env.NODE_ENV === 'development' 
					? 'https://api.zhongruanke.cn/api'  // 开发环境 - 通过网关
					: 'https://your-domain.com/api'  // 生产环境
				
				const [error, res] = await uni.request({
					url: `${baseUrl}/my-resource/detail/${this.resourceId}`,
					method: 'GET'
				})
				
				uni.hideLoading()
				
				if (error) {
					
					uni.showToast({
						title: '加载资源详情失败',
						icon: 'none'
					})
					return
				}
				
				if (res.statusCode === 200 && res.data) {
					// 检查返回的code
					if (res.data.code === 200 && res.data.data) {
						const resource = res.data.data
					
						
						// 填充表单数据
						this.formData.name = resource.name || ''
						this.formData.age = resource.age || null
						this.formData.gender = resource.gender || null
						if (this.formData.gender) {
							this.genderIndex = this.formData.gender - 1 // 1-男，2-女 -> 0,1
						}
						this.formData.constellation = resource.constellation || ''
						if (this.formData.constellation) {
							const index = this.constellationOptions.indexOf(this.formData.constellation)
							if (index >= 0) {
								this.constellationIndex = index
							}
						}
						this.formData.height = resource.height || null
						this.formData.weight = resource.weight || null
						this.formData.marrStatus = resource.marrStatus !== null && resource.marrStatus !== undefined ? resource.marrStatus : null
						if (this.formData.marrStatus !== null && this.formData.marrStatus >= 0) {
							this.maritalStatusIndex = this.formData.marrStatus
						}
						this.formData.diploma = resource.diploma || ''
						if (this.formData.diploma) {
							const index = this.diplomaOptions.indexOf(this.formData.diploma)
							if (index >= 0) {
								this.diplomaIndex = index
							}
						}
						this.formData.income = resource.income || ''
						
						// 解析地址和户籍地
						this.parseAddress(resource.address || '')
						this.parseDomicile(resource.domicile || '')
						
						this.formData.occupation = resource.occupation || ''
						this.formData.house = resource.house !== null && resource.house !== undefined ? resource.house : null
						if (this.formData.house !== null && this.formData.house !== undefined) {
							this.houseIndex = this.formData.house
						}
						this.formData.car = resource.car !== null && resource.car !== undefined ? resource.car : null
						if (this.formData.car !== null && this.formData.car !== undefined) {
							this.carIndex = this.formData.car
						}
						this.formData.mateSelectionCriteria = resource.mateSelectionCriteria || ''
						this.formData.phone = resource.phone || ''
						this.formData.backupPhone = resource.backupPhone || ''
						
						// 加载标签（需要先加载标签列表）
						// 这里假设标签会在 loadTags 之后加载，所以需要延迟处理
						this.$nextTick(() => {
							// 加载资源关联的标签
							this.loadResourceTags()
						})
					} else {
						// 资源不存在或其他错误
						const errorMessage = res.data.message || res.data.msg || '请求的资源不存在'
						uni.showToast({
							title: errorMessage,
							icon: 'none',
							duration: 2000
						})
						// 延迟返回上一页
						setTimeout(() => {
							uni.navigateBack()
						}, 2000)
					}
				} else {
					uni.showToast({
						title: '加载资源详情失败',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 2000)
				}
			} catch (e) {
				uni.hideLoading()
			
				uni.showToast({
					title: '加载资源详情失败',
					icon: 'none'
				})
			}
		},
		// 解析地址（分离省市区和详细地址）
		parseAddress(fullAddress) {
			if (!fullAddress) return
			
			// 简单的地址解析：假设格式为 "省 市 区 详细地址"
			// 这里可以根据实际情况调整解析逻辑
			const parts = fullAddress.split(' ')
			if (parts.length >= 3) {
				// 前三个部分可能是省市区
				const regionParts = parts.slice(0, 3)
				this.addressDisplayText = regionParts.join(' ')
				this.formData.addressDetail = parts.slice(3).join(' ') || ''
				
				// 尝试匹配省市区并设置选择器
				this.matchAddressRegion(regionParts)
			} else {
				// 如果格式不符合，将整个地址作为详细地址
				this.formData.addressDetail = fullAddress
			}
		},
		// 解析户籍地（分离省市区和详细地址）
		parseDomicile(fullDomicile) {
			if (!fullDomicile) return
			
			const parts = fullDomicile.split(' ')
			if (parts.length >= 3) {
				const regionParts = parts.slice(0, 3)
				this.domicileDisplayText = regionParts.join(' ')
				this.formData.domicileDetail = parts.slice(3).join(' ') || ''
				
				// 尝试匹配省市区并设置选择器
				this.matchDomicileRegion(regionParts)
			} else {
				this.formData.domicileDetail = fullDomicile
			}
		},
		// 匹配地址省市区（简化版，实际可能需要更复杂的匹配逻辑）
		async matchAddressRegion(regionParts) {
			// 这里简化处理，实际应该根据省市区名称匹配
			// 暂时只设置显示文本，不自动选择
		},
		// 匹配户籍地省市区（简化版）
		async matchDomicileRegion(regionParts) {
			// 这里简化处理，实际应该根据省市区名称匹配
			// 暂时只设置显示文本，不自动选择
		},
		// 加载资源关联的标签
		async loadResourceTags() {
			if (!this.resourceId) return
			
			try {
				const baseUrl = process.env.NODE_ENV === 'development' 
					? 'https://api.zhongruanke.cn/api'
					: 'https://your-domain.com/api'
				
				// 调用获取资源标签ID列表的接口
				const [error, res] = await uni.request({
					url: `${baseUrl}/my-resource/tag-ids/${this.resourceId}`,
					method: 'GET'
				})
				
				if (error) {
				
					return
				}
				
				if (res.statusCode === 200 && res.data && res.data.code === 200) {
					// 后端直接返回标签ID列表
					const tagIds = res.data.data || []
					this.selectedTagIds = tagIds.filter(id => id !== null && id !== undefined)
					
				}
			} catch (e) {
			
			}
		},
		// 加载标签分类列表
		async loadCategories() {
			try {
				const baseUrl = process.env.NODE_ENV === 'development' 
					? 'https://api.zhongruanke.cn/api'  // 开发环境 - 通过网关
					: 'https://your-domain.com/api'  // 生产环境
				
				const [error, res] = await uni.request({
					url: `${baseUrl}/tag/categories`,
					method: 'GET',
					timeout: 10000
				})
				
				if (error) {
					
					return
				}
				
				if (res.statusCode === 200 && res.data && res.data.code === 200) {
					// 将后端返回的下划线字段转换为驼峰命名
					this.categoryList = (res.data.data || []).map(category => ({
						id: category.id || category.category_id,
						name: category.name || category.category_name,
						code: category.code || category.category_code,
						sortOrder: category.sortOrder || category.sort_order,
						status: category.status
					}))
				
					
					// 如果还没有选中分类，默认选中职业分类（category_id = 1）
					if (this.selectedCategoryId === null || this.selectedCategoryId === undefined) {
						// 查找职业分类（code为'occupation'或id为1）
						const occupationCategory = this.categoryList.find(cat => 
							(cat.code === 'occupation' || cat.id === 1)
						)
						if (occupationCategory) {
							this.selectedCategoryId = occupationCategory.id
						
						} else if (this.categoryList.length > 0) {
							// 如果找不到职业分类，选中第一个分类
							this.selectedCategoryId = this.categoryList[0].id
							
						}
					}
				} else {
					
				}
			} catch (e) {
				
			}
		},
		// 加载标签列表
		async loadTags() {
			try {
				this.isLoadingTags = true
				const baseUrl = process.env.NODE_ENV === 'development' 
					? 'https://api.zhongruanke.cn/api'  // 开发环境 - 通过网关
					: 'https://your-domain.com/api'  // 生产环境
				
				const [error, res] = await uni.request({
					url: `${baseUrl}/tag/list`,
					method: 'GET',
					timeout: 10000
				})
				
				if (error) {
					
					return
				}
				
				if (res.statusCode === 200 && res.data && res.data.code === 200) {
					// 直接使用后端返回的数据，不进行映射（因为Vue的响应式系统会保留原始属性）
					// 只保存有分类的标签（category_id不为null）
					this.tagList = (res.data.data || []).filter(tag => {
						const categoryId = tag.category_id !== null && tag.category_id !== undefined 
							? tag.category_id 
							: (tag.categoryId !== null && tag.categoryId !== undefined ? tag.categoryId : null)
						return categoryId !== null && categoryId !== undefined
					})
					
					
				} 
			} catch (e) {
				
			} finally {
				this.isLoadingTags = false
			}
		},
		// 选择分类
		selectCategory(categoryId) {
			this.selectedCategoryId = categoryId
		
			
			// 使用$nextTick确保DOM更新后再输出
			this.$nextTick(() => {
				
				if (this.filteredTagList.length > 0) {
					
				} else {
					
					// 调试：查看前几条标签的category_id
					if (this.tagList.length > 0) {
						
					}
				}
			})
		},
		// 切换标签选择状态
		toggleTag(tagId) {
			const index = this.selectedTagIds.indexOf(tagId)
			if (index > -1) {
				// 已选中，取消选择
				this.selectedTagIds.splice(index, 1)
			} else {
				// 未选中，添加到选中列表
				this.selectedTagIds.push(tagId)
			}
			
		},
		onGenderChange(e) {
			this.genderIndex = parseInt(e.detail.value) || 0
			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
			
		},
		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.addressDisplayText && (!this.formData.addressDetail || !this.formData.addressDetail.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
				}
				
				// 调试：打印原始值
				
				
				// 确定婚姻状态的值：优先使用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
					
				} else if (this.maritalStatusIndex !== null && this.maritalStatusIndex !== undefined && this.maritalStatusIndex >= 0) {
					const parsed = parseInt(this.maritalStatusIndex)
					marrStatusValue = isNaN(parsed) ? null : parsed
					
				} 
				
				// 处理备用手机号：保留有效值，空字符串转为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
					
					} 
				} 
				
				// 处理择偶标准：保留有效值，空字符串转为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
						
					} 
				} 
				
				// 辅助函数：安全地将值转换为整数，无效值返回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: this.buildFullAddress(this.addressDisplayText, this.formData.addressDetail),
					// 组合户籍地：省市区 + 详细地址
					domicile: this.buildFullAddress(this.domicileDisplayText, this.formData.domicileDetail),
					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
				}
				
				

				// 调用后端接口（通过网关）
				const baseUrl = process.env.NODE_ENV === 'development' 
					? 'https://api.zhongruanke.cn/api'  // 开发环境 - 通过网关
					: 'https://your-domain.com/api'  // 生产环境
				
				// 检查手机号是否已存在（检查整个my_resource表，不限制红娘）
				const phone = submitData.phone
				const backupPhone = submitData.backupPhone
				
				// 检查是否已登录
				if (!this.currentUserId) {
					uni.hideLoading()
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					return
				}
				
				// 编辑模式下跳过手机号检查（因为可能是自己的手机号）
				// 新增模式下检查手机号是否已存在
				if (!this.isEditMode) {
					// 调用检查接口
					const checkUrl = `${baseUrl}/my-resource/check-phone?phone=${encodeURIComponent(phone || '')}${backupPhone ? '&backupPhone=' + encodeURIComponent(backupPhone) : ''}`
					const [checkError, checkRes] = await uni.request({
						url: checkUrl,
						method: 'GET'
					})
					
					if (checkError) {
					
						uni.hideLoading()
						uni.showToast({
							title: '检查手机号失败，请重试',
							icon: 'none'
						})
						return
					}
					
					if (checkRes.statusCode === 200 && checkRes.data && checkRes.data.code === 200) {
						const checkResult = checkRes.data.data
						const existingResource = checkResult.existingResource
						
						// 如果发现重复的手机号，提示用户
						if (checkResult.phoneExists || checkResult.backupPhoneExists || checkResult.phoneAsBackupExists || checkResult.backupPhoneAsMainExists) {
							let message = '该手机号已经绑定资源啦'
							
							// 根据不同的检查结果，显示具体的手机号类型
							if (checkResult.phoneExists) {
								message = '该主手机号已经绑定资源啦'
							} else if (checkResult.phoneAsBackupExists) {
								message = '该主手机号已经作为备用手机号绑定资源啦'
							} else if (checkResult.backupPhoneAsMainExists) {
								message = '该备用手机号已经作为主手机号绑定资源啦'
							} else if (checkResult.backupPhoneExists) {
								message = '该备用手机号已经绑定资源啦'
							}
							
							uni.hideLoading()
							uni.showToast({
								title: message,
								icon: 'none',
								duration: 3000
							})
							return
						}
					}
				}
				
				// 根据是否为编辑模式选择不同的接口
				let url, method, successMessage
				if (this.isEditMode && this.resourceId) {
					// 编辑模式：调用更新接口
					url = `${baseUrl}/my-resource/update/${this.resourceId}`
					method = 'PUT'
					successMessage = '修改成功'
					
				} else {
					// 新增模式：调用添加接口
					url = `${baseUrl}/my-resource/add`
					method = 'POST'
					// 确保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: method,
					data: submitData,
					header: {
						'Content-Type': 'application/json'
					}
				})

				uni.hideLoading()

				if (res[1].statusCode === 200 && res[1].data.code === 200) {
					if (this.isEditMode) {
						// 编辑模式：显示修改成功
						uni.showToast({
							title: successMessage,
							icon: 'success'
						})
					} else {
						// 新增模式：获取返回的资源类型信息
						const responseData = res[1].data.data
						const resourceType = responseData && responseData.resourceType ? responseData.resourceType : '资源'
						const isUser = responseData && responseData.isUser !== undefined ? responseData.isUser : null
						
						// 根据资源类型显示不同的成功提示
						if (isUser === 0 || resourceType === '线索') {
							successMessage = '提交线索成功'
						} else if (isUser === 1 || resourceType === '资源') {
							successMessage = '添加资源成功'
						}
						
						uni.showToast({
							title: successMessage,
							icon: 'success'
						})
					}
					
					// 延迟跳转到我的资源列表页面并刷新
					setTimeout(() => {
						if (this.isEditMode) {
							// 编辑模式：直接返回上一页并刷新
							uni.navigateBack({
								success: () => {
									// 触发刷新事件
									uni.$emit('refreshResourceList')
								}
							})
						} else {
							// 新增模式：获取页面栈，检查是否已经有我的资源列表页面
							const pages = getCurrentPages()
							const myResourcesPageIndex = pages.findIndex(page => {
								return page.route && page.route.includes('matchmaker-workbench/my-resources')
							})
							
							if (myResourcesPageIndex >= 0 && myResourcesPageIndex < pages.length - 1) {
								// 如果我的资源列表页面已经在页面栈中（且不是当前页），返回到该页面
								const delta = pages.length - myResourcesPageIndex - 1
								uni.navigateBack({
									delta: delta,
									success: () => {
										// 触发刷新事件
										uni.$emit('refreshResourceList')
									}
								})
							} else {
								// 如果我的资源列表页面不在页面栈中，跳转到该页面
								uni.redirectTo({
									url: '/pages/matchmaker-workbench/my-resources',
									success: () => {
										// 触发刷新事件
										uni.$emit('refreshResourceList')
									}
								})
							}
						}
					}, 1500)
				} else {
					uni.showToast({
						title: res[1].data.message || '提交失败',
						icon: 'none',
						duration: 2000
					})
				}
			} catch (error) {
				uni.hideLoading()
			
				uni.showToast({
					title: '提交失败，请稍后重试',
					icon: 'none'
				})
			}
		},
		// 组合完整地址（省市区 + 详细地址）
		buildFullAddress(regionText, detailText) {
			let fullAddress = ''
			if (regionText && regionText.trim()) {
				fullAddress = regionText.trim()
			}
			if (detailText && detailText.trim()) {
				if (fullAddress) {
					fullAddress += ' ' + detailText.trim()
				} else {
					fullAddress = detailText.trim()
				}
			}
			return fullAddress || null
		},
		// ========== 住址省市区相关方法 ==========
		// 加载住址省份列表
		async loadAddressProvinces() {
			try {
				const provinces = await api.area.getProvinces()
				this.addressProvinces = provinces || []
				this.addressMultiArray[0] = this.addressProvinces.map(p => p.name)
				// 默认加载第一个省份的城市
				if (this.addressProvinces.length > 0) {
					await this.loadAddressCities(0)
				}
			} catch (e) {
			}
		},
		// 加载住址城市列表
		async loadAddressCities(provinceIndex) {
			const province = this.addressProvinces[provinceIndex]
			if (!province || !province.id) return
			
			try {
				const cities = await api.area.getCities(province.id)
				this.addressCities = cities || []
				this.addressMultiArray[1] = this.addressCities.map(c => c.name)
				// 默认加载第一个城市的区域
				if (this.addressCities.length > 0) {
					await this.loadAddressAreas(0)
				} else {
					this.addressMultiArray[2] = []
				}
			} catch (e) {
			
				this.addressCities = []
				this.addressMultiArray[1] = []
				this.addressMultiArray[2] = []
			}
		},
		// 加载住址区域列表
		async loadAddressAreas(cityIndex) {
			const city = this.addressCities[cityIndex]
			if (!city || !city.id) return
			
			try {
				const areas = await api.area.getAreas(city.id)
				this.addressAreas = areas || []
				this.addressMultiArray[2] = this.addressAreas.map(a => a.name)
			} catch (e) {
			
				this.addressAreas = []
				this.addressMultiArray[2] = []
			}
		},
		// 住址列变化事件
		async onAddressColumnChange(e) {
			const column = e.detail.column
			const row = e.detail.value
			
			if (column === 0) {
				// 选择了省份
				this.addressMultiIndex[0] = row
				this.addressMultiIndex[1] = 0
				this.addressMultiIndex[2] = 0
				await this.loadAddressCities(row)
			} else if (column === 1) {
				// 选择了城市
				this.addressMultiIndex[1] = row
				this.addressMultiIndex[2] = 0
				await this.loadAddressAreas(row)
			} else if (column === 2) {
				// 选择了区域
				this.addressMultiIndex[2] = row
			}
		},
		// 住址确认选择事件
		onAddressChange(e) {
			const values = e.detail.value
			this.addressMultiIndex = values
			
			// 更新显示文本
			const provinceName = this.addressMultiArray[0][values[0]] || ''
			const cityName = this.addressMultiArray[1][values[1]] || ''
			const areaName = this.addressMultiArray[2][values[2]] || ''
			
			let displayText = ''
			if (provinceName) displayText += provinceName
			if (cityName) displayText += (displayText ? ' ' : '') + cityName
			if (areaName) displayText += (displayText ? ' ' : '') + areaName
			
			this.addressDisplayText = displayText
		},
		// ========== 户籍地省市区相关方法 ==========
		// 加载户籍地省份列表
		async loadDomicileProvinces() {
			try {
				const provinces = await api.area.getProvinces()
				this.domicileProvinces = provinces || []
				this.domicileMultiArray[0] = this.domicileProvinces.map(p => p.name)
				// 默认加载第一个省份的城市
				if (this.domicileProvinces.length > 0) {
					await this.loadDomicileCities(0)
				}
			} catch (e) {
				
			}
		},
		// 加载户籍地城市列表
		async loadDomicileCities(provinceIndex) {
			const province = this.domicileProvinces[provinceIndex]
			if (!province || !province.id) return
			
			try {
				const cities = await api.area.getCities(province.id)
				this.domicileCities = cities || []
				this.domicileMultiArray[1] = this.domicileCities.map(c => c.name)
				// 默认加载第一个城市的区域
				if (this.domicileCities.length > 0) {
					await this.loadDomicileAreas(0)
				} else {
					this.domicileMultiArray[2] = []
				}
			} catch (e) {
				
				this.domicileCities = []
				this.domicileMultiArray[1] = []
				this.domicileMultiArray[2] = []
			}
		},
		// 加载户籍地区域列表
		async loadDomicileAreas(cityIndex) {
			const city = this.domicileCities[cityIndex]
			if (!city || !city.id) return
			
			try {
				const areas = await api.area.getAreas(city.id)
				this.domicileAreas = areas || []
				this.domicileMultiArray[2] = this.domicileAreas.map(a => a.name)
			} catch (e) {
				
				this.domicileAreas = []
				this.domicileMultiArray[2] = []
			}
		},
		// 户籍地列变化事件
		async onDomicileColumnChange(e) {
			const column = e.detail.column
			const row = e.detail.value
			
			if (column === 0) {
				// 选择了省份
				this.domicileMultiIndex[0] = row
				this.domicileMultiIndex[1] = 0
				this.domicileMultiIndex[2] = 0
				await this.loadDomicileCities(row)
			} else if (column === 1) {
				// 选择了城市
				this.domicileMultiIndex[1] = row
				this.domicileMultiIndex[2] = 0
				await this.loadDomicileAreas(row)
			} else if (column === 2) {
				// 选择了区域
				this.domicileMultiIndex[2] = row
			}
		},
		// 户籍地确认选择事件
		onDomicileChange(e) {
			const values = e.detail.value
			this.domicileMultiIndex = values
			
			// 更新显示文本
			const provinceName = this.domicileMultiArray[0][values[0]] || ''
			const cityName = this.domicileMultiArray[1][values[1]] || ''
			const areaName = this.domicileMultiArray[2][values[2]] || ''
			
			let displayText = ''
			if (provinceName) displayText += provinceName
			if (cityName) displayText += (displayText ? ' ' : '') + cityName
			if (areaName) displayText += (displayText ? ' ' : '') + areaName
			
			this.domicileDisplayText = displayText
		}
	}
}
</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;
			}
		}
		
		.category-buttons {
			display: flex;
			flex-wrap: wrap;
			gap: 12rpx;
			margin-bottom: 20rpx;
			
			.category-btn {
				padding: 10rpx 20rpx;
				background: #F8F8F8;
				border: 2rpx solid #E0E0E0;
				border-radius: 20rpx;
				transition: all 0.3s;
				
				&.active {
					background: linear-gradient(135deg, #9C27B0 0%, #BA68C8 100%);
					border-color: #9C27B0;
					
					.category-btn-text {
						color: #FFFFFF;
						font-weight: 600;
					}
				}
				
				.category-btn-text {
					font-size: 24rpx;
					color: #666;
				}
			}
		}
		
		.tags-container {
			display: flex;
			flex-wrap: wrap;
			gap: 15rpx;
			margin-top: 10rpx;
			min-height: 400rpx; /* 设置最小高度，确保空间不变 */
			align-content: flex-start; /* 标签从顶部开始排列 */
			
			.tag-item {
				padding: 12rpx 24rpx;
				background: #F8F8F8;
				border: 2rpx solid #E0E0E0;
				border-radius: 24rpx;
				font-size: 26rpx;
				color: #666;
				transition: all 0.3s;
				flex-shrink: 0; /* 防止标签被压缩 */
				
				&.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;
				text-align: center;
				width: 100%;
				min-height: 400rpx; /* 加载时也保持固定高度 */
				display: flex;
				align-items: center;
				justify-content: center;
			}
			
			.tag-empty {
				padding: 20rpx;
				color: #999;
				font-size: 26rpx;
				text-align: center;
				width: 100%;
				min-height: 400rpx; /* 空状态时也保持固定高度 */
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

	.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-text {
			color: #333;
			flex: 1;
		}

		.picker-arrow {
			font-size: 24rpx;
			color: #999;
		}
	}
	
	.address-detail-input {
		margin-top: 15rpx;
	}
}

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

