<template>
	<view class="container">
		<u-navbar autoBack placeholder bgColor="transparent"
			style="background: linear-gradient(91deg, #FDEDEE 0%, #FFFFFF 100%);">
			<view class="navSlot" slot="left">
				<u-icon name="arrow-left" size="19"></u-icon>
				<text class="title" v-if="type == 1">添加公厕</text>
				<text class="title" v-else-if="type == 2">编辑公厕</text>
			</view>
		</u-navbar>
		<view class="main">
			<view @click="getMapLocation" class="flex ptb-20 flex-center-center"
				style="border-bottom: 1px solid #F0F0F0;">
				<text style="color: red;">*</text>
				<text style="color: black;">公厕位置</text>
				<text
					style="flex: 1;text-align: end;color: #999999;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;width: 100rpx;display: block;margin-left: 40rpx;">{{addressTitle==''?'请选择':addressTitle}}</text>
				<image class="left w-8 h-15 ml-10" src="../../static/hoem/ic_left.png"></image>
			</view>
			<view @click="showZone=true" class="flex ptb-20 flex-center-center"
				style="border-bottom: 1px solid #F0F0F0;">
				<text style="color: red;">*</text>
				<text style="color: black;">公厕所属区域</text>
				<text style="color: black;flex: 1;text-align: end;color: #999999;">{{zone==''?'请选择':zone}}</text>
				<image class="left w-8 h-15 ml-10" src="../../static/hoem/ic_left.png"></image>
			</view>
			<view @click="showAdmin=true" class="flex ptb-20 flex-center-center"
				style="border-bottom: 1px solid #F0F0F0;">
				<text style="color: red;">*</text>
				<text style="color: black;">管理员</text>
				<text style="color: black;flex: 1;text-align: end;color: #999999;">{{admin==''?'请选择':admin}}</text>
				<image class="left w-8 h-15 ml-10" src="../../static/hoem/ic_left.png"></image>
			</view>
			<view class="flex-column ptb-20" style="border-bottom: 1px solid #F0F0F0;">
				<view class="flex mb-20">
					<text style="color: red;">*</text>
					<text style="color: black;">公厕编号</text>
				</view>
				<input style="color: black;flex: 1;margin-left: 15rpx;" placeholder="请填写" v-model="number" />
			</view>
			<view class="flex-column ptb-20" style="border-bottom: 1px solid #F0F0F0;">
				<view class="flex mb-20">
					<text style="color: red;">*</text>
					<text style="color: black;">公厕面积</text>
				</view>
				<input style="color: black;flex: 1;margin-left: 15rpx;" placeholder="请填写" v-model="area" />
			</view>
			<view v-for="(item,index) in deviceList" :key="index">
				<view @click="onAddDevice(index)" @longpress="onLongDel(index)" class="flex ptb-20 flex-center-center"
					style="border-bottom: 1px solid #F0F0F0;">
					<text style="color: red;">*</text>
					<text style="color: black;">公厕坑位设备</text>
					<text
						style="color: black;flex: 1;text-align: end;color: #999999;">{{item.device==''?'请选择':item.device}}</text>
					<image class="left w-8 h-15 ml-10" src="../../static/hoem/ic_left.png"></image>
				</view>
			</view>

			<view @click="onAdd" class="flex-center-center fs-28 ptb-10"
				style="border-radius: 4px;border: 1px solid #999999;color: #999999;">
				<text>+坑位</text>
			</view>
			<view class="flex-column ptb-20">
				<view class="flex mb-20">
					<text style="color: red;">*</text>
					<text style="color: black;">公厕照片</text>
				</view>

				<upload-image v-if="type == 1" v-model="images" maxCount="3" width="100" height="100" type="fullurl"
					@uploadImages="uploadImages"></upload-image>
				<upload-image v-if="type == 2&&images" v-model="images" maxCount="3" width="100" height="100"
					type="fullurl" @uploadImages="uploadImages"></upload-image>
			</view>
			<view class="flex-column">
				<text style="color: black;">备注信息</text>
				<textarea v-model="dataParams.remarks" class="h-200 mt-20"
					style="width: 100%;padding: 10rpx; background: #F8F4F4;border-radius: 4px;box-sizing: border-box;"
					:adjust-position="false" placeholder="请输入详细地址"
					placeholder-style="color:#c0c4cc;font-size: 30rpx"></textarea>
			</view>
			<u-picker keyName="name" :show="showZone" ref="uPicker" :columns="zoneList" :closeOnClickOverlay="true"
				@close="showZone = false" @cancel="showZone = false" @confirm="onZone"
				@change="changeHandler"></u-picker>
			<u-picker :show="showAdmin" :columns="adminList" :closeOnClickOverlay="true" @close="showAdmin = false"
				@cancel="showAdmin = false" @confirm="onAdmin"></u-picker>
			<u-picker :show="showDevice" :columns="deviceListData" :closeOnClickOverlay="true"
				@close="showDevice = false" @cancel="showDevice = false" @confirm="onDevice"></u-picker>
		</view>
		<view class="btn-group flex-center-center" @click="onSubmit">
			<text>提交</text>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				addressTitle: '',
				type: "",
				zone: '',
				showZone: false,
				zoneList: [
					// ['中原区', '二七区', '管城回族区', "金水区", "上街区", "惠济区"],
					// ['中国', '美国'],
					// ['深圳', '厦门', '上海', '拉萨']
				],
				admin: '',
				showAdmin: false,
				adminList: [
					['张三', '李四', '王二', "麻子"]
				],

				showDevice: false,
				deviceListData: [
					['A1001', 'A1002', 'A1003', "A1004"]
				],
				deviceIndex: 0,
				deviceList: [{
					device: ''
				}],
				number: '',
				area: '',
				images: '',
				equipmentBinding: '',
				dataParams: {
					"locationlat": "", //公厕位置纬度
					// 23.038455
					"locationlong": "", //公厕位置经度
					// 113.317323
					"region": "", //所属区域
					"regionCode": "", //所属区域
					"managerId": "", //管理员id
					"managerName": "", //管理员id
					"managerContact": "", //管理员联系方式
					"toiletId": "", //公厕编号
					"area": "", //公厕面积 (平方米)
					"equipmentBindings": [], //绑定设备组
					"equipmentChanges": [], //
					"images": [], //图片url数组
					"remarks": "", //备注信息
					"province": "",
					"city": "",
					"area": "",
					"addresstext": "",
					"address": "",
					"addressTitle": "",
					"id": "",
				},
				managerList: [],
				posarr: []
			};
		},
		onLoad(data) {
			console.log(data)
			this.type = data.type;
			if (this.type == 2) {
				this.dataParams.id = data.id;
				this.getitem(data.id);
			}
			this.getZone()
			this.getManager()
			this.getDevice()
		},
		onShow() {},
		methods: {
			changeHandler(e) {
				console.log(e)
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e;
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				console.log(this.posarr)
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.posarr[index].children)
				}
			},
			getitem(id) {
				const params = {
					url: '/app/system/toilets/info',
					data: {
						id: id
					},
				}
				this.$request(params).then(res => {
					console.log(res.data.image)
					// this.dataParams = res.data;
					this.zone = res.data.region;
					this.dataParams.region = this.zone
					this.admin = res.data.managerName;
					this.dataParams.managerId = res.data.managerId;
					this.dataParams.managerName = res.data.managerName;
					this.dataParams.managerContact = res.data.managerContact;
					this.number = res.data.toiletId;
					this.area = res.data.area;
					this.images = res.data.image;
					this.addressTitle = res.data.addressTitle;
					this.dataParams.addressTitle = res.data.addressTitle;
					this.dataParams.locationlat = res.data.locationlat;
					this.dataParams.locationlong = res.data.locationlong;
					this.dataParams.remarks = res.data.remarks;
					this.dataParams.regionCode = res.data.regionCode;
					this.dataParams.region = res.data.region;
					this.equipmentBinding = res.data.equipmentBinding.split(",");
					res.data.equipmentBinding.split(",").forEach((item, index) => {
						if (index == 0) {
							this.deviceList[0].device = item
						} else {
							this.deviceList.push({
								device: item
							})
						}
					})


					console.log(this.deviceList)
				})
			},
			//获取区域列表数据
			getZone() {
				const params = {
					url: '/system/province/list',
					data: {},
				}
				this.$request(params).then(res => {
					this.zoneList.push(res.rows);
					this.zoneList.push(res.rows[0].children);
					this.posarr = res.rows;
					console.log(this.zoneList)
					// for (var i = 0; i < res.rows.length; i++) {
					// 	this.zoneList[0].push(res.rows[i].name)
					// }
				})
			},
			//获取管理员列表数据
			getManager() {
				const params = {
					url: '/system/province/setuser',
					data: {
						role: '1'
					},
				}
				this.$request(params).then(res => {
					this.managerList = res.data
					this.adminList[0].length = 0
					for (var i = 0; i < res.data.length; i++) {
						this.adminList[0].push(res.data[i].nickName)
					}
				})
			},
			//获取设备列表数据
			getDevice() {
				const params = {
					url: '/app/system/toilets/toiletsequipmentlist',
					data: {},
				}
				this.$request(params).then(res => {
					this.deviceListData[0].length = 0
					for (var i = 0; i < res.rows.length; i++) {
						this.deviceListData[0].push(res.rows[i])
					}
				})
			},

			onLongDel(index) {
				this.deviceIndex = index
				this.deviceList.splice(index, 1)
			},
			onZone(e) {
				console.log(e)
				this.zone = e.value[1].name
				this.showZone = false
				this.dataParams.region = e.value[1].name
				this.dataParams.regionCode = e.value[1].code
			},
			onAdmin(e) {
				this.admin = e.value[0]
				this.showAdmin = false
				this.dataParams.managerId = this.managerList[e.indexs[0]].userId
				this.dataParams.managerName = this.managerList[e.indexs[0]].nickName
				this.dataParams.managerContact = this.managerList[e.indexs[0]].phonenumber
			},

			//添加坑位
			onAdd() {
				let deviceInfo = {
					device: ''
				}
				this.deviceList.push(deviceInfo)
				console.log(this.deviceList)
			},
			//选择设备
			onDevice(e) {
				this.deviceList[this.deviceIndex].device = e.value[0]
				this.showDevice = false
			},
			onAddDevice(index) {
				this.deviceIndex = index
				this.showDevice = true
			},
			uploadImages(images) {
				console.log(images)
				this.images = images
				console.log(this.images)
			},
			onSubmit() {
				this.dataParams.toiletId = this.number
				this.dataParams.area = this.area
				for (var i = 0; i < this.deviceList.length; i++) {
					if (this.deviceList[i].device.length != 0) {
						this.dataParams.equipmentBindings.push(this.deviceList[i].device)
					}
				}
				if (this.type == 2) {
					this.dataParams.equipmentChanges = this.dataParams.equipmentBindings;
					this.dataParams.equipmentBindings = this.equipmentBinding;
				}
				let images = this.images.split(",")
				for (var i = 0; i < images.length; i++) {
					if (images[i].length != 0) {
						this.dataParams.images.push(images[i])
					}
				}
				if (this.dataParams.locationlat.length == 0) {
					this.$u.toast('请选择公厕位置')
					return
				}
				if (this.dataParams.region.length == 0) {
					this.$u.toast('请选择公厕所属区域')
					return
				}
				if (this.dataParams.managerName.length == 0) {
					this.$u.toast('请选择管理员')
					return
				}
				if (this.dataParams.toiletId.length == 0) {
					this.$u.toast('请输入公厕编号')
					return
				}
				if (this.dataParams.area.length == 0||this.dataParams.area.length === null) {
					this.$u.toast('请输入公厕面积')
					return
				}
				if (this.dataParams.equipmentBindings.length == 0) {
					this.$u.toast('请添加并选择公厕设备')
					return
				}
				if (this.dataParams.images.length == 0) {
					this.$u.toast('请添加公厕照片')
					return
				}
				let url = "";
				if (this.type == 1) {
					url = '/app/system/toilets/addtoilets'
				} else if (this.type == 2) {
					url = '/app/system/toilets/edit'
				}
				const params = {
					url: url,
					data: this.dataParams,
				}
				// console.log(this.dataParams)
				// return
				this.$request(params).then(res => {
					this.$u.toast('成功')
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 800)
				})
			},
			getMapLocation() {
				uni.chooseLocation({
					success: (data) => {
						console.log(data)
						console.log(formatLocation(data))
						this.addressTitle = data.name;
						this.dataParams.addressTitle = data.name;
						this.dataParams.locationlat = data.latitude;
						this.dataParams.locationlong = data.longitude;
						this.dataParams.province = formatLocation(data).REGION_PROVINCE;
						this.dataParams.city = formatLocation(data).REGION_CITY;
						this.dataParams.area = formatLocation(data).REGION_COUNTRY;
						this.dataParams.addresstext = formatLocation(data).ADDRESS;
						this.dataParams.address = this.dataParams.province + this.dataParams.city + this
							.dataParams.area + this.dataParams.addresstext;
						// //判断是否开通服务
						// const params = {
						// 	url: '/api/cityArea/checkCity',
						// 	method: "GET",
						// 	data: {
						// 		city: formatLocation(data).REGION_CITY
						// 	}
						// }
						// this.$request(params).then(res => {
						// 	if (res.data == true) {
						// 		// 将获取到的地址信息存储
						// 		this.addressData.province = formatLocation(data).REGION_PROVINCE;
						// 		this.addressData.city = formatLocation(data).REGION_CITY;
						// 		this.addressData.area = formatLocation(data).REGION_COUNTRY;
						// 		this.addressData.address = formatLocation(data).ADDRESS;
						// 		console.log(addressData)
						// 	} else {
						// 		this.$u.toast('该地区暂未开通服务')
						// 	}
						// })

					},
					fail: (resdata) => {
						console.log(resdata)
						// 如果用uni.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息
						uni.getSetting({
							success: (res) => {
								var status = res.authSetting;
								if (!status['scope.userLocation']) {
									// 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
									uni.showModal({
										title: "是否授权当前位置",
										content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
										success: (tip) => {
											if (tip.confirm) {
												// 如果用户同意授权地理信息，则打开授权设置页面，判断用户的操作
												uni.openSetting({
													success: (data) => {
														// 如果用户授权了地理信息在，则提示授权成功
														if (data
															.authSetting[
																'scope.userLocation'
															] === true
														) {
															uni.showToast({
																title: "授权成功",
																icon: "success",
																duration: 1000
															})
															// 授权成功后，然后再次chooseLocation获取信息
															uni.chooseLocation({
																success: (
																	res
																) => {
																	// 将获取到的地址信息存储
																	// this.addressData
																	// 	.address =
																	// 	res
																	// 	.address
																	// this.addressTitle = res.address;
																}
															})
														} else {
															uni.showToast({
																title: "授权失败",
																icon: "none",
																duration: 1000
															})
														}
													}
												})
											}
										}
									})
								}
							},
							fail: (res) => {
								uni.showToast({
									title: "调用授权窗口失败",
									icon: "none",
									duration: 1000
								})
							}
						})
					}
				});
			},


		},
	};

	function formatLocation(res) {
		var regex = /^(北京市|天津市|重庆市|上海市|香港特别行政区|澳门特别行政区)/;
		var REGION_PROVINCE = [];
		var addressBean = {
			REGION_PROVINCE: null,
			REGION_COUNTRY: null,
			REGION_CITY: null,
			ADDRESS: null
		};

		function regexAddressBean(address, addressBean) {
			// regex = /^(.*?[市州]|.*?地区|.*?特别行政区)(.*?[市区县])(.*?)$/g;
			regex = /^(.*?[市]|.*?地区|.*?特别行政区)(.*?[市区县])(.*?)$/g;
			var addxress = regex.exec(address);
			addressBean.REGION_CITY = addxress[1];
			addressBean.REGION_COUNTRY = addxress[2];
			addressBean.ADDRESS = addxress[3] + "(" + res.name + ")";
			// console.log(addxress);
		}
		if (!(REGION_PROVINCE = regex.exec(res.address))) {
			regex = /^(.*?(省|自治区))(.*?)$/;
			REGION_PROVINCE = regex.exec(res.address);
			addressBean.REGION_PROVINCE = REGION_PROVINCE[1];
			regexAddressBean(REGION_PROVINCE[3], addressBean);
		} else {
			addressBean.REGION_PROVINCE = REGION_PROVINCE[1];
			regexAddressBean(res.address, addressBean);
		}
		return addressBean
	};
</script>

<style lang="scss">
	::v-deep .u-navbar {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		z-index: 11;
	}

	.container {
		width: 100%;
		background: #F8F4F4;
		display: flex;
		flex-direction: column;
		padding-bottom: 20rpx;
	}

	.main {
		padding: 20rpx 24rpx;
		background: #FFFFFF;
		border-radius: 14rpx 14rpx 14rpx 14rpx;
		flex: 1;
		margin: 20rpx 24rpx;
		margin-top: 196rpx;
	}

	.btn-group {
		background: linear-gradient(89deg, #FFBFBC 0%, #FB262A 100%);
		margin: 0 20rpx;
		border-radius: 44rpx;
		height: 88rpx;
		background: linear-gradient(89deg, #FFBFBC 0%, #FB262A 100%);
		border-radius: 44rpx 44rpx 44rpx 44rpx;
		font-family: Microsoft YaHei, Microsoft YaHei;
		font-weight: bold;
		font-size: 32rpx;
		color: #FFFFFF;
		line-height: 88rpx;
	}
</style>