<template>
	<view 
	class="addressMap"
	v-if="position.latitude && addressList.length">
		<map
		style="width: 100%;height: 500rpx;border-radius: 20rpx;" 
		:layer-style='5' 
		:show-location='true'
		:latitude="positionMap.latitude" 
		:longitude="positionMap.longitude" 
		:markers="addressMarkers" 
		:scale="scale" 
		@markertap="markertap"
		id="mapId"
		@callouttap="callouttap">
		</map>
	</view>
</template>

<script>
    import positionMixin from '@/mixins/position';
	export default {
		mixins: [positionMixin],
		name:"addressMap",
		props : {
			addressList : {
				default : []
			},
		},
		computed : {
			addressMarkers(){
				
				if (!this.addressList ||
				    this.addressList.length == 0 ||
				    !this.position || 
				    !this.position.latitude || 
				    !this.position.longitude) {
				    return []
				}
				
				this.addressList.forEach((item, index) => {
				    let distance = this.calculateDistance(
				        this.position.latitude,
				        this.position.longitude,
				        item.latitude,
				        item.longitude,
				    )
					
					item.width = 20 //图标icon 宽度
					item.height = 28 //图标icon 高度
				    item.distance = distance
					item.iconPath = ''
				})
				
				this.addressList.sort((a,b) => {
					return a.distance - b.distance
				})

				// 计算最大距离并设置缩放比例
				if (this.addressList.length > 1) {
					let maxDistance = 0
					for (let i = 0; i < this.addressList.length; i++) {
						for (let j = i + 1; j < this.addressList.length; j++) {
							const distance = this.calculateDistance(
								this.addressList[i].latitude,
								this.addressList[i].longitude,
								this.addressList[j].latitude,
								this.addressList[j].longitude
							)
							maxDistance = Math.max(maxDistance, distance)
						}
					}
					// 根据最大距离设置缩放比例
					// 距离越大，缩放比例越小
					if (maxDistance > 100) { // 
						this.scale = 5
					}else if (maxDistance > 50) { // 
						this.scale = 8
					}else if (maxDistance > 10) { // 10公里以上
						this.scale = 10
					} else if (maxDistance > 5) { // 5-10公里
						this.scale = 11
					} else if (maxDistance > 2) { // 2-5公里
						this.scale = 13
					} else { // 2公里以内
						this.scale = 15
					}
				}
				
				return this.addressList
			},
			positionMap(){
				if(this.addressMarkers.length == 0){
					return {
						latitude : 0,
						longitude : 0,
					}
				}
				
				return {
					latitude : this.addressMarkers[0].latitude,
					longitude : this.addressMarkers[0].longitude,
				}
			}
		},
		data() {
			return {
				scale : 15,
			};
		},
		methods : {
			markertap(e){
				console.log(e);
				this.addressList.forEach(item => {
					if(item.id == e.detail.markerId){
						this.$emit('clickAddress', item)
					}
				})
			},
			callouttap(e){},
		},
	}
</script>

<style scoped lang="scss">
.addressMap{
	padding-bottom: 30rpx;
}
</style>