var arr = [];
mui.plusReady(function(){
	
	var maps = [{
			pname: 'com.baidu.BaiduMap',
			action: 'baidumap',
			name: '百度地图'
		}, {
			pname: 'com.autonavi.minimap',
			action: 'iosamap',
			name: '高德地图'
		}
		// , {
		// 	pname: 'com.google.android.apps.maps',
		// 	action: 'com.google.android.apps.maps',
		// 	name: '谷歌地图'
		// }
		// , {
		// 	pname: 'com.tencent.map',
		// 	action: 'com.google.android.apps.maps',
		// 	name: '腾讯地图'
		// },
	]
	// checkApp("com.baidu.BaiduMap", "baidumap", "百度地图")
	// checkApp("com.autonavi.minimap", "iosamap", "高德地图")
	// checkApp("com.google.android.apps.maps", "com.google.android.apps.maps", "谷歌地图")
	// 判断地图软件是否安装
	// maps= toJson(maps)
	// //console.log(maps)
	$.each(maps, function(i, v) {//不能写进点击事件函数里 不然点击一次增加一个title
		var that = this
		checkApp(that.pname, that.action, that.name)
	})
	
	function checkApp(pn, ac, name) { //  pname：android 包名  action：ios包名   name：用作底部弹出
		if (plus.runtime.isApplicationExist({
			pname: pn, //包名
			action: ac //ios包名
		})) {
			// //console.log("微信应用已安装");
			title = {
				title: name
			};
			arr.push(title)
		} else {
	
		}
	}
	var viewportHeight = $(window).height();
	$(document).on('scroll', function() {
		var scrollTop = $(window).scrollTop();
		var x = scrollTop + viewportHeight - $("#apear").position().top;
		if (x > 0)
		{
			app.loadNextPage();
		}
	})
})

function copyToClip (text) {
	var Context = plus.android.importClass("android.content.Context");
	var main = plus.android.runtimeMainActivity();
	var clip = main.getSystemService(Context.CLIPBOARD_SERVICE);
	plus.android.invoke(clip,"setText",text.toString());
	mui.toast("复制成功");
}

function invokeNavi(from, destination) {
	if (0 == arr.length) {
		var startpos= bMapTransQQMap(from[1], from[0])
		var endpos = bMapTransQQMap(destination[1], destination[0])
		var urlStr = encodeURI('http://uri.amap.com/navigation?from='+startpos.lng+','+startpos.lat+',起点&to='+endpos.lng+','+endpos.lat+',终点&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0')
		plus.runtime.openURL(urlStr)
		return false
	} else {
		openMapApp(destination)
	}
}

function invokeSearch(address) {
	if (0 === arr.length) {
		var urlStr = encodeURI('http://api.map.baidu.com/geocoder?address='+address+'&output=html&src=cn.com.zgqlg.app')
		plus.runtime.openURL(urlStr)
	} else {
		var map = arr[0];
		var title = map.title;
		switch (title) {
			case "百度地图":
				goMaps(
					"baidumap://map/geocoder?address="+address+"&src=cn.com.zgqlg.app"
				)
				break;
			case "高德地图":
				goMaps('androidamap://poi?sourceApplication=nyx_super&keywords=' + address +
					'&output=html&src="全亮共"')
				break;
		}
	}
}

