<template>
	<view class="page">
		<view class="search" @click="searchaddress">
			<view class="region dis a-c j-s" style="position: absolute; z-index: 9;">
				<text>{{city}}</text>
				<view style="width: 1px;height: 60%;background-color: #999;"></view>
			</view>
			<u-search style="position: relative;" placeholder="请输入位置/地名等" :show-action="false" :height='80'
				:input-style="{paddingLeft: '50px'}" :disabled="true">
			</u-search>
			<view v-if="searchshow" class="" style="width: 100%;height: 100vh;background-color: #fff;">
			</view>
		</view>
		<map v-if="mapshow" id="map1" style="width: 100%; height: 300px;" :key="timeKey" :latitude="latitude"
			:longitude="longitude" :markers="covers" :controls="controls" scale='16' theme="satellite"
			:showLocation="true" @controltap="controltap" @regionchange="getCenterLocation">
			<cover-image src="/static/image/map/p1.png"
				style="width: 30px; height: 30px;position: absolute;top: 42%;left:45%;"></cover-image>
		</map>
		<view class="Peripheral dis f-c">
			<view class="dis a-c j-s" v-for="(item,index) in addressList" :key="index" style="margin-bottom: 10px;"
				@click="addressClick(item)">
				<view class="">
					<text v-if="index==0" style="font-size: 16px;color:#2979ff;font-weight: bold;">{{item.name}}</text>
					<text v-else style="font-size: 16px;">{{item.name}}</text>
					<view class="dis a-c" style="color: #999;font-size: 12px;">
						<text>{{item.distance}}</text>
						<view style="width: 1px;height: 16px;background-color: #999;margin: 0 10px;"></view>
						<text>{{item.address}}</text>
					</view>
				</view>
				<u-icon v-if="index==0" name="checkmark-circle-fill" color="#2979ff" size="40"></u-icon>
				<u-icon v-else name="checkmark-circle" color="rgb(217,217,217)" size="40"></u-icon>
			</view>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				mapshow: false,
				timeKey: 0,
				mapKey: '197d1a12301a306f82533a23651807b8',
				address: "",
				city: "",
				cityInfo: {},
				searchshow: false,
				id: 0, // 使用 marker点击事件 需要填写id
				title: 'map',
				latitude: 0,
				longitude: 0,
				covers: [],
				controls: [{
					id: 1,
					position: {
						left: 360,
						top: 250,
						width: 40,
						height: 40,
					},
					iconPath: "/static/image/map/d1.png",
					clickable: true,
				}],
				addressList: [],
				type: '',
				keywords: "",
			}
		},
		onShow() {
			if (this.latitude == 0) {
				this.getCurrentLocation();
			}
		},
		onLoad(params) {
			this.type = params.type;
		},
		onReady() {
			this.mapContext = uni.createMapContext("map1", this);
		},
		methods: {
			getCurrentLocation() {
				//获取当前的地理位置
				let vthis = this;
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: function(res) {
						vthis.latitude = res.latitude;
						vthis.longitude = res.longitude;
						vthis.city = res.address.city;
						vthis.cityInfo = res;
						vthis.mapshow = true;
						vthis.addressConversion();
					},
					fail: function(err) {
						uni.showModal({
							title: '提示',
							content: '请打开定位服务',
							success: ({
								confirm,
								cancel
							}) => {
								if (confirm) {
									// android平台
									if (uni.getSystemInfoSync().platform == 'android') {
										var Intent = plus.android.importClass(
											'android.content.Intent');
										var Settings = plus.android.importClass(
											'android.provider.Settings');
										var intent = new Intent(Settings
											.ACTION_LOCATION_SOURCE_SETTINGS);
										var main = plus.android.runtimeMainActivity();
										main.startActivity(intent); // 打开系统设置GPS服务页面

									}
								}
								// 用户取消前往开启定位服务
								if (cancel) {
									// do sth...
								}
							}
						});
					}
				});
			},
			controltap() {
				this.getCurrentLocation();
				this.timeKey++;
			},
			addressConversion() {
				uni.request({
					url: `https://restapi.amap.com/v3/place/around?key=${this.mapKey}&location=${this.longitude},${this.latitude}&radius=5000&types=&city=${this.city}&keywords=${this.keywords}`,
					method: "GET",
					success: (res) => {
						this.addressList = res.data.pois;
						this.addressList.map(val => {
							val.distance = this.conversion(val.distance);
							return val;
						})
					}
				});
			},
			searchaddress() {
				uni.navigateTo({
					url: "/pages/caragent/addressSearch?info=" + JSON.stringify(this.cityInfo)
				})
			},
			getCenterLocation() {
				this.mapContext.getCenterLocation({
					success: (res) => {
						this.latitude = res.latitude;
						this.longitude = res.longitude;
						this.mapshow = true;
						this.addressConversion();
					}
				})
			},

			addressClick(item) {
				//选中之后返回上一页并修改数据
				let pages = getCurrentPages(); //获取所有页面栈实例列表
				let nowPage = pages[pages.length - 1]; //当前页页面实例
				let prevPage = pages[pages.length - 2]; //上一页页面实例
				let data = item.location.split(',')
				switch (prevPage.route) {
					case 'pages/roadRescue/Grounding':
						prevPage.$vm.dataInfo.rescuePosition = item.address; //详细地址
						break;
					case 'pages/roadRescue/trailer':
						if (this.type == '1') {
							prevPage.$vm.dataInfo.rescueStarting = item.address; //详细地址
							prevPage.$vm.dataInfo.startingLongitude = data[0]; //详细地址
							prevPage.$vm.dataInfo.startingLatitude = data[1]; //详细地址
						} else {
							prevPage.$vm.dataInfo.rescuePosition = item.address; //详细地址
							prevPage.$vm.dataInfo.positionLongitude = data[0]; //详细地址
							prevPage.$vm.dataInfo.positionLatitude = data[1]; //详细地址
						}
						break;
					case 'pages/roadRescue/replacement':
						prevPage.$vm.dataInfo.rescuePosition = item.address; //详细地址
						break;
					default:

				}
				uni.navigateBack({ //uni.navigateTo跳转的返回，默认1为返回上一级
					delta: 1
				});

			},
			conversion(data) {
				if (data < 1000) {
					return data + 'm'
				} else {
					return data / 1000 + 'km'
				}
			},
			add() {
				// this.gomapApp(37.857133, 112.521744, "北京市")
			},
			gomapApp(latitude, longitude, name) {
				let url = "";
				if (plus.os.name == "Android") { //判断是安卓端
					plus.nativeUI.actionSheet({ //选择菜单
						title: "选择地图应用",
						cancel: "取消",
						buttons: [{
							title: "腾讯地图"
						}, {
							title: "百度地图"
						}, {
							title: "高德地图"
						}]
					}, function(e) {
						console.log(e);
						switch (e.index) {

							//下面是拼接url,不同系统以及不同地图都有不同的拼接字段
							case 1:
								//注意referer=xxx的xxx替换成你在腾讯地图开发平台申请的key
								url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=xxx`;
								break;
							case 2:
								url =
									`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&coord_type=gcj02&src=andr.baidu.openAPIdemo`;
								break;
							case 3:
								url =
									`amapuri://route/plan/?sid=&slat=${latitude}&slon=${longitude}&sname=太原市&did=&dlat=${39.990496}&dlon=${116.482086}&dname=${name}&dev=0&t=0`;
								break;
							default:
								break;
						}
						if (url != "") {
							url = encodeURI(url);
							//plus.runtime.openURL(url,function(e){})调起手机APP应用
							plus.runtime.openURL(url, function(e) {
								plus.nativeUI.alert("本机未安装指定的地图应用");
							});
						}
					})
				} else {
					// iOS上获取本机是否安装了百度高德地图，需要在manifest里配置
					// 在manifest.json文件app-plus->distribute->apple->urlschemewhitelist节点下添加
					//（如urlschemewhitelist:["iosamap","baidumap"]）  
					plus.nativeUI.actionSheet({
						title: "选择地图应用",
						cancel: "取消",
						buttons: [{
							title: "腾讯地图"
						}, {
							title: "百度地图"
						}, {
							title: "高德地图"
						}]
					}, function(e) {
						switch (e.index) {
							case 1:
								url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=xxx`;
								break;
							case 2:
								url =
									`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`;
								break;
							case 3:
								url =
									`iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
								break;
							default:
								break;
						}
						if (url != "") {
							url = encodeURI(url);
							plus.runtime.openURL(url, function(e) {
								plus.nativeUI.alert("本机未安装指定的地图应用");
							});
						}
					})
				}
			}
		},
		onUnload() {
			this.mapKey = 0;
		}
	}
</script>

<style>
	.mymap__map {
		width: 100%;
		height: 400px;
	}

	.search {
		padding: 10px;
		background-color: #fff;
	}

	.region {
		width: 70px;
		height: 40px;
		background-color: #f2f2f2;
		padding: 5px 10px;
		border-bottom-left-radius: 50px;
		border-top-left-radius: 50px;
	}

	.Peripheral {
		width: 100%;
		height: calc(100vh - 44px - 360px);
		overflow-y: auto;
		background-color: white;
		padding: 15px;
		margin-top: 10px;
	}
</style>