<template>
	<view class="page">
		<navbar :title="isEdit ? '编辑租房' : '发布租房'" leftClick @leftClick="$utils.navigateBack" />
		
		
		<view class="form">
			<view class="help-issue">
				<text>租房标题</text>
				<text style="color: #BD3624;">*</text>
			</view>
			<view class="form-sheet-cell">
				<input type="text" class="title-input" v-model="form.title"/>
			</view>
			
			<uv-cell
			title="租房地点"
			rightIconStyle="fontSize: 30rpx;"
			:value="form.address || '请选择租房地点'"
			@click="selectAddr"
			isLink
			></uv-cell>
			
			<uv-cell
			title="朝向"
			rightIconStyle="fontSize: 30rpx;"
			:value="form.face || '请选择朝向'"
			@click="openPicker('face')"
			isLink
			></uv-cell>
			
			<uv-cell
			title="装修"
			rightIconStyle="fontSize: 30rpx;"
			:value="form.decoration || '请选择装修'"
			@click="openPicker('decoration')"
			isLink
			></uv-cell>
			
			<!-- <uv-cell
			title="楼层"
			rightIconStyle="fontSize: 30rpx;"
			value="请选择楼层"
			isLink
			></uv-cell> -->
			
			<!-- <view class="form-sheet-cell">
				<view class="label">
					租房地点
				</view>
				<view class="price">
					<input placeholder="请输入租房地点" v-model="form.address" />
				</view>
			</view> -->
			
			<view class="form-sheet-cell">
				<view class="label">
					楼层
				</view>
				<view class="price">
					<input placeholder="请输入楼层（1楼）" v-model="form.floor" />
				</view>
			</view>
			
			<view class="form-sheet-cell">
				<view class="label">
					户型
				</view>
				<view class="price">
					<input placeholder="请输入户型（三室一厅）" v-model="form.home" />
				</view>
			</view>
			
			<view class="form-sheet-cell">
				<view class="label">
					付款方式
				</view>
				<view class="price">
					<input placeholder="请输入付款方式（押一付三）" v-model="form.payment" />
				</view>
			</view>
			
			<view class="form-sheet-cell">
				<view class="label">
					租金/月
				</view>
				<view class="price">
					<input placeholder="请输入租金" type="text" v-model="form.money" />
				</view>
			</view>
			
			<view class="form-sheet-cell">
				<view class="label">
					面积
				</view>
				<view class="price">
					<input placeholder="请输入面积（平方米）" type="number" v-model="form.crm" />
				</view>
			</view>
			
			
			<view class="form-sheet-cell">
				<view class="label">
					看房
				</view>
				<uv-radio-group v-model="form.showings">
					<view class="price">
						<uv-radio
							:customStyle="{margin: '8px'}"
							iconSize="30rpx"
							size="40rpx"
							labelSize="26rpx"
							:label="t.name" 
							v-for="(t, i) in showingsRadio"
							:key="i"
							:name="t.name">
						</uv-radio>
					</view>
				</uv-radio-group>
			</view>
			<view class="form-sheet-cell">
				<view class="label">
					电梯
				</view>
				<uv-radio-group v-model="form.lift">
					<view class="price">
						<uv-radio
							:customStyle="{margin: '8px'}"
							iconSize="30rpx"
							size="40rpx"
							labelSize="26rpx"
							:label="t.name" 
							:name="t.name"
							v-for="(t, i) in liftRadio"
							:key="i">
						</uv-radio>
					</view>
				</uv-radio-group>
			</view>
			
			<view class="form-sheet-cell">
				<view class="label">
					交付
				</view>
				<uv-radio-group v-model="form.deliver">
					<view class="price">
						<uv-radio
							:customStyle="{margin: '8px'}" 
							iconSize="30rpx"
							size="40rpx"
							labelSize="26rpx"
							:label="t.name" 
							:name="t.name"
							v-for="(t, i) in deliverRadio"
							:key="i">
						</uv-radio>
					</view>
				</uv-radio-group>
			</view>
			
			<view class="form-sheet-cell">
				<view class="label">
					联系电话
				</view>
				<input placeholder="请输入联系电话" v-model="form.phone" />
			</view>
			
			<view class="form-sheet-cell">
				<view class="label">
					备注
				</view>
				<input placeholder="请输入备注" v-model="form.titleSub" />
			</view>
			
			<view class="images box">
				<view class="">
					精选照片
				</view>
				<uv-upload 
				:fileList="fileList" 
				:maxCount="imageMax" 
				multiple 
				width="150rpx" 
				height="150rpx"
				@delete="deleteImage"
				@afterRead="afterRead"
				:previewFullImage="true"></uv-upload>
			</view>
			
			<view class="category">
				<view class="title">
					选择地区
				</view>
				<view class="tagList">
					<view 
					:class="{act : t.id == form.addId}"
					@click="form.addId = t.id"
					v-for="(t, i) in cityList"
					:key="i">
						{{ t.name }}
					</view>
				</view>
			</view>
			
			<!-- <view class="">
				<uv-textarea 
				v-model="form.content" 
				count 
				:maxlength="300" 
				autoHeight
				placeholder="请输入详细介绍"></uv-textarea>
			</view> -->
			
			<uv-picker 
			ref="picker"
			:columns="columns" 
			@confirm="pickerConfirm"></uv-picker>
			
			<view class="uni-color-btn"
			@click="submit">
				{{ isEdit ? '保存修改' : '发布' }}
			</view>
			
			<!-- 编辑模式下显示删除按钮 -->
			<view v-if="isEdit" class="delete-btn"
			@click="deleteRenting">
				删除租房
			</view>
		</view>
	</view>
