<template>
	<view><!-- 以下是测试用例 -->
	<u-button type="primary" text="开启定位" @click="startPosition()"></u-button>
	<u-button type="primary" :plain="true" text="增加定位" @click="addPosition(Math.floor(Math.random() * 10) + ``)"></u-button>
	<u--input v-model="value" placeholder="请输入需要清除的id" border="surround"></u--input>
	<u-button type="primary" text="关闭定位" @click="closePosition()"></u-button>
	<u-button type="primary" :plain="true" text="清空缓存" @click="cleanData()"></u-button>
	</view>
</template>
<script>
	import {updateLngAndLat} from '@/api/api.js';
	export default {
		name: "positionInfo",
		data() {
			return {
				value: '',
				positionInfo: {watchLocation: null,positionData: [],location: null},
				maximumAge: 30 * 1000};},
				methods: {/*** 检测是否开启定位*/
				checkOpenGPSServiceByAndroidIOS() {
					let system = uni.getSystemInfoSync(); // 获取系统信息
					if (system.platform === 'android') { // 判断平台
					var context = plus.android.importClass("android.content.Context");
					var locationManager = plus.android.importClass("android.location.LocationManager");
					var main = plus.android.runtimeMainActivity();
					var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
						if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
							uni.showModal({title: '提示',content: '请打开定位服务功能',showCancel: false, // 不显示取消按钮
							success() {
								if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
									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);
									main.startActivity(intent); // 打开系统设置GPS服务页面
								} else {
									return true;
									console.log('GPS功能已开启');
									}
								}
							});
						} else {
							return true;
						}
					} else if (system.platform === 'ios') {
						console.log("苹果");
						var cllocationManger = plus.ios.import("CLLocationManager");
						var enable = cllocationManger.locationServicesEnabled();
						var status = cllocationManger.authorizationStatus();
						plus.ios.deleteObject(cllocationManger);
						if (enable && status != 2) {
							return true;
							console.log("手机系统的定位已经打开");
						} else {
							console.log("手机系统的定位没有打开");
							uni.showModal({title: '提示',content: '请前往设置-隐私-定位服务打开定位服务功能',showCancel: false, // 不显示取消按钮
							success() {
								var UIApplication = plus.ios.import("UIApplication");
								var application2 = UIApplication.sharedApplication();
								var NSURL2 = plus.ios.import("NSURL");// 
								var setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");// 
								var setting2 = NSURL2.URLWithString("App-Prefs:root=LOCATION_SERVICES");
								var setting2 = NSURL2.URLWithString("app-settings:");//
								var setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION");// 
								var setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION_SERVICES");
								application2.openURL(setting2);
								plus.ios.deleteObject(setting2);
								plus.ios.deleteObject(NSURL2);
								plus.ios.deleteObject(application2);
								}
								});
						}
					}
					return false;
				},
				/*** 启动获取定位信息（建议登录时调用）*/
				startPosition() {
					let _this = this;
					if (this.locationInfo != undefined) {
						let positionData = this.locationInfo.positionData;
						if (positionData.length > 0) {
							let flag = _this.checkOpenGPSServiceByAndroidIOS();
							if (flag) {
								let watchLocation = plus.geolocation.watchPosition((position) => {
									let coords = position.coords;
									_this.locationInfo.location = coords;
									// console.log("获取经纬度信息：", coords.longitude, coords.latitude)//更新经纬度
									_this.pushPosition(coords.longitude, coords.latitude);
								}, function(e) {
									console.log('Gelocation Error: code - ' + e.code + '; message - ' + e.message);
								}, {maximumAge: _this.maximumAge});
								_this.locationInfo.watchLocation = watchLocation;//缓存经纬度信息
								this.$u.vuex('locationInfo', _this.locationInfo);
							}
						}
					}
				},
					/*** 增加获取位置信息的数量* @param {Object} id 传入的id（例如：repairId）*/
					addPosition(id) {
										let flag = this.checkOpenGPSServiceByAndroidIOS();
										if (flag) {
											let _this = this;
											let positionData = _this.locationInfo === undefined ? [] : _this.locationInfo.positionData;
											if (positionData.length === 0) {
												var timer = plus.geolocation.watchPosition((position) => {
													let coords = position.coords;
													this.$nextTick(() => {this.positionInfo = {...this.locationInfo};
													this.positionInfo.location = coords;// 
													console.log("获取经纬度信息：", this.positionInfo)
													this.$u.vuex('locationInfo', this.positionInfo);
													})//更新经纬度
													_this.pushPosition(coords.longitude, coords.latitude);
													}, function(e) {
														console.log('Gelocation Error: code - ' + e.code + '; message - ' + e.message);
														}, {maximumAge: _this.maximumAge});
														_this.positionInfo.watchLocation = timer;
											} else {
												let num = positionData.filter(t => t === id).length;
												if (num > 0) {
													return;
												}
											_this.positionInfo = {..._this.locationInfo};
											}
											positionData.push(id);
											_this.positionInfo.positionData = positionData;//缓存位置信息
											this.$u.vuex('locationInfo', _this.positionInfo);// 
											console.log("新增缓存位置信息：", this.locationInfo)
											}
					},
					/*** 清除定时任务* @param {Object} id 传入的id（例如：repairId）*/
					closePosition() {
						let id = this.value;
						let _this = this;//清除传入的id
						let positionData = _this.locationInfo.positionData.filter(t => t !== id);
						if (positionData.length === 0) {
							plus.geolocation.clearWatch(_this.locationInfo.watchLocation);
							_this.positionInfo = {watchLocation: null,positionData: [],location: null};
						} else {
								_this.positionInfo = {positionData: positionData,watchLocation: _this.locationInfo.watchLocation,location: _this.locationInfo.location};
						}
						_this.$u.vuex('locationInfo', _this.positionInfo);// 
						console.log("清除任务后的缓存：", _this.locationInfo)
					},
					/*** 往后台推送最新的经纬度信息* @param {Object} 传到后台存入redis的key(多个逗号分开)* @param {Object} longitude 经度* @param {Object} latitude  纬度*/
					pushPosition(longitude, latitude) {
							let id = this.locationInfo.positionData.join(",");
							updateLngAndLat({key: id,longitude: longitude,latitude: latitude})
							.then(res => {
								console.log("更新经纬度信息", res)});
					},
					cleanData() {
							this.$u.vuex('locationInfo', undefined);// 
							console.log("清空后的缓存:", this.locationInfo)	
					},
			},
	}
</script><style></style>