<template>
	<view>
		<u-navbar :is-back="isBack" title="经纬度拾取">

		</u-navbar>
		<map style="width: 100vw; height: 40vh;" id="maps" class="map" :show-location="true"
			:enable-satellite="satellite" :theme="theme" :scale="scale" :markers="markers" @regionchange="regionchange"
			@tap="tapAction"></map>
		<view class="selectPointPosition">
			<view>已选位置:</view>
			<view>经度：{{longitude}}纬度：{{latitude}}</view>
		</view>
		<view class="cameraInfo">
			<view class="btnListBox">
				<view>操作:</view>
				<u-icon name="map-fill" size="56" @click="reGetLocation()" style="margin-right: 20rpx;"></u-icon>
			</view>
			<u-section title="已选择设备" :sub-title="cameara.number==null?'请选择':cameara.number"
				@click="goToSelectCamera()"></u-section>
			<view class="cameraItem" v-if="cameara.number!=null">
				<view class="editItem">
					<view class="editItemBtn" @click="goToEdit()">
						<u-icon name="edit-pen" size="36" style="margin-right: 20rpx;"></u-icon>
						<text>编辑其它信息</text>
					</view>
				</view>
				<view class="cameraItemLi">
					<view>设备编码：</view>
					<view>{{cameara.number}}</view>
				</view>
				<view class="cameraItemLi">
					<view>设备类型：</view>
					<view>{{cameara.type}}</view>
				</view>
				<view class="cameraItemLi">
					<view>纬度：</view>
					<view v-if="cameara.latitude">{{cameara.latitude}}</view>
					<view class="unKnow" v-if="!cameara.latitude">空</view>
				</view>
				<view class="cameraItemLi">
					<view>经度：</view>
					<view v-if="cameara.longitude">{{cameara.longitude}}</view>
					<view class="unKnow" v-if="!cameara.longitude">空</view>
				</view>
				<view class="btnList">
					<u-button size="mini" class="btn" type="info" @click="moveTo(10000)">聚焦历史点位</u-button>
					<u-button size="mini" class="btn" type="info" @click="moveTo(100)">聚焦手选位置</u-button>
					<u-button size="mini" class="btn" type="info" @click="moveTo(1)">聚焦当前位置</u-button>
				</view>
				<view class="btnList1">
					<u-button size="mini" type="primary" class="btn" @click="updateAction(0)">设置黑色点为当前设备位置</u-button>
					<u-button size="mini" type="primary" class="btn" @click="updateAction(1)">设置红色点为当前设备位置</u-button>
				</view>
			</view>
		</view>
		<view class="tipsList">
			<view>注：</view>
			<view>黑色图标为用户当前位置</view>
			<view>红色图标为用户手动选中位置（点击地图可以收到选择）</view>
			<view>黄色图标为设备旧位置</view>
		</view>
		<view v-for="item in logs">
			{{item}}
		</view>
		<u-popup v-model="leftModelShow">
			<u-search placeholder="日照香炉生紫烟" v-model="keyword"></u-search>
			<view>出淤泥而不染，濯清涟而不妖</view>
		</u-popup>
		<u-action-sheet :list="list" v-model="showActionList"></u-action-sheet>
	</view>
</template>