</template>

<script>
	import { Position } from '@/utils/position.js'
	import { mapState } from 'vuex'
	import { subscribeBeforePublish } from '@/utils/subscribeMessage.js'
	export default {
		data() {
			return {
				rentingId: '', // 租房ID，用于编辑模式
				isEdit: false, // 是否为编辑模式
				form : {
					addId : '',//地区id
					address : '',//地址
					crm : '',//面积
					showings : '随时可看',//看房
					face : '',
					lift : '有',
					deliver : '整租',
					floor : '',
					decoration : '',
					title: '', // 租房标题
					home: '', // 户型
					payment: '', // 付款方式
					money: '', // 租金
					phone: '', // 联系电话
					titleSub: '', // 备注
					latitude: '', // 纬度
					longitude: '', // 经度
				},
				showingsRadio : [//看房
					{
						name : '随时可看',
					},
					{
						name : '电话预约',
					},
				],
				liftRadio : [
					{
						name : '有',
					},
					{
						name : '无',
					},
				],
				deliverRadio : [
					{
						name : '整租',
					},
					{
						name : '合租',
					},
				],
				fileList : [],
				imageMax : 9,
				picker : {
					face : [
						'朝东',
						'朝南',
						'朝西',
						'朝北',
					],
					decoration : [
						'精装',
						'毛胚',
					],
				},
				pickerKey : '',
			}
		},
		onLoad(options) {
			// 检查是否是编辑模式
			if (options.id) {
				this.rentingId = options.id
				this.isEdit = true
				this.getRentingDetail()
			} else {
				// 新增模式，设置默认地区
				if (this.cityList && this.cityList.length > 0) {
					this.form.addId = this.cityList[0].id
				}
			}
		},
		computed : {
			columns(){
				return [this.picker[this.pickerKey]]
			},
			...mapState(['cityList', 'category']),
		},
		watch: {
			// 监听cityList变化，用于处理异步加载的城市数据
			cityList: {
				handler(newVal) {
					if (newVal && newVal.length > 0 && !this.isEdit && !this.form.addId) {
						this.form.addId = newVal[0].id
					}
				},
				immediate: true
			}
		},
		methods: {
			// 获取租房详情数据
			getRentingDetail() {
				this.$api('getRentDetail', { id: this.rentingId }, res => {
					if (res.code == 200) {
						const data = res.result
						
						// 回显基本信息
						this.form = {
							...this.form,
							title: data.title || '',
							address: data.address || '',
							face: data.face || '',
							decoration: data.decoration || '',
							floor: data.floor || '',
							home: data.home || '',
							payment: data.payment || '',
							money: data.money || '',
							crm: data.crm || '',
							showings: data.showings || '随时可看',
							lift: data.lift || '有',
							deliver: data.deliver || '整租',
							phone: data.phone || '',
							titleSub: data.titleSub || '',
							addId: data.addId || (this.cityList.length > 0 ? this.cityList[0].id : ''),
							latitude: data.latitude || '',
							longitude: data.longitude || '',
						}
						
						// 回显图片
						if (data.image) {
							const images = data.image.split(',').filter(img => img.trim())
							this.fileList = images.map(url => ({ url: url.trim() }))
						}
					} else {
						uni.showToast({
							title: res.msg || '获取租房信息失败',
							icon: 'none'
						})
					}
				})
			},
			
			openPicker(key){
				this.pickerKey = key
				this.$refs.picker.open()
			},
			pickerConfirm(e){
				this.form[this.pickerKey] = e.value[0]
			},
			deleteImage(e){
				this.fileList.splice(e.index, 1)
			},
			afterRead(e){
				let self = this
				e.file.forEach(file => {
					self.$Oss.ossUpload(file.url).then(url => {
						self.fileList.push({
							url
						})
					})
				})
			},
			//地图上选择地址
			selectAddr() {
				Position.selectAddress(this.form.latitude || 0, this.form.longitude || 0, res => {
					//经纬度信息
					this.form.latitude = res.latitude
					this.form.longitude = res.longitude
					if (res.name) {
						return this.form.address = res.name
					}
					this.form.address = ''
				})
			},
			// 提交
			async submit(){
				
				if (this.$utils.verificationAll(this.form, {
						title: '请输入标题',
						address : '请选择租房地点',
						face : '请选择朝向',
						decoration : '请选择装修',
						floor : '请输入楼层',
						home : '请输入户型',
						payment : '请输入付款方式',
						money : '请输入租金',
						crm : '请输入面积',
						showings : '请选择看房',
						lift : '请选择电梯',
						deliver : '请选择交付方式',
						phone: '请输入联系电话',
					})) {
					return
				}
				
				if(this.fileList.length == 0){
					return uni.showToast({
						title: '请上传精选照片',
						icon : 'none'
					})
				}
				
				// 只有在新发布时才订阅消息通知，编辑时不需要
				if (!this.isEdit) {
					const subscribed = await subscribeBeforePublish()
					if (!subscribed) {
						return // 用户拒绝订阅，停止发布
					}
				}
				
				// 处理图片数据
				this.form.image = this.fileList.map(n => n.url).join(',')
				
				// 根据是否是编辑模式调用不同的API
				const apiName = this.isEdit ? 'editMyRent' : 'publishRent'
				const params = this.isEdit ? { ...this.form, id: this.rentingId } : this.form
				
				this.$api(apiName, params, res => {
					if(res.code == 200){
						uni.showToast({
							title: this.isEdit ? '修改成功!' : '发布成功!',
							icon: 'none'
						})
						
						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					} else {
						uni.showToast({
							title: res.msg || (this.isEdit ? '修改失败' : '发布失败'),
							icon: 'none'
						})
					}
				})
			},
			// 删除租房
			deleteRenting() {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个租房信息吗？删除后无法恢复。',
					confirmColor: '#ff4757',
					success: (res) => {
						if (res.confirm) {
							this.$api('deleteMyRent', { id: this.rentingId }, res => {
								if (res.code == 200) {
									uni.showToast({
										title: '删除成功!',
										icon: 'none'
									})
									
									setTimeout(() => {
										uni.navigateBack()
									}, 1000)
								} else {
									uni.showToast({
										title: res.msg || '删除失败',
										icon: 'none'
									})
								}
							})
						}
					}
				})
			},
		}
	}
