<template>
	<view class="container">
		<view class="header">
			<view class="title">闲置农房信息录入</view>
		</view>
		
		<view class="form-container">
			<uv-form labelPosition="left" :model="form" :rules="rules" ref="form" labelWidth="80" labelStyle="font-size:28rpx;">
				
				<!-- 必填项 -->
				<view class="section-title">基本信息（必填）</view>
				
				<!-- 1. 出租/流转 -->
				<uv-form-item label="类型" prop="type" required>
					<uv-radio-group v-model="form.type" placement="row" @change="debounceSaveFormData">
						<uv-radio name="rent" label="出租"></uv-radio>
						<uv-radio name="transfer" customStyle="margin-left:30rpx;" label="流转"></uv-radio>
					</uv-radio-group>
				</uv-form-item>
				
				<!-- 2. 地址 -->
				<uv-form-item label="地址" prop="address" required @click="handleAddressSelect()">
					<uv-input v-model="form.address" @click="handleAddressSelect()" disabled disabledColor="#ffffff" placeholder="请选择房屋位置" border="none">
					</uv-input>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item>
				
				<!-- 3. 联系人和电话 -->
				<uv-form-item label="联系人" prop="contactName" required>
					<uv-input v-model="form.contactName" type="text" placeholder="请输入联系人姓名" customStyle="border-radius: 5px;margin-top:5px;background-color: #f5f5f5;padding:5px 10px;" @input="debounceSaveFormData"></uv-input>
				</uv-form-item>
				
				<uv-form-item label="联系电话" prop="contactPhone" required>
					<uv-input v-model="form.contactPhone" type="number" placeholder="请输入联系电话" customStyle="border-radius: 5px;margin-top:5px;background-color: #f5f5f5;padding:5px 10px;" @input="debounceSaveFormData"></uv-input>
				</uv-form-item>
				
				<!-- 4. 房屋状况 -->
				<uv-form-item label="房屋状况" prop="houseCondition" required @click="handleHouseConditionSelect()">
					<uv-input v-model="form.houseConditionName" @click="handleHouseConditionSelect()" disabled disabledColor="#ffffff" placeholder="请选择房屋状况" border="none">
					</uv-input>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item>
				
				<!-- 5. 产权证照片 -->
				<uv-form-item label="产权证照片" labelWidth="250" prop="propertyImages" labelPosition="top" required>
					<view class="upload-tip">请上传房产证、土地证或不动产权证照片</view>
					<uv-upload customStyle="margin-top:20rpx;" :fileList="form.propertyImages" @afterRead="afterPropertyRead" @delete="deletePropertyPic" name="1"
						multiple :maxCount="5"></uv-upload>
				</uv-form-item>
				
				<!-- 6. 产权面积 -->
				<uv-form-item label="房屋面积" prop="houseArea" required>
					<view class="input-with-unit">
						<uv-input v-model="form.houseArea" type="digit" placeholder="请输入房屋面积" customStyle="border-radius: 5px;margin-top:5px;background-color: #f5f5f5;padding:5px 10px;" @input="debounceSaveFormData"></uv-input>
						<text class="unit">平米</text>
					</view>
					<view class="input-tip">请录入房屋证或不动产权证登记面积</view>
				</uv-form-item>
				
				<uv-form-item label="土地面积" prop="landArea" required>
					<view class="input-with-unit">
						<uv-input v-model="form.landArea" type="digit" placeholder="请输入土地面积" customStyle="border-radius: 5px;margin-top:5px;background-color: #f5f5f5;padding:5px 10px;" @input="debounceSaveFormData"></uv-input>
						<text class="unit">平米</text>
					</view>
					<view class="input-tip">请录入土地使用证或不动产权证面积</view>
				</uv-form-item>
				
				<!-- 7. 房屋正面照片 -->
				<uv-form-item label="房屋正面照片" labelWidth="250" prop="frontImages" labelPosition="top" required>
					<view class="upload-tip">作为封面展示，建议拍摄房屋正面全貌</view>
					<uv-upload customStyle="margin-top:20rpx;" :fileList="form.frontImages" @afterRead="afterFrontRead" @delete="deleteFrontPic" name="1"
						multiple :maxCount="3"></uv-upload>
				</uv-form-item>
				
				<!-- 8. 房屋视频 -->
				<uv-form-item label="房屋视频" labelWidth="250" prop="videos" labelPosition="top" required>
					<view class="upload-tip">请上传房屋内部和外部视频，时长不超过1分钟，最多上传2个视频</view>
					<uv-upload customStyle="margin-top:20rpx;" accept="video" :fileList="form.videos" @afterRead="afterVideoRead" @delete="deleteVideoPic" name="1"
						multiple :maxCount="2"></uv-upload>
				</uv-form-item>
				
				<!-- 9. 价格 -->
				<uv-form-item label="价格" prop="price" required>
					<view class="price-container">
						<uv-input v-model="form.price" type="digit" placeholder="请输入价格" customStyle="border-radius: 5px;margin-top:5px;background-color: #f5f5f5;padding:5px 10px;flex:1;" @input="debounceSaveFormData"></uv-input>
						<text class="price-unit" v-if="form.type === 'rent'">元/年</text>
						<text class="price-unit" v-else-if="form.type === 'transfer'">万元</text>
						<text class="price-unit" v-else>元</text>
					</view>
					<view class="input-tip">请输入数字，支持小数点后两位</view>
				</uv-form-item>
				
				<!-- 分类标识 -->
				<uv-form-item label="分类标识" prop="classId" @click="handleClass()">
					<uv-input v-model="form.className" @click="handleClass()" disabled disabledColor="#ffffff" placeholder="选择分类标识" border="none">
					</uv-input>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item>
				
				<!-- 选填项 -->
				<view class="section-title">详细信息（选填）</view>
				
				<!-- 10. 可用菜地 -->
				<uv-form-item label="可用菜地" prop="vegetableGarden">
					<view class="input-with-unit">
						<uv-input v-model="form.vegetableGarden" type="digit" placeholder="请输入菜地面积" customStyle="border-radius: 5px;margin-top:5px;background-color: #f5f5f5;padding:5px 10px;" @input="debounceSaveFormData"></uv-input>
						<text class="unit">平米</text>
					</view>
				</uv-form-item>
				
				<!-- 11. 房屋亮点 -->
				<uv-form-item label="房屋亮点" prop="highlights" labelPosition="top">
					<view class="tags-container">
						<view 
							class="tag-item" 
							:class="{ 'tag-selected': form.highlights.includes(item) }"
							v-for="item in highlightOptions" 
							:key="item"
							@click="toggleHighlight(item)"
						>
							{{item}}
						</view>
					</view>
				</uv-form-item>
				
				<!-- 12. 不利因素 -->
				<uv-form-item label="不利因素" prop="disadvantages" labelPosition="top">
					<view class="tags-container">
						<view 
							class="tag-item disadvantage-tag" 
							:class="{ 'tag-selected': form.disadvantages.includes(item) }"
							v-for="item in disadvantageOptions" 
							:key="item"
							@click="toggleDisadvantage(item)"
						>
							{{item}}
						</view>
					</view>
				</uv-form-item>
				
				<!-- 13. 房屋介绍 -->
				<uv-form-item label="房屋介绍" prop="description" labelPosition="top">
					<uv-input 
						v-model="form.description" 
						type="textarea" 
						placeholder="请详细介绍房屋情况、周边环境等" 
						customStyle="border-radius: 5px;margin-top:5px;background-color: #f5f5f5;padding:10px;"
						:autoHeight="true"
						:maxlength="500"
						@input="debounceSaveFormData"
					></uv-input>
				</uv-form-item>
				
				<uv-form-item>
					<uv-button type="primary" text="提交信息" customStyle="margin-top: 30px;background-color: #1EC77A;border-radius: 30px;" @click="submit"></uv-button>
				</uv-form-item>
			</uv-form>
		</view>
		
		<!-- 房屋状况选择器 -->
		<uv-picker ref="houseConditionPicker" :columns="houseConditionColumns" @confirm="confirmHouseCondition"></uv-picker>
		
		<!-- 分类选择器 -->
		<uv-picker ref="picker" :columns="columns" @confirm="confirm"></uv-picker>
	</view>