<script>
	import dayjs from "dayjs"
	import config from "../../libs/config/config.js"
	export default {
		data() {
			return {
				theme: 'satellite',
				satellite: true,
				isBack: false,
				leftModelShow: false,
				latitude: "", // 默认定在首都
				longitude: "",
				scale: 16, // 默认16
				markers: [],
				markerHeight: 30,
				timer: null,
				logs: [],
				keyword: '',
				accuracy: '', //位置的精确度
				altitude: '', //高度，单位 m
				horizontalAccuracy: '', //水平精度，单位 m
				cameara: {
					id: "",
					camera_name: "",
					camera_code: "",
					longitude: "",
					latitude: "",
					images: "",
					remarks: "",
					type: "",
				},
				showActionList: false,
				list: [{
					text: '点赞',
					color: 'blue',
					fontSize: 28,
					subText: '感谢您的点赞'
				}, {
					text: '分享'
				}, {
					text: '评论'
				}],

			};
		},
		onShow() {
			const returnedTarget = Object.assign(this.$store.state.equip.currentData, this.$store.state.equip.currentDataDetails);
			this.cameara=returnedTarget
			this.$store.dispatch('queryCurrentDataDetails', {})
		},
		onReady() {
			this._mapContext = uni.createMapContext("maps", this);
			this.timer = setInterval(() => {
				//this.getLocationInfo()
			}, 2000)
			this.getLocationInfo()
			//this.bindMapClickAction();
			// this.addMarkers();
		},
		methods: {
			tapAction(e) {
				console.log(e)
				let point = e.detail;
				point.iconPath = '../../static/address_2.png';
				point.id = 100



				this.latitude = point.latitude;
				this.longitude = point.longitude;

				this._mapContext.moveToLocation({
					latitude: point.latitude,
					longitude: point.longitude,
				})

				let list = JSON.parse(JSON.stringify(this.markers));

				let isFrist = 0;

				list.forEach(function(item) {
					if (item.id == 100) {
						isFrist = 1;
						item.latitude = point.latitude;
						item.longitude = point.longitude;
					} else {

					}
				});

				if (isFrist == 0) {
					this.markers = this.markers.concat(point);
				} else {
					this.markers = list;
				}

			},
			bindMapClickAction() {
				var that = this;
				var maps = this._mapContext.$getAppMap();
				maps.onclick = function(point) {
					console.log(point);

					point.iconPath = '../../static/address_2.png';
					point.id = 100

					that.latitude = point.latitude;
					that.longitude = point.longitude;

					that._mapContext.moveToLocation({
						latitude: point.latitude,
						longitude: point.longitude,
					})

					let list = JSON.parse(JSON.stringify(that.markers));

					let isFrist = 0;

					list.forEach(function(item) {
						if (item.id == 100) {
							isFrist = 1;
							item.latitude = point.latitude;
							item.longitude = point.longitude;
						} else {

						}
					});

					if (isFrist == 0) {
						that.markers = that.markers.concat(point);
					} else {
						that.markers = list;
					}

					//that.markers = list;

					console.log(_item)
					// if (_item.length > 0) {
					// 	console.log("=============平移：", point.latitude)
					// 	console.log("=============平移：", point.longitude)
					// 	that._mapContext.translateMarker({
					// 		markerId: 100,
					// 		destination: {
					// 			latitude: point.latitude,
					// 			longitude: point.longitude,
					// 		},
					// 		fail(e) {
					// 			console.log(e)
					// 		}
					// 	})
					// } else {
					// 	console.log("=============新增")
					// 	that.markers = that.markers.concat(point);
					// }
				};
			},
			goToEdit() {
				let url = "../addEquip/addEquip?cameara=" + JSON.stringify(this.cameara)
				uni.navigateTo({
					url: url
				});
			},
			add() {
				uni.navigateTo({
					url: '../addEquip/addEquip'
				});
			},
			updateAction(index) {
				let cameara = JSON.parse(JSON.stringify(this.cameara))

				let selfClick = this.markers.filter(item => {
					if (item.id == 100) {
						return item
					}
				})
				selfClick = selfClick[0];
				console.log("=========================selfClick:", JSON.stringify(selfClick))
				let selfAuto = this.markers.filter(item => {
					if (item.id == 1) {
						return item
					}
				})
				selfAuto = selfAuto[0];
				console.log("=========================selfAuto:", JSON.stringify(selfAuto))
				this.cameara = cameara;

				// 用户当前位置
				if (index == 0) {
					cameara.latitude = selfAuto.latitude;
					cameara.longitude = selfAuto.longitude;
				} else {
					// 用户手选位置
					cameara.latitude = selfClick.latitude;
					cameara.longitude = selfClick.longitude;
				}
				this.$store.dispatch('updateEquipDetails', {data: cameara})
			},
			// 拖拽地图
			regionchange(event) {
				console.log("========中心点改变1")
				if (event.type == 'regionchange') {
					//this.getCenterLanLat()
				}
			},
			// 获取当前地图中心的经纬度
			getCenterLanLat() {
				console.log("========中心点改变2")
				let self = this
				self._mapContext.getCenterLocation({
					altitude:true,
					type: 'gcj02',
					success: (res) => {
						let address = {
							latitude: res.latitude,
							longitude: res.longitude
						}

						let list = JSON.parse(JSON.stringify(self.markers));
						let isFrist = 0;

						list.forEach(function(item) {
							if (item.id == 1000) {
								isFrist = 1;
								item.latitude = res.latitude;
								item.longitude = res.longitude;
							}
						});

						if (isFrist == 0) {
							console.log("========中心点改变20")
							self.markers = self.markers.concat({
								id: 1000,
								width: 50,
								height: 50,
								latitude: address.latitude,
								longitude: address.longitude,
								iconPath: "../../static/address_3.png",
							});
						} else {
							console.log("========中心点改变21")
							self.markers = list;
						}
					},
					fail: (err) => {
						// console.log('获取当前地图中心的经纬度2', err);
					}
				})
			},
			tapMap(e) {
				var that = this;
				var id = e.currentTarget.id;
				var maps = this._mapContext.$getAppMap();
				console.log("============maps:", maps)
				maps.onclick = function(point) {
					console.log(point);

					point.iconPath = '../../static/address_2.png';
					point.id = 100

					that._mapContext.moveToLocation({
						latitude: point.latitude,
						longitude: point.longitude,
					})

					let list = JSON.parse(JSON.stringify(that.markers));

					let isFrist = 0;

					list.forEach(function(item) {
						if (item.id == 100) {
							isFrist = 1;
							item.latitude = point.latitude;
							item.longitude = point.longitude;
						} else {

						}
					});

					if (isFrist == 0) {
						that.markers = that.markers.concat(point);
					} else {
						that.markers = list;
					}

					//that.markers = list;

					console.log(_item)
					// if (_item.length > 0) {
					// 	console.log("=============平移：", point.latitude)
					// 	console.log("=============平移：", point.longitude)
					// 	that._mapContext.translateMarker({
					// 		markerId: 100,
					// 		destination: {
					// 			latitude: point.latitude,
					// 			longitude: point.longitude,
					// 		},
					// 		fail(e) {
					// 			console.log(e)
					// 		}
					// 	})
					// } else {
					// 	console.log("=============新增")
					// 	that.markers = that.markers.concat(point);
					// }
				};
			},
			goToSelectCamera() {
				uni.navigateTo({
					url: '../listPage/listPage'
				});
				console.log("获取周围美食");
			},
			reGetLocation() {
				this.getLocationInfo();
			},
			// 确认授权后，获取用户位置
			getLocationInfo() {
				const that = this;
				uni.getLocation({
					isHighAccuracy: true,
					highAccuracyExpireTime: 3500,
					accuracy: 'best',
					altitude:true,
					type: "gcj02",
					success: function(res) {

                        console.log("============================定位结果res:",res);
						// 暂时
						that.longitude = res.longitude; //118.787575;
						that.latitude = res.latitude; //32.05024;
						//精确度信息
						that.accuracy = res.accuracy;
						that.altitude = res.altitude;
						that.horizontalAccuracy = res.horizontalAccuracy;


						that._mapContext.moveToLocation({
							latitude: res.latitude,
							longitude: res.longitude,
						})


						let list = JSON.parse(JSON.stringify(that.markers));

						let isFrist = 0;

						list.forEach(function(item) {
							if (item.id == 1) {
								isFrist = 1;
								item.latitude = res.latitude;
								item.longitude = res.longitude;
							} else {

							}
						});

						if (isFrist == 0) {
							that.markers.push({
								id: 1,
								width: 50,
								height: 50,
								latitude: res.latitude,
								longitude: res.longitude,
								iconPath: "../../static/address_1.png",
								width: that.markerHeight, //宽
								height: that.markerHeight, //高
								color: '#FFFFFF'
							})
						} else {
							that.markers = list;
						}


					},
					fail(err) {
						uni.showToast({
							icon: "error",
							title: "获取位置出错"
						})
						console.log(err)
					}
				});
			},
			getList() {
				console.log("获取周围美食");
				console.log(this.markers.length)
			},
			historyPosition() {
				const returnedTarget = Object.assign(this.$store.state.equip.currentData, this.$store.state.equip.currentDataDetails);
				let cameara=returnedTarget
				if (cameara.longitude) {
					console.log("==============更新旧点")

					// cameara.longitude = info[0];
					// cameara.latitude = info[1];

					let point = {};
					point.iconPath = '../../static/address_4.png';
					point.id = 10000
					point.latitude = cameara.latitude;
					point.longitude = cameara.longitude;

					let list = JSON.parse(JSON.stringify(this.markers));

					let isFrist = 0;

					list.forEach(function(item) {
						if (item.id == 10000) {
							isFrist = 1;
							item.latitude = cameara.latitude;
							item.longitude = cameara.longitude;
						}
					});

					if (isFrist == 0) {
						this.markers = this.markers.concat(point);
					} else {
						this.markers = list;
					}
					console.log("=====================this.markers:", JSON.stringify(this.markers))
				} else {
					let list = JSON.parse(JSON.stringify(this.markers));
					let _index = 10000;
					list.forEach(function(item, index) {
						if (item.id == 10000) {
							_index = index
						}
					});
					if (_index != 10000) {
						list.splice(_index, _index)
					}
					this.markers = list;

				}


			},
			moveTo(index) {

				let point_list = this.markers.filter(item => {
					if (item.id == index) {
						return item
					}
				})
				let point = point_list[0];
				if (point_list.length > 0) {
					this._mapContext.moveToLocation({
						latitude: point.latitude,
						longitude: point.longitude,
					})
				}

			},
			getById(id) {
				this.$u.post(config.api + '/xfhrshInternet/service/selPicture', {
					subjectId: id
				}).then(res => {
					if(res.code==0){
						this.$store.dispatch('setCurrentEquipDtails', {data: res.data[0]})
					}
					//this.camera_list = res;
				});
			},
		},
		onUnload: function() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		},
		onLoad() {
			// 监听事件  
			uni.$on('updateCamera', (cameara) => {
				setTimeout(() => {
					this.historyPosition()
				}, 2500)
			})
		},

		onUnload() {
			// 移除监听事件  
			uni.$off('updateCamera');
		},
	};
