var storage = require('../common/storage.js');

function srcFn(url, isLogin) {
	if (isLogin && !storage.getUserToken()) {
		uni.navigateTo({
			url: '/pages/loginRegister/login'
		})
		return
	}
	uni.navigateTo({
		url,
	})
}
async function location() {
	const storedLocation = storage.getUserCurrentLocation()
	try {
		let data = await locationAsync()
		storage.setUserCurrentLocation({
			longitude: data.longitude,
			latitude: data.latitude
		})
		return data
	} catch (error) {
		return storedLocation
	}
}

function htmlData(str){
	return str.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block" ')
}


function locationAsync() {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			success(res) {
				resolve(res)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}

function msg(str) {
	uni.showToast({
		title: str,
		icon: 'none'
	})
}
function checkLocationPermissionH5() {
  return new Promise((resolve) => {
    if (navigator.permissions) {
      navigator.permissions.query({ name: 'geolocation' }).then((result) => {
        resolve(result.state === 'granted'); // granted 表示已授权
      });
    } else {
      // 兼容旧版本浏览器：直接尝试获取位置，通过错误判断
      navigator.geolocation.getCurrentPosition(
        () => resolve(true),
        (error) => resolve(error.code === error.PERMISSION_DENIED ? false : true)
      );
    }
  });
}

function checkLocationPermissionMP() {
  return new Promise((resolve) => {
    uni.getSetting({
      success: (res) => {
        // 微信小程序的权限字段为 'scope.userLocation'
        const hasPermission = res.authSetting['scope.userLocation'] === true;
        resolve(hasPermission);
      },
      fail: () => resolve(false)
    });
  });
}
function checkLocationPermissionApp() {
  return new Promise((resolve) => {
    uni.getSetting({
      success: (res) => {
        // Android/iOS 的权限字段可能不同，需实测确认
        const hasPermission = res.authSetting['scope.userLocation'] === true;
        resolve(hasPermission);
      },
      fail: () => resolve(false)
    });
  });
}

function checkLocationPermission() {
	return new Promise((resolve) => {
		// #ifdef H5
		checkLocationPermissionH5().then(resolve);
		// #endif

		// #ifdef MP-WEIXIN
		checkLocationPermissionMP().then(resolve);
		// #endif

		// #ifdef APP-PLUS
		checkLocationPermissionApp().then(resolve);
		// #endif
	});
}
function paramsObj(url){
	if(url.indexOf("https://zx.uwenya.cc/xcx/s") == -1){
		return {}
	}
	// 1. 提取参数部分
	const queryString = url.split('?')[1] || '';
	
	// 2. 解析为对象
	const params = {};
	queryString.split('&').forEach(pair => {
	  const [key, value] = pair.split('=');
	  if (key) {
	    params[key] = decodeURIComponent(value || '');
	  }
	});
	return params
}
export default {
	install: function(vm) {
		vm.prototype.$paramsObj = paramsObj;
		vm.prototype.$srcFn = srcFn;
		vm.prototype.$msg = msg;
		vm.prototype.$location = location;
		vm.prototype.$checkLocationPermission = checkLocationPermission;
		vm.prototype.$htmlData = htmlData;
	},
};