<template>
	<div class="container">
		<model :show="show" @close="show=false" :content="content" />
		<u-popup v-model="popupshow" mode="bottom" border-radius="40" height="600px">
			<view class="popup-father">

				<view class="popup-title">
					<view class="all-bgc"
						style="display: flex; align-items: center;height: 150rpx;width: 100%;position: relative;border-bottom: 1rpx solid #DFDFDF;">
						<view class="title-font">
							请选择所在地区
						</view>
						<!-- <image class="title-imge-title" src="https://www.focusnu.com/media/directive/index/mark.png" /> -->
					</view>
					<view style="display: flex;margin-left: 15rpx;">
						<view class="button-father" v-for="(item,index) in address"
							:style="index==address.length-1?{backgroundColor:`#e4e4e4;`,color:`#595959`}:{}"
							@click="deleteUP(index)">
							<view>
								{{item.name}}
							</view>
							<image class="title-imge"
								:src="`https://www.focusnu.com/media/directive/index/workjoin/redcha.png`" />
						</view>
					</view>

				</view>
				<view style="height: 150rpx;width: 100%;"></view>
				<view style="height: 80rpx;width: 100%;" v-if="address.length"></view>
				<view class="other-title">
					选择地区
				</view>
				<view v-for="(item,index) in list" :key="index" @click="clickcard(item)">
					<view class="cards">
						<view class="zimu">
							{{item.firstLetter}}
						</view>
						<view class="font">
							{{item.name}}
						</view>
					</view>

				</view>
			</view>

		</u-popup>
		<!-- <view class="title-back">
			<view class="left-father" @click="goBack">
				<image class="back-img" src="https://www.focusnu.com/media/directive/index/left.png" />
				<view style="font-size: 30rpx;">机构信息</view>
			</view>
		</view> -->
		<view class="title-back" :style="{height:`${uni.getStorageSync('moveHeight')+40}px`}">
			<view class="left-father" @click="goBack">
				<image class="back-img" src="https://www.focusnu.com/media/directive/index/left.png" />
				<view style="font-size: 30rpx;">机构信息</view>
			</view>
		</view>
		<view :style="{height:`${uni.getStorageSync('moveHeight') + 30}px`}"></view>
		<view class="white-content">
			<view class="content-title">
				<view class="shu"></view>
				<view class="content-weight">机构信息</view>
			</view>
			<view class="white-message">
				<view @click="openpopupshow">
					<view class="one" style="position: relative;">
						<view class="one-left">机构位置</view>
						<input disabled style="cursor: not-allowed;pointer-events: none;" class="one-right" type="text"
							placeholder="请选择机构位置" v-model="form.address" />
						<image class="one-left-imge" src="https://www.focusnu.com/media/directive/index/canread.png" />
						<!-- <image class="triangle-down" src="https://www.focusnu.com/media/directive/login/xia.png" /> -->
					</view>
				</view>
				<view>
					<view class="one" style="overflow: hidden;">
						<view class="one-left">详细地址</view>
						<input maxlength="30" class="one-right" placeholder="请输入详细地址" v-model="form.orgAddress" />
						<image class="one-left-imge" src="https://www.focusnu.com/media/directive/index/canread.png" />
					</view>
				</view>
				<view>
					<view class="one">
						<view class="one-left">机构负责人</view>
						<input :maxlength="fzrmax" class="one-right" type="text" placeholder="请输入机构负责人姓名"
						@focus="fzrmax = 30" @blur="fzrmax = 5"
							v-model="form.orgLeader" />
						<image class="one-left-imge" src="https://www.focusnu.com/media/directive/index/canread.png" />
					</view>
				</view>
				<view>
					<view class="one">
						<view class="one-left">机构负责人电话</view>
						<input class="one-right" type="number" maxlength="11" placeholder="请输入机构负责人电话"
							v-model="form.orgLeaderPhone" />
						<image class="one-left-imge" src="https://www.focusnu.com/media/directive/index/canread.png" />
					</view>
				</view>

				<view>
					<view class="one" style="position: relative;" @click="showselect = true">
						<view class="one-left">房屋性质</view>
						<input disabled style="cursor: not-allowed;pointer-events: none;" class="one-right" type="text"
							placeholder="请选择房屋性质" v-model="form.orgPropertyType" />
						<image class="one-left-imge" src="https://www.focusnu.com/media/directive/index/canread.png" />
						<!-- <image class="triangle-down" src="https://www.focusnu.com/media/directive/login/xia.png" /> -->
					</view>
				</view>
				<u-select style="font-size: 35rpx;" v-model="showselect" :list="showlist"
					@confirm="onSelect1"></u-select>
				<view style="margin-bottom: 20rpx;">
					<view class="one" style="position: relative;">
						<view class="one-left">建筑面积</view>
						<input maxlength="10" class="one-right" type="digit" placeholder="请输入建筑面积"
							v-model="form.orgBuildingArea" @input="formatArea" />
						<view class="triangle-down-mi">
							m²
						</view>
						<image class="one-left-imge" src="https://www.focusnu.com/media/directive/index/canread.png" />
					</view>
				</view>
			</view>
		</view>

		<view style="display: flex;width: 100%;margin-top: 10rpx;padding: 0 10%;justify-content: space-between;">
			<view class="back-button" @click="goBack">
				返回上一步
			</view>
			<view class="finish-button" @click="next">
				确认并提交
			</view>
		</view>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive,
		nextTick
	} from 'vue'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';

	import {
		base_url
	} from '@/request/index.js'

	import {
		changemessage,
		getdate
	} from './api/addjigou.js'
	import model from "@/compontent/public/model.vue"
	import {
		swapLongTerm
	} from '@/compontent/public/long.js'
	import {
		shallowEqualObjects
	} from '@/compontent/public/issame.js'

	const address = ref([])
	const show = ref(false);
	const content = ref("");
	const jigouweizhi = ref("");
	const popupshow = ref(false);
	const list = ref([]);
	const showselect = ref(false);
	const showlist = reactive(
		[{
				value: 1,
				label: '租赁'
			},
			{
				value: 2,
				label: '自由产权'
			},
			{
				value: 3,
				label: '合作使用'
			},
			{
				value: 4,
				label: '其它'
			}
		]
	)
	const fzrmax = ref(5)
	function onSelect1(arr) {
		form.orgPropertyType = arr[0].label
	}
	const form = reactive({
		orgLeader: "",
		orgLeaderPhone: "",
		orgAddress: "",
		orgPropertyType: "",
		orgBuildingArea: "",
		orgCoordinateLo: "",
		orgCoordinateLa: "",
		id: uni.getStorageSync('specicalid') || "",
		tel: uni.getStorageSync('tel'),
		status: "1"
	})
	// 本地保存的临时文件路径
	const tempImagePath = ref('')
	const headImge = ref("");
	const backImge = ref("");

	function isAtLeastEightChars(str) {
		return typeof str === 'string' && str.length >= 12;
	}
	const openLook = (res) => {
		if (isAtLeastEightChars(res)) {
			content.value = res;
			show.value = true
		}
	}
	//配置删除逻辑
	function takeFirst(arr, num) {
		// 1. 安全裁剪：确保 num 在 [0, arr.length] 范围内
		const count = Math.max(0, Math.min(num, arr.length));
		// 2. slice(0, count) 会返回前 count 项，count=0 时即返回 []
		return arr.slice(0, count);
	}
	const deleteUP = (index) => {
		address.value = takeFirst(address.value, index);
		if (index) {
			list.value = [];
			getdate(address.value[0].id).then(res => {
				list.value = dedupeFirstLetter(res.result)
			})
		} else {
			list.value = [];
			getdate(`xzqhdm`).then(res => {
				list.value = dedupeFirstLetter(res.result)
			})
		}
	}

	function isValid11DigitNumber(val) {
		// return /^(\d{11})$/.test(val);
		return /^1[3-9]\d{9}$/.test(val);
	}
	const ukey = ref(
		`${uni.getStorageSync('openid') || ''}jgbg${String(Date.now()).slice(-5)}${String(Math.floor(Math.random() * 900) + 100)}`
	)
	const next = () => {
		if (!form.address) {
			uni.showToast({
				title: '请选择机构位置',
				icon: 'error'
			})
			return
		} else if (!form.orgAddress) {
			uni.showToast({
				title: '请输入详细地址',
				icon: 'error'
			})
			return
		} else if (!form.orgLeader) {
			uni.showToast({
				title: '请输入机构负责人',
				icon: 'error'
			})
			return
		} else if (!form.orgLeaderPhone) {
			uni.showToast({
				title: '请输入手机号',
				icon: 'error'
			})
			return
		} else if (!isValid11DigitNumber(form.orgLeaderPhone)) {
			uni.showToast({
				title: '手机号格式错误',
				icon: 'error'
			})
			return
		} else if (!form.orgPropertyType) {
			uni.showToast({
				title: '请输入房屋性质',
				icon: 'error'
			})
			return
		} else if (!form.orgBuildingArea) {
			uni.showToast({
				title: '请输入建筑面积',
				icon: 'error'
			})
			return
		}
		const allNonEmpty = form.orgLeader && form.orgLeaderPhone && form.orgAddress && form.orgPropertyType &&
			form.orgBuildingArea && form.address
		let data = uni.getStorageSync('backhuancun')
		data.openId = uni.getStorageSync('openid')
		data.address = form.address
		data.orgProvince = form.orgProvince
		data.orgCity = form.orgCity
		data.orgDistrict = form.orgDistrict
		data.orgAddress = form.orgAddress
		data.orgLeader = form.orgLeader
		data.orgLeaderPhone = form.orgLeaderPhone
		data.orgPropertyType = form.orgPropertyType
		data.orgBuildingArea = form.orgBuildingArea

		if (data.id === null) {
			data.status = `4`
		} else {
			data.status = form.status
		}
		uni.setStorageSync("backhuancun", data)

		if (allNonEmpty) {
			let data = uni.getStorageSync('backhuancun')
			// console.log("?????",data)
			if (data.endTime == '长期') {
				data.endTime = swapLongTerm(data.endTime);
			}
			uni.setStorageSync("backhuancun", data)
			// return
			changemessage(uni.getStorageSync('backhuancun'), ukey.value).then(res => {
				if (res.success && res.result != '重复提交' && res.result != '未做变更') {

					uni.requestSubscribeMessage({
						// 这里填后台申请好的 templateId 数组
						tmplIds: ['cWVzXm1C-iitx1gNFn1nZdijq9R_3fCv8vLbiqs9zww'],
						success: (res) => {
							uni.setStorageSync('specicalid', "");
							uni.reLaunch({
								url: `/pages/login/specialsmall?type=1&special=${uni.getStorageSync('backhuancun').id===null}`
							});
						},
						fail: (err) => {
							console.error('订阅接口调用失败：', err);
							uni.showToast({
								title: '订阅失败',
								icon: 'none'
							});
						}
					});

				} else {
					uni.showToast({
						title: res.result == '未做变更' ? `当前无变更，无需提交` : res.message,
						icon: 'none'
					})
				}
			})
		} else {
			uni.showToast({
				title: '请完善信息',
				icon: 'error'
			})
		}
	}

	const goBack = () => {
		if (form.address) {
			let data = uni.getStorageSync('backhuancun')
			data.address = form.address
			data.orgProvince = form.orgProvince
			data.orgCity = form.orgCity
			data.orgDistrict = form.orgDistrict
			data.orgAddress = form.orgAddress
			data.orgLeader = form.orgLeader
			data.orgLeaderPhone = form.orgLeaderPhone
			data.orgPropertyType = form.orgPropertyType
			data.orgBuildingArea = form.orgBuildingArea
			uni.setStorageSync("backhuancun", data)
		}
		uni.navigateBack()
	}
	const jumpToMap = () => {
		uni.navigateTo({
			url: "/pages/map/index"
		});
	}

	const clickcard = (element) => {
		if (address.value.length < 3) {
			list.value = [];
			address.value.push(element)
			getdate(element.id).then(res => {
				if (res.result.length) {
					list.value = dedupeFirstLetter(res.result)
				} else {
					popupshow.value = false;
					form.address = "";
					address.value.forEach(res => {
						form.address += res.name
					})
					const keys = ['orgProvince', 'orgCity', 'orgDistrict'];

					keys.forEach((key, idx) => {
						// 如果 address.value[idx] 存在就取它的 id，否则用空字符串
						form[key] = address.value[idx]?.id ? address.value[idx]?.id : "";
					});
					address.value = [];
					list.value = [];
					getdate(`xzqhdm`).then(res => {
						list.value = dedupeFirstLetter(res.result)
					})
				}

			})
		}


	}
	const openpopupshow = () => {
		popupshow.value = true;

	}
	onShow(() => {
		// 读取并立即清除，避免下次重复拿到
		const data = uni.getStorageSync('dingwei')
		if (data) {
			console.log("data", data)
			jigouweizhi.value = data.name
			form.orgAddress = data.name
			form.orgCoordinateLo = data.lng
			form.orgCoordinateLa = data.lat
			uni.removeStorageSync('dingwei')
		}
	})
	//处理首字母
	function dedupeFirstLetter(arr) {
		const seen = new Set();
		return arr.map(item => {
			const letter = item.firstLetter;
			if (!letter || seen.has(letter)) {
				// 如果没 letter 或者已经出现过，则清空
				return {
					...item,
					firstLetter: ''
				};
			} else {
				// 第一次出现，保留并记录
				seen.add(letter);
				return item;
			}
		});
	}

	function formatArea() {
		const value = form.orgBuildingArea;
		const firstDot = value.indexOf('.');
		const lastDot = value.lastIndexOf('.');

		let cleaned = value;

		// 如果出现多个小数点，则去掉最后一个后面的
		if (firstDot !== lastDot) {
			cleaned = value.slice(0, lastDot);
		}

		// 限制小数点后只能有最多 4 位
		if (cleaned.includes('.')) {
			const [intPart, decimalPart] = cleaned.split('.');
			cleaned = intPart + '.' + decimalPart.slice(0, 4);
		}

		// 如果格式有变动，则更新
		if (cleaned !== value) {
			nextTick(() => {
				form.orgBuildingArea = cleaned;
			});
		}
	}
	onLoad(() => {
		getdate(`xzqhdm`).then(res => {
			list.value = dedupeFirstLetter(res.result)
		})
		if (uni.getStorageSync('backhuancun').address) {
			let data = uni.getStorageSync('backhuancun');
			form.address = data.address
			form.orgProvince = data.orgProvince;
			form.orgCity = data.orgCity;
			form.orgDistrict = data.orgDistrict;
			form.orgAddress = data.orgAddress;
			form.orgLeader = data.orgLeader;
			form.orgLeaderPhone = data.orgLeaderPhone;
			form.orgPropertyType = data.orgPropertyType;
			form.orgBuildingArea = data.orgBuildingArea;
			console.log("111", form)
		} else if (uni.getStorageSync('baddata')) {
			let data = uni.getStorageSync('baddata');
			if (data.orgProvince_dictText) {
				form.address = data.orgProvince_dictText + (data.orgCity_dictText != null ? data.orgCity_dictText :
					``) + (data.orgDistrict_dictText != null ? data.orgDistrict_dictText : ``)
			}
			form.orgProvince = data.orgProvince;
			form.orgCity = data.orgCity;
			form.orgDistrict = data.orgDistrict;
			form.orgAddress = data.orgAddress;
			form.orgLeader = data.orgLeader;
			form.orgLeaderPhone = data.orgLeaderPhone;
			form.orgPropertyType = data.orgPropertyType;
			form.orgBuildingArea = data.orgBuildingArea;
			console.log("222", form)
		} else {

			form.orgLeaderPhone = uni.getStorageSync('tel');
		}
	})
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		width: 100%;
		background-color: #F7F7F7;
		position: relative;

		.white-content {
			width: 100%;
			margin-top: 20rpx;
			border-radius: 35rpx;

			.content-title {
				display: flex;
				align-items: center;
				height: 70rpx;
				position: relative;

				.content-weight {
					font-size: 32rpx;
					font-weight: 600;
					margin-left: 20rpx;
				}

				.content-img {
					position: absolute;
					right: 0;
					top: 0;
					width: 400rpx;
					height: 100%;
				}
			}
		}

		.white-photo {
			width: 90%;
			margin-left: 5%;
			height: 300rpx;
			border-radius: 35rpx;
			background-color: #fff;
			justify-content: space-around;
			align-items: center;
			display: flex;

			.photo {
				width: 300rpx;
				height: 200rpx;
			}
		}

		.white-message {
			width: 90%;
			margin-left: 5%;
			margin-top: 10rpx;
			margin-bottom: 30rpx;
			padding: 30rpx 0;
			border-radius: 35rpx;
			background-color: #fff;
			justify-content: space-around;
			display: flex;
			flex-direction: column;

			.message-title {
				width: 100%;
				height: 100rpx;
				align-items: center;
				display: flex;

				.message-weight {
					font-size: 30rpx;
				}
			}

			.one {
				width: 90%;
				margin-left: 5%;
				height: 100rpx;
				display: flex;
				align-items: center;
				margin-bottom: 10rpx;
				position: relative;

				.one-left {
					margin-left: 10rpx;
					font-size: 30rpx;
					width: 250rpx;
				}

				.one-right {
					font-size: 30rpx;
					height: 100%;
					color: #999999;
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
					max-width: 300rpx;
					display: flex;
				}

				.one-left-imge {
					width: 35rpx;
					height: 35rpx;
					position: absolute;
					top: 50%;
					right: 8rpx;
					transform: translateY(-50%);
				}

			}
		}
	}

	.photo-left {
		.photo-weight {
			font-size: 26rpx;
			font-weight: 600;
		}

		.photo-font {
			font-size: 23rpx;
			margin-top: 10rpx;
		}

	}

	.finish-button {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 44%;
		height: 90rpx;
		// margin: 0rpx auto;
		margin-bottom: 80rpx;
		background: linear-gradient(to bottom, #e7f4ff, #c5e5ff);
		border: 2rpx solid #9AD1FF;
		color: #007CFF;
		border-radius: 37rpx;
		font-size: 33rpx;
	}

	.one-img {
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		right: 10rpx;
		width: 60rpx;
		height: 50rpx;
	}

	.pingfangmi {
		position: absolute;
		top: 50%;
		right: 5rpx;
		transform: translateY(-50%);
	}

	.special {
		display: flex;
		align-items: center;
		width: 280rpx;
		position: relative;
	}

	.popup-father {
		width: 100%;
		position: relative;

		.popup-title {
			position: fixed;
			top: 0;
			left: 0;
			display: flex;
			flex-direction: column;
			width: 100%;

			.title-font {
				font-size: 38rpx;
				// font-weight: 600;
				margin-left: 80rpx;
			}

			.title-imge {
				width: 30rpx;
				height: 30rpx;
				margin-left: 10rpx;
				margin-top: 5rpx;
			}

			background-color: #fff;
			z-index: 1;
		}

		.other-title {
			font-size: 32rpx;
			font-weight: 600;
			margin-left: 45rpx;
			margin-top: 50rpx;
		}
	}

	.cards {
		width: 100%;
		display: flex;
		align-items: center;
		height: 100rpx;

		.zimu {
			margin: 0 30rpx;
			color: #d7d7d7;
			width: 28rpx;
		}

		.font {
			font-size: 30rpx;
		}
	}

	.title-back {
		background-color: #F7F7F7;
		width: 100%;
		height: 70rpx;
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #cbd1d2;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 9999;

		.left-father {
			display: flex;
			align-items: center;

			.back-img {
				width: 45rpx;
				height: 40rpx;
				margin-left: 40rpx;
				margin-right: 15rpx;
			}
		}
	}

	.back-button {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 44%;
		height: 90rpx;
		margin-bottom: 80rpx;
		border: 2rpx solid #c3cacd;
		background: linear-gradient(to bottom, #f3f3f5, #dee4e9);
		border-radius: 37rpx;
		font-size: 33rpx;
	}

	.shu {
		width: 14rpx;
		height: 36rpx;
		background-color: #0097FF;
		border-radius: 10rpx;
		margin: 3rpx 5rpx 0 60rpx;
	}

	.triangle-down {
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		right: 26rpx;
		width: 20rpx;
		height: 20rpx;
	}

	.triangle-down-mi {
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		right: 50rpx;
		font-size: 30rpx;
		color: #999999;
	}

	.all-bgc {
		// background-image: url('https://www.focusnu.com/media/directive/index/where.png');
		// background-size: 100% auto;
		// /* 宽度占满，高度自动 */
		// background-position: top center;
		// background-repeat: no-repeat;
	}

	.title-imge-title {
		width: 100rpx;
		height: 120rpx;
		position: absolute;
		top: 10rpx;
		right: 80rpx;
	}

	.button-father {
		height: 60rpx;
		padding: 0 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		background-color: #F5F5F5;
		color: #666666;
		border-radius: 30rpx;
		margin-top: 30rpx;
		margin-left: 30rpx;
	}
</style>
<style>
	.uni-scroll-view {
		height: auto;
	}
</style>