</script>

<style lang="scss">
	.u-nav-slot {
		padding: 0 20rpx 0 0;
	}

	.cameraInfo {
		margin-top: 20rpx;
		margin-bottom: 20rpx;

		.btnListBox {
			display: flex;
			width: 300rpx;
			justify-content: space-around;
			align-items: center;
			margin-bottom: 20rpx;
			margin-left: 10rpx;
		}
	}

	.cameraItem {
		margin: 0 24rpx;
		margin-top: 30rpx !important;
		border: 1px solid #A3A8A8;
		border-radius: 10rpx;
		padding: 10rpx;

		.editItem {
			display: flex;
			flex-direction: row;
			justify-content: flex-end;
			margin: 20rpx 0;

			.editItemBtn {
				border: 1rpx solid #A3A8A8;
				border-radius: 4rpx;
				padding: 4rpx 4rpx;
				display: flex;
				flex-direction: row;
				justify-content: center;
				align-items: center;
			}
		}

		.cameraItemLi {
			display: flex;
			flex-direction: row;
			justify-content: space-between;

			.unKnow {
				color: red;
			}
		}
	}

	.btn {
		margin-top: 10rpx;
	}

	.btnList {
		display: flex;
		flex-direction: row;
		width: 100%;
		justify-content: space-around;
	}

	.btnList1 {
		display: flex;
		flex-direction: row;
		width: 100%;
		justify-content: space-around;
	}

	.tipsList {
		margin: 10rpx;
	}

	.selectPointPosition {
		display: flex;
		justify-content: space-between;
	}
</style>
