import myAmapFun from "@/utils/initmap.js"
import {showConfirm} from '@/utils/common'

var __CFG = null;
//系统参数
__CFG = __CFG || {
	'lat': '',
	'lng': '',
	'address': '',
	'city':'',
	"UxLocation": {
		"lng": "",
		"lat": "",
		"address": "",
		'city':'',
		'temperature':'',
		'weather':'',
		'icon':''
	},
	iconWeatherMap:[{tit:'风',val:'weaiona',children:['有风', '平静', '微风', '和风', '清风', '强风/劲风', '疾风', '大风', '烈风', '风暴', '狂爆风', '飓风', '热带风暴', '龙卷风']},
	{tit:'多云',val:'weaionb',children:['少云','多云']},
	{tit:'晴间多云',val:'weaionc',children:['晴间多云', ]},
	{tit:'雪',val:'weaiond',children:['雪', '阵雪', '小雪', '中雪', '大雪', '暴雪', '小雪-中雪', '中雪-大雪', '大雪-暴雪', '冷']},
	{tit:'雾',val:'weaione',children:['浮尘', '扬沙', '沙尘暴', '强沙尘暴', '雾', '浓雾', '强浓雾', '轻雾', '大雾', '特强浓雾']},
	{tit:'晴',val:'weaionf',children:['晴', '热']},
	{tit:'雨夹雪',val:'weaiong',children:['雨雪天气', '雨夹雪', '阵雨夹雪']},
	{tit:'雨',val:'weaionh',children:['阵雨', '雷阵雨', '雷阵雨并伴有冰雹', '小雨', '中雨', '大雨', '暴雨', '大暴雨', '特大暴雨', '强阵雨', '强雷阵雨', '极端降雨', '毛毛雨/细雨', '雨', '小雨-中雨', '中雨-大雨', '大雨-暴雨', '暴雨-大暴雨', '大暴雨-特大暴雨', '冻雨']},
	{tit:'阴',val:'weaioni',children:['阴','未知']},
	{tit:'霾',val:'weaionj',children:['霾', '中度霾', '重度霾', '严重霾',]},
	],
};
function setUxLocation(UxLocation){
    UxLocation = UxLocation || {};
	__CFG.lng = UxLocation.lng || '';
	__CFG.lat = UxLocation.lat || '';
	__CFG.address = UxLocation.address || UxLocation.addr || '';
	__CFG.city = UxLocation.city || UxLocation.city || '';
	__CFG.UxLocation = UxLocation;
}
//设置浏览器cookie
function set_cookie(key, value, expire, path){
	var keys = __CFG.C_PREFIX + key;
	path = path || '/';
	var a = keys + "=" + value;
	if(typeof(expire) != 'undefined'){
		var date = new Date();
		expire = parseInt(expire,10);
		date.setTime(date.getTime() + expire*1000);
		a += "; expires="+date.toGMTString();
	}
	a += ";path="+path;
	if(__CFG.C_DOMAIN){
		a += ";domain="+__CFG.C_DOMAIN;
	}
	document.cookie = a;
};

//删除浏览器cookie
function remove_cookie(key){
	if (!key) {
		return false;
	} else {
		var keys = __CFG.C_PREFIX + key;
		document.cookie = keys+"=;expires="+(new Date(0)).toGMTString();
	}
};

//获取浏览器cookie
function get_cookie(key) {
	if (!key) {
		return false;
	} else {
		var keys = __CFG.C_PREFIX + key;
		var reg = new RegExp("(^| )" + keys + "=([^;]*)(;|\x24)");
		var result = reg.exec(document.cookie);
		if (result) {
			return result[2] || '';
		}
		return '';
	}
};