</script>

<style scoped lang="scss">
.page{
	background-color: #fff;
	min-height: 100vh;
	box-sizing: border-box;
	color: #333333;
	font-size: 28rpx;
	/deep/ text{
		font-size: 28rpx !important;
	}
	.form{
		padding: 30rpx;
		.help-issue {
			margin: 20rpx;
		}
		.title-input{
			border: 1px solid $uni-color;
			width: 100%;
			border-radius: 10rpx;
			padding: 10rpx 20rpx;
			box-sizing: border-box;
			height: 65rpx;
		}
		.form-sheet-cell{
			display: flex;
			background-color: #fff;
			padding: 20rpx 30rpx;
			align-items: center;
			.label{
				width: 160rpx;
			}
			.price{
				display: flex;
				// text-align: center;
				input{
					width: 450rpx;
					// border: 1px solid $uni-color;
					margin: 0 10rpx;
				}
			}
			.right-icon{
				margin-left: auto;
			}
		}
		
		.images{
			padding: 30rpx;
			view{
				padding-bottom: 20rpx;
			}
		}
	}
	
	.delete-btn {
		background: #ff4757;
		color: white;
		text-align: center;
		padding: 20rpx;
		margin: 30rpx;
        border-radius: 40rpx;
		font-size: 28rpx;
		font-weight: bold;
		
		&:active {
			background: #ff3742;
		}
	}
	
	.category{
		padding: 20rpx;
		.title{
			// font-weight: 900;
			// font-size: 30rpx;
		}
		.tagList{
			display: flex;
			flex-wrap: wrap;
			padding: 10rpx 0;
			view{
				background: rgba($uni-color, 0.1);
				padding: 10rpx 20rpx;
				margin: 10rpx;
				border-radius: 10rpx;
				font-size: 26rpx;
			}
			.act{
				color: #fff;
				background: $uni-color;
			}
		}
	}
}
</style>
