// 计算两点之间距离
const distance = (la1, lo1, la2, lo2) => {
	let La1 = la1 * Math.PI / 180.0;
	let La2 = la2 * Math.PI / 180.0;
	let La3 = La1 - La2;
	let Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
	let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
	s = s * 6378.137;
	s = Math.round(s * 10000) / 10000;
	s = s.toFixed(2);
	return s; //单位千米
}

//逆地址解析  坐标经纬度转地址描述
const reverseGeocoder = () => {
	return new Promise((reslove, reject) => {
		// #ifdef H5
		H5ReverseGeocoder(reslove, reject) // H5适配
		// #endif

		// #ifdef MP
		WXReverseGeocoder(reslove, reject) //微信地址逆解析
		// #endif	
	})
}

const H5ReverseGeocoder = (reslove, reject) => {
	let { userLocation, cacheUserLocation, MapIns} = getApp().globalData
	let { latitude, longitude } = userLocation //每次通过JSSDK获取经纬度后维护的当前最新位置 
	const oldLatitude = cacheUserLocation.latitude //已缓存纬度
	const oldLongitude = cacheUserLocation.longitude // 已缓存经度
	if(!oldLatitude || (oldLatitude && +distance(latitude, longitude, oldLatitude, oldLongitude) > 0.015 )){ //Distance()方法返回值为千米, 15米内使用缓存位置
		MapIns.plugin('AMap.Geocoder', function() {
			const geocoder = new MapIns.Geocoder()
			const lnglat = [longitude, latitude] // todo经纬度顺序固定
			geocoder.getAddress(lnglat, function(status, result) {
				if (status === 'complete' && result.info === 'OK') {
					// result为对应的地理位置详细信息
					const regeocode = result.regeocode
					const addressComponent = regeocode.addressComponent
					let markers = [{
						latitude: latitude,
						longitude: longitude,
					}]
					let textData = {
						desc: regeocode.formattedAddress,
						province: addressComponent.province,
						city: addressComponent.city,
						district: addressComponent.district,
						street: addressComponent.street + addressComponent.streetNumber,
					}
					const addressInfo = {markers, textData, latitude, longitude} //整理数据结构
					getApp().globalData.cacheUserLocation = addressInfo //缓存位置信息
					reslove(addressInfo)
				} else {
					const text = result === 'INVALID_USER_DOMAIN' ? '地址解析失败，当前IP未在高德域名白名单' : result
					uni.showToast({
						title: text,
						icon: 'none',
						duration: 3000
					});
				}
			})
		})
	} else {
		reslove(cacheUserLocation)
	}
}

const WXReverseGeocoder = (reslove, reject) => {
	let {MapIns} = getApp().globalData
	MapIns.getRegeo({
		iconWidth: 20,
		iconHeight: 30,
		success: (data) => {
			const res = data[0]
			let addressComponent = res.regeocodeData.addressComponent
			let markers = [{
				id: res.id,
				latitude: res.latitude,
				longitude: res.longitude,
				iconPath: res.iconPath,
				width: res.width,
				height: res.height
			}]
			let textData = {
				name: res.name,
				desc: res.desc,
				province: addressComponent.province,
				city: addressComponent.city.length ? addressComponent.city : '',
				district: addressComponent.district,
				siteName: res.regeocodeData.aois.length ? res.regeocodeData.aois[0].name : res.name
			}
			//整理数据结构
			reslove({
				markers,
				textData,
				latitude: res.latitude,
				longitude: res.longitude,
			})
		},
		fail: (err) => {
			reject(err)
		}
	})
}

//H5获取定位经纬度 注：PC上使用 Chrome 浏览器的时候，位置信息是连接谷歌服务器获取的，国内用户可能获取位置信息失败。
const AMapGetLocation = () => {
	return new Promise((reslove, reject) => {
		let {MapIns} = getApp().globalData
		MapIns.plugin('AMap.Geolocation', function() {		
		  const geolocation = new MapIns.Geolocation({
		    enableHighAccuracy: true, // 是否使用高精度定位，默认：true
		    timeout: 4000, // 设置定位超时时间，默认：无穷大
		  })
		  
		  geolocation.getCurrentPosition(function(status,result){
			    console.log('高德获取经纬度：', result)
		        if(status=='complete' && result.info === 'SUCCESS'){ //result是具体的定位信息
					const {lat, lng} = result.position
					reslove({latitude: lat, longitude: lng})
		        } else { // 定位出错		
					uni.showToast({
						title: result.message,
						icon: 'none',
						duration: 3000
					});
		        }
		  });
		})
	})
}
let AMap = {
	reverseGeocoder, //高德地图Functions API
	AMapGetLocation
}

export default AMap