function getLocation(callback) {
	
	callback = typeof(callback) == 'function' ? callback : function(res) {};
		var num=1;
		var that = this;
		// #ifdef H5
		
		var lng = '117.211954';
		var lat = '31.839676';
		that.__CFG.lng = lng;
		that.__CFG.lat = lat;
		callback();
		return
		
		uni.getLocation({
			type: 'gcj02',
			geocode: true,
			success: function(res) {
				// console.log(res)
				// var lng=res.longitude;
				// var lat=res.latitude;
				// that.user.lng=res.longitude;
				// that.user.lat=res.latitude;
				var lng = '117.211954';
				var lat = '31.839676';
				that.__CFG.lng = lng;
				that.__CFG.lat = lng;
				callback();
				//  console.log('当前位置的经度：' + res.longitude);
				// console.log('当前位置的纬度：' + res.latitude);
			},
			fail: function(red) {
				console.log(red,88)
			},
		})
		// #endif
		// #ifdef MP-WEIXIN
		uni.getSetting({
			success(res) {
				if(res.authSetting['scope.userLocation'] != undefined){
					if (res.authSetting['scope.userLocation']) {
						getLocationaddr(callback)
						// 已经授权，可以直接调用 getLocation 获取地理位置
					} else {
						showConfirm('您还未开启定位，是否去开启定位？').then(cres => {
						  if (cres.confirm) {
						    uni.openSetting({
						    	success(res2) {
						    		if (res2.authSetting['scope.userLocation']) {
						    			
						    		}
						    	}
						    });
							callback(-1)
						  }
						})
					};
				}else{
					var uxlocation = {"lng": "", "lat": "", "address": ""};
					// var citynum=1;
					uni.getLocation({
						type: 'gcj02',
						geocode: 'true',
						success: function(ares) {
							uxlocation.lat = ares.latitude;
							uxlocation.lng = res.longitude;
							// myAmapFun.getRegeo({
							// 	success: function(data) {
							// 		// citynum=0;
							// 		uxlocation.address = data[0].name+data[0].desc||data[0].regeocodeData.formatted_address;
							// 		uxlocation.city = data[0].regeocodeData.addressComponent.city;
							// 		setUxLocation(uxlocation);
							// 		callback(uxlocation);
							// 		//成功回调
							// 	},
							// 	fail: function(info) {
							// 		//失败回调
							// 	}
							// })
							// 获取天气
							myAmapFun.getWeather({
								success(res){
									//temperature  温度
									//weather 天气现象
									uxlocation.city = res.city.data;
									uxlocation.temperature = res.temperature.data;
									uxlocation.weather = res.weather.data;
									var weather=res.weather.data;
									var weatherMap=__CFG.iconWeatherMap;
									var url=require('@/static/images/weather/weaionf.png');
									Object.keys(weatherMap).some((key) => {
										if (weatherMap[key].children.indexOf(weather)!=-1) {
											url=require(`@/static/images/weather/${weatherMap[key].val}.png`)
											return true;
										}
									}) 
									uxlocation.icon = url;
									setUxLocation(uxlocation);
									callback(uxlocation);
								},
								fail(err){
									console.log('fail')
								}
							})
							// if(citynum==1){
							// 	setUxLocation(uxlocation);
							// 	callback(uxlocation);
							// }
						},
						
						fail: function(error) {
							uni.showToast({
								icon: 'none',
								title: '定位失败'
							})
					
							// #ifdef APP-PLUS
							// #endif
					
						},
						complete: function(rs) {
							// console.log('complete:'+JSON.stringify(rs))
						}
					})
				}
			},
			fail(err) {
				console.log(err)
			},
		})
		// #endif
		// #ifdef APP-PLUS
		let system = uni.getSystemInfoSync();
			if(system.platform === "android"){
				var context = plus.android.importClass("android.content.Context");
				var locationManger = plus.android.importClass("android.location.LocationManager");
				var main = plus.android.runtimeMainActivity();
				var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
				if(!mainSvr.isProviderEnabled(locationManger.GPS_PROVIDER)){
					uni.showModal({
						title:"提示",
						content:"请授权位置获取地址",
						showCancel:false,
							success() {
								if(!mainSvr.isProviderEnabled(locationManger.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);
								}else{
									console.log("定位已开启")
									_self.setSite()
								}
							}
						})
				}else{
					plus.android.requestPermissions(
						['android.permission.ACCESS_FINE_LOCATION'], // 理论上支持多个权限同时查询，但实际上本函数封装只处理了一个权限的情况。有需要的可自行扩展封装
						function(resultObj) {
							var result = 0;
							for (var i = 0; i < resultObj.granted.length; i++) {
								var grantedPermission = resultObj.granted[i];
								console.log('已获取的权限：' + grantedPermission);
								result = 1
							}
							for (var i = 0; i < resultObj.deniedPresent.length; i++) {
								var deniedPresentPermission = resultObj.deniedPresent[i];
								console.log('拒绝本次申请的权限：' + deniedPresentPermission);
								result = 0
							}
							for (var i = 0; i < resultObj.deniedAlways.length; i++) {
								var deniedAlwaysPermission = resultObj.deniedAlways[i];
								console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
								result = -1
							}
							// resolve(result);
							// 若所需权限被拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限
							if (result != 1) {
								showConfirm('您还未开启定位，是否去开启定位？').then(res => {
								  if (res.confirm) {
								    gotoAppPermissionSetting()
									callback(result)
								  }
								})
							}else{
								getLocationaddr(callback)
							}
						},
						function(error) {
							console.log('申请权限错误：' + error.code + " = " + error.message);
							// resolve({
							// 	code: error.code,
							// 	message: error.message
							// });
						}
					);
				}
			}
			
		// #endif
};
// 跳转到**应用**的权限页面
function gotoAppPermissionSetting() {
	var isIos
	// #ifdef APP-PLUS
	isIos = (plus.os.name == "iOS")
	// #endif
	if (isIos) {
		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-settings:");
		application2.openURL(setting2);

		plus.ios.deleteObject(setting2);
		plus.ios.deleteObject(NSURL2);
		plus.ios.deleteObject(application2);
	} else {
		var Intent = plus.android.importClass("android.content.Intent");
		var Settings = plus.android.importClass("android.provider.Settings");
		var Uri = plus.android.importClass("android.net.Uri");
		var mainActivity = plus.android.runtimeMainActivity();
		var intent = new Intent();
		intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
		var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
		intent.setData(uri);
		mainActivity.startActivity(intent);
	}
}
function getLocationaddr(callback){
	callback = typeof(callback) == 'function' ? callback : function(res) {};
	var uxlocation = {"lng": "", "lat": "", "address": ""};
	uni.getLocation({
		type: 'gcj02',
		geocode: 'true',
		success: function(res) {
			uxlocation.lat = res.latitude;
			uxlocation.lng = res.longitude;
			// myAmapFun.getRegeo({
			// 	success: function(data) {
			// 		uxlocation.address = data[0].name+data[0].desc||data[0].regeocodeData.formatted_address;
			// 		uxlocation.city = data[0].regeocodeData.addressComponent.city;
			// 		setUxLocation(uxlocation);
			// 		callback(uxlocation);
			// 	},
			// 	fail: function(info) {
			// 		//失败回调
			// 		console.log(info,223)
			// 	}
			// })
			// 获取天气
			myAmapFun.getWeather({
				success(res){
					//temperature  温度
					//weather 天气现象
					uxlocation.city = res.city.data;
					uxlocation.temperature = res.temperature.data;
					uxlocation.weather = res.weather.data;
					var weather=res.weather.data;
					var weatherMap=__CFG.iconWeatherMap;
					var url=require('@/static/images/weather/weaionf.png');
					Object.keys(weatherMap).some((key) => {
						if (weatherMap[key].children.indexOf(weather)!=-1) {
							url=require(`@/static/images/weather/${weatherMap[key].val}.png`)
							return true;
						}
					}) 
					uxlocation.icon = url;
					setUxLocation(uxlocation);
					callback(uxlocation);
				},
				fail(err){
					console.log('fail')
				}
			})
		},
		
		fail: function(error) {
			uni.showToast({
				icon: 'none',
				title: '定位失败'
			})
	
			// #ifdef APP-PLUS
			// #endif
	
		},
		complete: function(rs) {
			// console.log('complete:'+JSON.stringify(rs))
		}
	})
}

const self = {
	getLocation,
	setUxLocation,
	__CFG
}
export default self