function openMapApp(destination) {
	function realOpen(idx) {
		var shopLat = destination[0];
		var shopLng = destination[1];
		var title = arr[idx].title;
		// var   i1 = new Intent();
		switch (title) {
			case "百度地图":
				// if (plus.os.name == "Android") {
				// 				plus.runtime.openURL(
				// 					"baidumap://map/direction?origin=latlng:39.98871,116.43234|name:我的位置&destination=31.236244,121.480239&mode=driving&src=webapp.navi.hanguosoft.yinyijianghu",
				// 					function(error) {
				// 						mui.alert('打开' + title + '失败');
				// 					});
				// }
				goMaps(
					"baidumap://map/direction?origin=我的位置&destination="+shopLat+","+shopLng+"&mode=driving&src=cn.com.zgqlg.app"
				)
				
				break;
			case "高德地图":
		
				var endpos = bMapTransQQMap(shopLng, shopLat)
				// 				plus.runtime.openURL('androidamap://navi?sourceApplication=nyx_super&lat=' + endpos.lat + '&lon=' + endpos.lng +
				// 					'&mode=driving&region=www&output=html&src="全亮共"',
				// 					function(e) {
				// 						mui.alert('打开' + title + '失败');
				// 					})
				goMaps('androidamap://navi?sourceApplication=nyx_super&lat=' + endpos.lat + '&lon=' + endpos.lng +
					'&mode=driving&output=html&src="全亮共"')
					
				break;
		}
	}
	
	//底部弹出选择地图软件
	if (arr.length === 1) {
		realOpen(0)
	}else{
		plus.nativeUI.actionSheet({
			title: "请选择导航使用的地图",
			cancel: "取消",
			buttons: arr
		}, function(e) {
			realOpen(e.index - 1)
		})
	}
}

function goMaps(url) {
	var mContext = plus.android.runtimeMainActivity();
	var Uri = plus.android.importClass('android.net.Uri');
	var Intent = plus.android.importClass('android.content.Intent');
	var intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
	mContext.startActivity(intent);
}

const waiting = plus.nativeUI.showWaiting("正在加载")

const app = new Vue({
	el: '#app',
	data() {
		return {
			orderList: [
			],
			location: [0,0],
			highlightText: "",
			currentPage: 1,
			isLoading: false,
		}
	},
	methods: {
		getDistance(from, to) {
			var radLat1 = from[0]*Math.PI / 180.0;
			var radLat2 = to[0]*Math.PI / 180.0;
			var a = radLat1 - radLat2;
			var b = from[0]*Math.PI / 180.0 - to[0]*Math.PI / 180.0;
			var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
			Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
			s = s *6378.137 ;// EARTH_RADIUS;
			if (s < 1.5) {
				return `${(s * 1000).toFixed(2)}m`;
			}
			if (s > 50) {
				return `>50km`;
			}
			return `${s.toFixed(2)}km`;
		},
		loadNextPage() {
			if (this.isLoading) return;
			this.isLoading = true;
			$.ajax({
				url: qlgUrl("app/orders/shundaiList"),
				method: "GET",
				data: {
					page: this.currentPage+1,
				},
				dataType: 'json',
				success: (res) => {
					this.isLoading = false;
					if(res.status == 1){
						this.currentPage += 1;
						$.each(res.data, (k, i)=>{
							this.orderList.push(i)
						});
					}else{
						mui.alert(res.msg);
					}
				},
				error: function(err){
					mui.alert("请求失败");
					this.isLoading = false;
				}
			});
		},
		copyText() {
			copyToClip(this.highlightText)
		},
		dismissHighLight() {
			this.highlightText = "";
		},
		setHighLightText(text){
			this.highlightText = text;
		},
		navi(destination) {
			invokeNavi(this.location, destination);
		},
		search: invokeSearch,
		loadData() {
			$.ajax({
				url: qlgUrl("app/orders/shundaiList"),
				method: "GET",
				data: {
					page: this.currentPage,
					lat: this.location[0],
					lng: this.location[1],
				},
				dataType: 'json',
				success: (res) => {
					waiting.close();
					if(res.status == 1){
						this.orderList = res.data;
					}else{
						mui.alert(res.msg);
					}
				},
				error: function(err){
					waiting.close();
					mui.alert("请求失败");
					self.back();
				}
			});
		},
	},
	created() {
		var lat = localStorage.getItem('lat');
		var lng = localStorage.getItem('lng');
		if (!lat || !lng) {
			plus.geolocation.getCurrentPosition((p) => {
				console.log(p.coords.latitude);
				console.log(p.coords.longitude);
				this.location=[p.coords.latitude, p.coords.longitude];
				this.loadData();
			},function (err) {
				mui.alert('获取当前位置失败')
				waiting.close();
			})
		} else {
			this.location=[lat, lng];
			this.loadData();
		}
	},
})