</template>

<script>
	import { saveOrUpdateHouse, houseType } from "@/common/api.js"
	import formStorage from "@/utils/formStorage.js"
	
	export default {
			data() {
				return {
					formKey: 'farmhouse_form', // 表单存储唯一标识
					saveTimer: null, // 防抖定时器
					commonClass: '', // 所属分类ID
				form: {
					type: '', // 出租/流转
					address: '', // 地址
					contactName: '', // 联系人
					contactPhone: '', // 联系电话
					houseCondition: '', // 房屋状况ID
					houseConditionName: '', // 房屋状况名称
					propertyImages: [], // 产权证照片
					houseArea: '', // 房屋面积
					landArea: '', // 土地面积
					frontImages: [], // 房屋正面照片
					videos: [], // 房屋视频
					price: '', // 价格
					longitude: '', // 经度
					latitude: '', // 纬度
					vegetableGarden: '', // 可用菜地
					highlights: [], // 房屋亮点
					disadvantages: [], // 不利因素
					description: '', // 房屋介绍
					classId: '', // 分类标识
					className: '' // 分类名称
				},
				houseConditionColumns: [
					['老旧房屋', '装修较好可拎包入住', '新房']
				],
				highlightOptions: [
					'靠河', '靠山', '通自来水', '通天然气', '近场镇或城市', 
					'双车道到家', '精装修', '四合院', '周边无坟墓', '周边无电线塔'
				],
				disadvantageOptions: [
					'可见坟墓', '周边有电塔', '非正常死亡'
				],
				columns: [], // 分类选择器数据
				houseTypeList: [], // 分类列表
				rules: {
					type: [
						{ required: true, message: '请选择出租或流转', trigger: ['blur', 'change'] }
					],
					address: [
						{ required: true, message: '请选择房屋地址', trigger: ['blur', 'change'] }
					],
					contactName: [
						{ required: true, message: '请输入联系人姓名', trigger: ['blur', 'change'] }
					],
					contactPhone: [
						{ required: true, message: '请输入联系电话', trigger: ['blur', 'change'] },
						{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: ['blur', 'change'] }
					],
					houseCondition: [
						{ required: true, message: '请选择房屋状况', trigger: ['blur', 'change'] }
					],
					houseArea: [
						{ required: true, message: '请输入房屋面积', trigger: ['blur', 'change'] },
						{ pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的数字格式', trigger: ['blur', 'change'] }
					],
					landArea: [
						{ required: true, message: '请输入土地面积', trigger: ['blur', 'change'] },
						{ pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的数字格式', trigger: ['blur', 'change'] }
					],
					price: [
						{ required: true, message: '请输入价格', trigger: ['blur', 'change'] },
						{ pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的价格格式', trigger: ['blur', 'change'] }
					],
					classId: [
						{ required: true, message: '请选择分类标识', trigger: ['blur', 'change'] }
					]
				}
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		onLoad(options) {
			// 设置页面标题
			uni.setNavigationBarTitle({
				title: '闲置农房录入'
			})
			
			// 接收传递的commonClass参数
			if(options.commonClass) {
				this.commonClass = options.commonClass
			}
			
			// 如果是编辑模式，设置classId用于回显
			if(options.classId) {
				this.form.classId = options.classId
			}
			
			// 初始化分类数据
			this.onHouseType()
			
			// 恢复表单数据
			this.restoreFormData()
		},
		onUnload() {
			// 页面卸载时保存数据
			this.saveFormData()
			// 清除定时器
			if (this.saveTimer) {
				clearTimeout(this.saveTimer)
			}
		},
		methods: {
			// 恢复表单数据
			restoreFormData() {
				const savedData = formStorage.getFormData(this.formKey)
				if (savedData) {
					// 合并保存的数据到表单
					this.form = { ...this.form, ...savedData }
				}
			},
			
			// 保存表单数据
			saveFormData() {
				formStorage.saveFormData(this.formKey, this.form)
			},
			
			// 防抖保存表单数据
			debounceSaveFormData() {
				clearTimeout(this.saveTimer)
				this.saveTimer = setTimeout(() => {
					this.saveFormData()
				}, 1000)
			},
			// 获取分类数据
			onHouseType(){
				let that = this
				houseType({}).then(response=>{
					let arr=[]
					that.houseTypeList = response.result
					response.result.forEach(items=>{
						arr.push(items.title)
						// 数据回显：如果当前classId匹配，设置className
						if(items.id == that.form.classId){
							that.form.className = items.title
						}
					})
					that.columns[0]=arr
				}).catch(error=>{
					
				})
			},
			
			// 地址选择
			handleAddressSelect() {
				const that = this;
				wx.chooseLocation({
					success: function (res) {
						console.log('选择的位置：', res);
						that.form.longitude = res.longitude
						that.form.latitude = res.latitude
						that.form.address = res.address
					}
				})
			},
			
			// 房屋状况选择
			handleHouseConditionSelect() {
				this.$refs.houseConditionPicker.open();
			},
			
			confirmHouseCondition(e) {
				const { indexs, value } = e;
				this.form.houseCondition = value[0]; // 修改：直接使用选择的值而不是索引
				this.form.houseConditionName = value[0];
				// 选择后保存表单数据
				this.debounceSaveFormData()
			},
			
			// 分类标识选择
			handleClass() {
				this.$refs.picker.open();
			},
			
			confirm(e) {
				let that = this
				let {indexs,value,values} = e
				that.form.classId = that.houseTypeList[indexs[0]].id;
				that.form.className = that.houseTypeList[indexs[0]].title;
				// 选择后保存表单数据
				that.debounceSaveFormData()
			},
			
			// 产权证照片上传
			async afterPropertyRead(e) {
				let self = this
				e.file.forEach(file => {
					self.$Oss.ossUpload(file.url).then(url => {
						self.form.propertyImages.push({
							url
						})
						// 上传完成后保存表单数据
						self.debounceSaveFormData()
					})
				})
			},
			
			deletePropertyPic(event) {
				this.form.propertyImages.splice(event.index, 1)
				// 删除后保存表单数据
				this.debounceSaveFormData()
			},
			
			// 房屋正面照片上传
			async afterFrontRead(e) {
				let self = this
				e.file.forEach(file => {
					self.$Oss.ossUpload(file.url).then(url => {
						self.form.frontImages.push({
							url
						})
						// 上传完成后保存表单数据
						self.debounceSaveFormData()
					})
				})
			},
			
			deleteFrontPic(event) {
				this.form.frontImages.splice(event.index, 1)
				// 删除后保存表单数据
				this.debounceSaveFormData()
			},
			
			// 视频上传
			async afterVideoRead(e) {
				let self = this
				for (let file of e.file) {
					try {
						// 检查视频时长
						const duration = await this.getVideoDuration(file.url)
						if (duration > 60) {
							uni.showToast({
								title: '视频时长不能超过1分钟',
								icon: 'none'
							})
							continue // 跳过这个视频
						}
						
						self.$Oss.ossUpload(file.url).then(url => {
							self.form.videos.push({
								url
							})
							// 上传完成后保存表单数据
							self.debounceSaveFormData()
						})
					} catch (error) {
						console.error('视频处理失败：', error)
						// 如果获取时长失败，仍然允许上传
						self.$Oss.ossUpload(file.url).then(url => {
							self.form.videos.push({
								url
							})
							// 上传完成后保存表单数据
							self.debounceSaveFormData()
						})
					}
				}
			},
			
			// 获取视频时长的辅助方法
			getVideoDuration(videoUrl) {
				return new Promise((resolve, reject) => {
					// #ifdef MP-WEIXIN
					uni.getVideoInfo({
						src: videoUrl,
						success: (res) => {
							resolve(res.duration)
						},
						fail: (err) => {
							reject(err)
						}
					})
					// #endif
					
					// #ifdef APP-PLUS
					plus.io.getVideoInfo({
						filePath: videoUrl,
						success: (res) => {
							resolve(res.duration)
						},
						fail: (err) => {
							reject(err)
						}
					})
					// #endif
					
					// #ifdef H5
					// H5环境暂不支持视频时长检测，直接通过
					resolve(0)
					// #endif
				})
			},
			
			deleteVideoPic(event) {
				this.form.videos.splice(event.index, 1)
				// 删除后保存表单数据
				this.debounceSaveFormData()
			},
			
			// 切换房屋亮点
			toggleHighlight(item) {
				const index = this.form.highlights.indexOf(item);
				if (index > -1) {
					this.form.highlights.splice(index, 1);
				} else {
					this.form.highlights.push(item);
				}
				// 选择后保存表单数据
				this.debounceSaveFormData()
			},
			
			// 切换不利因素
			toggleDisadvantage(item) {
				const index = this.form.disadvantages.indexOf(item);
				if (index > -1) {
					this.form.disadvantages.splice(index, 1);
				} else {
					this.form.disadvantages.push(item);
				}
				// 选择后保存表单数据
				this.debounceSaveFormData()
			},
			
			// 提交表单
			submit() {
				this.$refs.form.validate().then(res => {
					// 验证必填的图片和视频
					if (this.form.propertyImages.length === 0) {
						uni.showToast({
							title: '请上传产权证照片',
							icon: 'none'
						});
						return;
					}
					
					if (this.form.frontImages.length === 0) {
						uni.showToast({
							title: '请上传房屋正面照片',
							icon: 'none'
						});
						return;
					}
					
					if (this.form.videos.length === 0) {
						uni.showToast({
							title: '请上传房屋视频',
							icon: 'none'
						});
						return;
					}
					
					// 构建与index.vue兼容的提交参数
					const params = {
						userId: uni.getStorageSync('userInfo')?.id || "",
						id: "", // 新增数据，无ID
						classId: this.form.classId, // 使用分类标识
						commonClass: this.commonClass, // 所属分类
						address: this.form.address, // 地址
						homeAge: "", // 户主年龄 - 农房录入无此字段
						homeAz: "", // 是否经过安置 - 默认否
						homeBian: this.form.highlights.join(','), // 房屋周边 - 使用亮点代替
						homeBjsx: "", // 报建手续 - 农房录入无此字段
						homeCai: this.form.vegetableGarden || "", // 菜地面积
						homeCat: "", // 停车 - 农房录入无此字段
						homeGz: "", // 房屋主体是否改造 - 农房录入无此字段
						homeHb: "", // 房屋朝向及海拔 - 农房录入无此字段
						homeBz: this.form.description, // 备注 - 使用房屋介绍
						homeJg: this.form.houseCondition, // 房屋结构 - 使用房屋状况
						homeJl: "", // 距离场镇距离 - 农房录入无此字段
						homeJt: "", // 交通 - 农房录入无此字段
						homeJtzy: "", // 户主家庭职业 - 农房录入无此字段
						homeMi: "", // 面积 - 使用房屋面积
						homeMj: this.form.houseArea, // 房屋面积
						homeMoney: "", // 佣金 - 农房录入无此字段
						homeNo: "", // 房屋编号 - 农房录入无此字段
						homeNum: "1", // 房间数量 - 农房录入无此字段
						homePay: "", // 付款方式及押金 - 农房录入无此字段
						homePj: "", // 邻居对房东评价 - 农房录入无此字段
						homeSd: "", // 水电气网 - 农房录入无此字段
						homeShjl: "", // 距离成都西三环 - 农房录入无此字段
						homeSw: this.form.disadvantages.join(','), // 非正常死亡 - 显示不利因素信息
						homeTf: "", // 府市民云房屋信息档案查询 - 农房录入无此字段
						homeTime: "", // 租期 - 农房录入无此字段
						homeType: this.form.type === 'rent' ? '出租' : '流转', // 户型 - 使用类型
						homeYs: "", // 钥匙 - 默认无
						homeYzmj: this.form.landArea, // 院子总面积 - 使用土地面积
						homeZy: this.form.disadvantages.join(','), // 坟包及电塔 工厂噪音 - 使用不利因素
						iconName: "闲置农房", // 热点名称
						iconTitle: this.form.highlights.join(','), // 标签 - 使用亮点
						num: "0", // 浏览量 - 默认0
						price: this.form.price, // 价格
						timeGo: "", // 年限 - 农房录入无此字段
						title: `${this.form.type === 'rent' ? '出租' : '流转'}-${this.form.address.split('市')[1] || this.form.address}`, // 标题 - 自动生成
						unit: this.form.type === 'rent' ? '元/年' : '万元', // 单位
						image: this.form.frontImages.map(item => item.url).join(','), // 图片 - 使用正面照片
						iconImage: "", // 左上角图标
						homeImage: this.form.propertyImages.map(item => item.url).join(','), // 产权证照片
						homeMp4: this.form.videos.map(item => item.url).join(','), // 视频
						latitude: this.form.latitude,
						longitude: this.form.longitude,
						// 新增字段用于标识农房
						category: 'farmhouse',
						contactName: this.form.contactName,
						contactPhone: this.form.contactPhone
					};
					
					console.log('农房提交参数：', params);
					
					uni.showLoading({
						title: '提交中...'
					});
					
					// 调用统一API
			saveOrUpdateHouse(params).then(response => {
				uni.hideLoading();
				// 提交成功后清除本地存储的表单数据
				formStorage.removeFormData(this.formKey);
				uni.showToast({
					title: response.message || '提交成功',
					icon: 'success'
				});
				setTimeout(() => {
					uni.redirectTo({
						url: "/pages_subpack/successful-apply/index"
					});
				}, 2000);
			}).catch(error => {
						uni.hideLoading();
						uni.showToast({
							title: error.message || '提交失败',
							icon: 'none'
						});
						console.error('农房提交失败：', error);
					});
					
				}).catch(errors => {
					console.log('表单验证失败：', errors);
                    uni.showToast({
                        title: '请补全必填项',
                        icon: 'none'
                    });
				});
			}
		}
	}
</script>

<style scoped>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}
	
	.header {
		background: linear-gradient(135deg, #1EC77A 0%, #4CAF50 100%);
		padding: 40rpx 40rpx 60rpx;
		color: white;
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
		text-align: center;
	}
	
	.form-container {
		background: white;
		margin: -30rpx 20rpx 20rpx;
		border-radius: 20rpx;
		padding: 40rpx;
		box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin: 40rpx 0 30rpx;
		padding-left: 20rpx;
		border-left: 6rpx solid #1EC77A;
	}
	
	.section-title:first-child {
		margin-top: 0;
	}
	
	.input-with-unit {
		display: flex;
		align-items: center;
		gap: 10rpx;
	}
	
	.unit {
		font-size: 26rpx;
		color: #666;
		margin-left: 10rpx;
	}
	
	.input-tip {
		font-size: 22rpx;
		color: #999;
		margin-top: 10rpx;
		line-height: 1.4;
	}
	
	.upload-tip {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 10rpx;
		line-height: 1.5;
	}
	
	.price-container {
		display: flex;
		align-items: center;
		gap: 10rpx;
	}
	
	.price-unit {
		font-size: 26rpx;
		color: #1EC77A;
		font-weight: bold;
		margin-left: 10rpx;
	}
	
	.tags-container {
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
		margin-top: 20rpx;
	}
	
	.tag-item {
		padding: 15rpx 25rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 25rpx;
		font-size: 24rpx;
		color: #666;
		background: #f9f9f9;
		transition: all 0.3s ease;
	}
	
	.tag-item.tag-selected {
		border-color: #1EC77A;
		background: #1EC77A;
		color: white;
	}
	
	.disadvantage-tag.tag-selected {
		border-color: #ff4757;
		background: #ff4757;
		color: white;
	}
</style>