// 计算两点之间距离
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米内使用缓存位置
	    const myGeo = new MapIns.Geocoder(); // 创建地理编码实例
		const point = new MapIns.Point(longitude, latitude) //转换当前坐标点
		myGeo.getLocation(point, function(result){ // 根据坐标得到地址描述, result为对应的地理位置详细信息
		    if (result){      
		        const addressComponent = result.addressComponents			
		        let markers = [{
		        	latitude: latitude,
		        	longitude: longitude,
		        }]
		        let textData = {
		        	desc: result.address,
		        	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 {
		reslove(cacheUserLocation)
	}
}

const WXReverseGeocoder = (reslove, reject) => {
	let {MapIns} = getApp().globalData
	MapIns.regeocoding({
		iconWidth: 20,
		iconHeight: 30,
		success: (data) => {
			const res = data.wxMarkerData[0]
			let addressComponent = data.originalData.result.addressComponent
			let markers = [{
				id: res.id,
				latitude: res.latitude,
				longitude: res.longitude,
				iconPath: res.iconPath,
				width: res.width || 20,
				height: res.height || 30
			}]

			let textData = {
				name: res.address || res.desc,
				desc: res.desc,
				province: addressComponent.province,
				city: addressComponent.city,
				district: addressComponent.district,
				siteName: res.address || res.desc
			}
			//整理数据结构
			reslove({
				markers,
				textData,
				latitude: res.latitude,
				longitude: res.longitude,
			})
		},
		fail: (err) => {
			reject(err)
		}
	})
}

//H5获取定位经纬度 注：PC上使用 Chrome 浏览器的时候，位置信息是连接谷歌服务器获取的，国内用户可能获取位置信息失败。
const BMapGetLocation = () => {
	return new Promise((reslove, reject) => {
		let {MapIns} = getApp().globalData
		const geolocation = new MapIns.Geolocation();
		geolocation.enableSDKLocation(); //开启SDK辅助定位
		geolocation.getCurrentPosition(function(res){
			const errCode = {
				6: '没有权限，定位被拒绝',
				2: '定位不可用',
				8: '定位超时',
			}
			const status = this.getStatus()
			if(status === 0){
			   reslove({latitude: res.latitude, longitude: res.longitude})
			} else {
				uni.showToast({
					title: errCode[status] || res,
					icon: 'none',
					duration: 3000
				});
			}						
		})          
	})
}
let BMap = {
	reverseGeocoder, //高德地图Functions API
	BMapGetLocation
}

export default BMap
