<template>
	<view class="ChargingStationMap_body">
		<map @tap='mapTap' :scale="10" @callouttap='callouttap' :circles='circles' :show-location='true'
			@regionchange='regionchange' id="map_Id" @markertap='markertap' :markers="markers"
			:latitude="location.latitude" :longitude="location.longitude" class="ChargingStationMap">
			<cover-view slot="callout">
				<block v-for="(item,index) in markers" :key="index">
					<cover-view class="customCallout" :marker-id="item.id">
						<cover-image class="customCallout_img" src="../../static/customCallout.png"></cover-image>
						<cover-view></cover-view>
						<cover-view class="content flex column">
							<cover-view style="width: 100%;" class="flex">
								<cover-view class="content_label">
									闲 {{ item.idleNum}}
								</cover-view>
								<cover-view style="text-align: center;line-height: 26rpx;   padding-top: 10rpx;"
									class="oneflex flex jc ac">
									￥{{tool.getnum(item.totalFee)}}</cover-view>
							</cover-view>
							<cover-view class="content_value flex oneflex ac ">
								<cover-view class="content_value_price oneflex"> 快 {{item.fastNum}}
								</cover-view>
								<cover-view class="content_value_price oneflex"> 慢
									{{item.slowNum}}</cover-view>
							</cover-view>
						</cover-view>
					</cover-view>
				</block>
			</cover-view>
		</map>
		<station-item :data="stationData" style="position: absolute;bottom: 50rpx;left: 0; right: 0; margin: 0 auto;"
			v-if="stationData"></station-item>
	</view>
</template>

<script>
	// import {
	// 	page
	// } from "@/pages/home/AntiCorruptionLayer.js"
	import station from "@/api/station.js"
	import utils from "./static/utils.js"
	import stationItem from "@/components/stationItem/stationItem.vue"
	export default {
		name: "ChargingStationMap",
		components: {
			stationItem
		},
		props: {
			pageData: {
				type: Object,
				default: () => null
			}
		},
		data() {
			return {
				user: uni.getStorageSync('user'),
				showLabelLength: 30,
				standbyMarkers: [],
				markersTimer: null,
				stationData: null,
				circles: [],
				getListTimer: null,
				location: null,
				markers: [],
				mapContext: null,
				isGetRegion: false,
			};
		},
		created() {
			this.init()
		},
		methods: {
			onshow() {
				let that = this;
				this.mapContext.getCenterLocation({
					success(e) {
						let {
							latitude,
							longitude
						} = e; 
						that.getRegion({
							detail: {
								centerLocation: {
									latitude,
									longitude
								}
							}
						})
					}
				})
			},
			mapTap() {
				this.stationData = null
			},
			getDetails(data) {
				if(!this.user) {
					uni.showToast({
						title: '登陆后可查看',
						icon: 'none',
						success() { 
						}
					});
					return
				}
				station.getSiteDetails(data).then(res => {
					res.data = [res.data];
					this.tool.difTags(res);
					let data = new this.tool.Anticorrosive(res, page);
					this.stationData = data.list[0];
				})
			},
			//点击气泡
			callouttap(e) {
				try {
					let id = this.standbyMarkers.find(item => item.id == e.detail.markerId)['siteId'];
					this.getDetails({
						id,
						stationLat: this.location.latitude,
						stationLng: this.location.longitude,
					})
				} catch (e) {
					//TODO handle the exception
				}
			},
			filterMarks(markers) {
				if (this.markers.length) {
					let idList = this.markers.map(item => item.siteId);
					if (this.markers.length >= markers.length) {
						return markers.filter(item => !idList.includes(item.id))
					} else {
						return markers.filter(item => idList.includes(item.id))
					}
				} else {
					return null
				}
			},
			getRegion(e) {
				let that = this;
				return new Promise((re, rj) => {
					this.mapContext.getRegion({
						success: res => {
							let juli = utils.getDistance(res.northeast.latitude, res.northeast
								.longitude, res.northeast.latitude, res.southwest.longitude);
							that.$emit('update:pageData', Object.assign(that.pageData, {
								ranger: (juli / 2 / 1000) + 5,
								...e.detail.centerLocation
							}));
							re('success')
						},
						fail: (data, code) => {
							rj(JSON.stringify(data))
						}
					})
				})
			},
			regionchange(e) {
				if (e.type == 'end') {
					this.getRegion(e).then(res => {
						this.getList(1500)
					})
				}
			},
			markertap(e) {
				console.log(e)
			},
			//定位处理
			locationProcessing(markerList = []) {
				if (markerList && markerList.length) {
					let that = this
					let newMarkerList = markerList.map((item, index) => {
						let id = Number(`${item.id.substr(item.id.length - 9,item.id.length)}`);
						let configure = {
							siteId: item.id,
							id,
							width: 20,
							height: 20,
							latitude: item.stationLat,
							longitude: item.stationLng,
							iconPath: '../../static/tt.png',
							// joinCluster: true, 
							customCallout: {
								anchorY: 0, // Y轴偏移量
								anchorX: 0, // X轴偏移量
								display: 'ALWAYS', // 一直展示 
							}
						}
						let data = Object.assign(JSON.parse(JSON.stringify(item)), configure);
						if (markerList.length > this.showLabelLength) delete data.customCallout
						return data
					});
					return newMarkerList;
				} else {
					// throw 'markerList.length of 0'
					return []
				}
			},
			addMarkers(newMarkers) {
				this.mapContext.addMarkers({
					markers: newMarkers,
					clear: true,
					success() {
						console.log('添加成功')
					},
					fail(err) {
						console.log(err, '添加失败')
					}
				})
			},
			WeightlessnessReduction(array) {
				return [...new Set(array)]
			},
			//获取列表
			getList(time = 1000) {
				let that = this;
				if (this.getListTimer) {
					clearTimeout(this.getListTimer);
					this.getListTimer = null
				}
				this.getListTimer = setTimeout(() => {
					uni.showLoading({
						title: '电站加载中',
						mask: true
					});
					console.log(this.pageData,'this.pageDatathis.pageDatathis.pageData')
					station[this.user?'getMapStations':'getMapTouristSites'](this.pageData).then(res => {
						// this.markers = [] 
						console.log(res, '电站列表')
						clearTimeout(this.markersTimer);
						this.markersTimer = null;
						this.markersTimer = setTimeout(() => {
							let newMarkers = this.locationProcessing(res.data)
							this.removeMarkers(newMarkers);
							this.standbyMarkers = newMarkers;
							if (this.standbyMarkers.length > this.showLabelLength) {
								this.addMarkers(this.standbyMarkers)
							} else {
								this.markers = this.standbyMarkers;
							}
							uni.hideLoading(); 
						}, 500)
					})
				}, time)
			},
			removeMarkers(newMarkers) {
				let standbyMarkersIds = this.standbyMarkers.length ? this.standbyMarkers.map(item => String(item.id)) : [];
				let newMarkersIds = newMarkers.length ? newMarkers.map(item => String(item.id)) : [];
				let ids = standbyMarkersIds.filter(item => !newMarkersIds.includes(item));
				// this.markers = [] 
				this.mapContext.removeMarkers({
					markerIds: ids
				});
				// this.mapContext.removeMarkers();
			},
			//获取定位
			async getPosition() {
				console.log('位置更行')
				let location = uni.getStorageSync('location');
				if (location) {
					this.location = uni.getStorageSync('location');
				} else {
					this.location = {
						longitude: 116.38,
						latitude: 39.90,
					}
				}
				// await this.tool.userLocationChenk().then(res => {}).catch(err => {})
				// await this.tool.getLocation().then(res => {
				// 	this.location = uni.getStorageSync('location');
				// }).catch(err => {
				// 	this.location = {
				// 		longitude: 116.38,
				// 		latitude: 39.90,
				// 	}
				// });
			},
			moveToLocation(longitude, latitude) {
				setTimeout(() => {
					this.mapContext.moveToLocation({
						longitude,
						latitude,
						success() {
							console.log('移动成功')
						},
						fail(e) {
							console.log(e, '移动失败')
						},
					})
				}, 500)
			},
			//初始化
			async init() {
				let that = this;
				// await this.getPosition();
				this.mapContext = uni.createMapContext("map_Id", this);
				this.$nextTick(() => {
					this.onshow()
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import 'index.scss';
</style>