/**
 * 本模块封装了Android、iOS的应用权限判断、打开应用权限设置界面、以及位置系统服务是否开启
 *  https://ext.dcloud.net.cn/plugin?id=594
 */

var isIos
// #ifdef APP-PLUS
isIos = (plus.os.name == "iOS")
// #endif

// 判断推送权限是否开启
function judgeIosPermissionPush() {
	var result = false;
	var UIApplication = plus.ios.import("UIApplication");
	var app = UIApplication.sharedApplication();
	var enabledTypes = 0;
	if (app.currentUserNotificationSettings) {
		var settings = app.currentUserNotificationSettings();
		enabledTypes = settings.plusGetAttribute("types");
		console.log("enabledTypes1:" + enabledTypes);
		if (enabledTypes == 0) {
			console.log("推送权限没有开启");
		} else {
			result = true;
			console.log("已经开启推送功能!")
		}
		plus.ios.deleteObject(settings);
	} else {
		enabledTypes = app.enabledRemoteNotificationTypes();
		if (enabledTypes == 0) {
			console.log("推送权限没有开启!");
		} else {
			result = true;
			console.log("已经开启推送功能!")
		}
		console.log("enabledTypes2:" + enabledTypes);
	}
	plus.ios.deleteObject(app);
	plus.ios.deleteObject(UIApplication);
	return result;
}

// 判断定位权限是否开启
function judgeIosPermissionLocation() {
	var result = false;
	var cllocationManger = plus.ios.import("CLLocationManager");
	var status = cllocationManger.authorizationStatus();
	result = (status != 2)
	console.log("定位权限开启：" + result);
	// 以下代码判断了手机设备的定位是否关闭，推荐另行使用方法 checkSystemEnableLocation
	/* var enable = cllocationManger.locationServicesEnabled();
	var status = cllocationManger.authorizationStatus();
	console.log("enable:" + enable);
	console.log("status:" + status);
	if (enable && status != 2) {
		result = true;
		console.log("手机定位服务已开启且已授予定位权限");
	} else {
		console.log("手机系统的定位没有打开或未给予定位权限");
	} */
	plus.ios.deleteObject(cllocationManger);
	return result;
}

// 判断麦克风权限是否开启
function judgeIosPermissionRecord() {
	var result = false;
	var avaudiosession = plus.ios.import("AVAudioSession");
	var avaudio = avaudiosession.sharedInstance();
	var permissionStatus = avaudio.recordPermission();
	console.log("permissionStatus:" + permissionStatus);
	if (permissionStatus == 1684369017 || permissionStatus == 1970168948) {
		console.log("麦克风权限没有开启");
	} else {
		result = true;
		console.log("麦克风权限已经开启");
	}
	plus.ios.deleteObject(avaudiosession);
	return result;
}

// 判断相机权限是否开启
function judgeIosPermissionCamera() {
	var result = false;
	var AVCaptureDevice = plus.ios.import("AVCaptureDevice");
	var authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide');
	console.log("authStatus:" + authStatus);
	if (authStatus == 3) {
		result = true;
		console.log("相机权限已经开启");
	} else {
		console.log("相机权限没有开启");
	}
	plus.ios.deleteObject(AVCaptureDevice);
	return result;
}

// 判断相册权限是否开启
function judgeIosPermissionPhotoLibrary() {
	var result = false;
	var PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
	var authStatus = PHPhotoLibrary.authorizationStatus();
	console.log("authStatus:" + authStatus);
	if (authStatus == 3) {
		result = true;
		console.log("相册权限已经开启");
	} else {
		console.log("相册权限没有开启");
	}
	plus.ios.deleteObject(PHPhotoLibrary);
	return result;
}

// 判断通讯录权限是否开启
function judgeIosPermissionContact() {
	var result = false;
	var CNContactStore = plus.ios.import("CNContactStore");
	var cnAuthStatus = CNContactStore.authorizationStatusForEntityType(0);
	if (cnAuthStatus == 3) {
		result = true;
		console.log("通讯录权限已经开启");
	} else {
		console.log("通讯录权限没有开启");
	}
	plus.ios.deleteObject(CNContactStore);
	return result;
}

// 判断日历权限是否开启
function judgeIosPermissionCalendar() {
	var result = false;
	var EKEventStore = plus.ios.import("EKEventStore");
	var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(0);
	if (ekAuthStatus == 3) {
		result = true;
		console.log("日历权限已经开启");
	} else {
		console.log("日历权限没有开启");
	}
	plus.ios.deleteObject(EKEventStore);
	return result;
}

// 判断备忘录权限是否开启
function judgeIosPermissionMemo() {
	var result = false;
	var EKEventStore = plus.ios.import("EKEventStore");
	var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(1);
	if (ekAuthStatus == 3) {
		result = true;
		console.log("备忘录权限已经开启");
	} else {
		console.log("备忘录权限没有开启");
	}
	plus.ios.deleteObject(EKEventStore);
	return result;
}

// Android权限查询
function requestAndroidPermission(permissionID) {
	return new Promise((resolve, reject) => {
		plus.android.requestPermissions(
			[permissionID], // 理论上支持多个权限同时查询，但实际上本函数封装只处理了一个权限的情况。有需要的可自行扩展封装
			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) {
				// gotoAppPermissionSetting()
				// }
			},
			function(error) {
				console.log('申请权限错误：' + error.code + " = " + error.message);
				resolve({
					code: error.code,
					message: error.message
				});
			}
		);
	});
}

// 使用一个方法，根据参数判断权限
function judgeIosPermission(permissionID) {
	if (permissionID == "location") {
		return judgeIosPermissionLocation()
	} else if (permissionID == "camera") {
		return judgeIosPermissionCamera()
	} else if (permissionID == "photoLibrary") {
		return judgeIosPermissionPhotoLibrary()
	} else if (permissionID == "record") {
		return judgeIosPermissionRecord()
	} else if (permissionID == "push") {
		return judgeIosPermissionPush()
	} else if (permissionID == "contact") {
		return judgeIosPermissionContact()
	} else if (permissionID == "calendar") {
		return judgeIosPermissionCalendar()
	} else if (permissionID == "memo") {
		return judgeIosPermissionMemo()
	}
	return false;
}

// 跳转到**应用**的权限页面
function gotoAppPermissionSetting() {
	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 {
		// console.log(plus.device.vendor);
		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);
	}
}

// 检查系统的设备服务是否开启
// var checkSystemEnableLocation = async function () {
function checkSystemEnableLocation() {
	if (isIos) {
		var result = false;
		var cllocationManger = plus.ios.import("CLLocationManager");
		var result = cllocationManger.locationServicesEnabled();
		console.log("系统定位开启:" + result);
		plus.ios.deleteObject(cllocationManger);
		return result;
	} else {
		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);
		var result = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);
		console.log("系统定位开启:" + result);
		return result
	}
}
//获取ios手机权限
// 判断位置权限是否始终开启
function judgeIosPermissionLocationAlways() {
    var result = false;
    var cllocationManger = plus.ios.import("CLLocationManager");
    var status = cllocationManger.authorizationStatus();
    var enable = cllocationManger.locationServicesEnabled();
    if (status == 3 && enable) {
        result = true;
        console.log("位置权限始终开启");
    } else {
        console.log("位置权限不是始终开启");
    }
    plus.ios.deleteObject(cllocationManger);
    return result;
}

// 判断是否开启精准位置权限
function judgeIosPermissionLocationAccuracy() {
    var result = false;
    var cllocationManger = plus.ios.import("CLLocationManager");
    var status = cllocationManger.authorizationStatus();
    if (status == 3 || status == 4) {
        result = true;
        console.log("精准位置权限已开启");
    } else {
        console.log("精准位置权限未开启");
    }
    plus.ios.deleteObject(cllocationManger);
    return result;
}

//获取安卓手机权限
function requestAndroidPermissions(type) {
	let permissionArr=[]
	if(type=='ios'){
		// const awalysLocation=judgeIosPermissionLocationAlways()
		// const preciseLocation=judgeIosPermissionLocationAccuracy()
		const awalysLocation=true
		const preciseLocation=true
		permissionArr=[
			{type: 'awalysLocation',state:awalysLocation,title: ('使用App期间'), desc: '允许访问位置信息'},
			{type: 'preciseLocation',state:preciseLocation,title: ('精准位置'),  desc: '开启精准位置开关'},
		]
	}else if(type=='android'){
		const locationPermission=checkLocationPermission()
		const optimizationStatus=checkBatteryOptimizationStatus()
		permissionArr=[
			{type: 'location',state:locationPermission,title: ('位置权限'), desc: '打开手机定位，并运行APP始终使用'},
			{type: 'battery',state:optimizationStatus,title: ('电池优化'),  desc: '打开电池优化设置， 将弗兰克APP加入保护名单'},
		]
	}
	return permissionArr
}


function checkLocationPermission() {
    var main = plus.android.runtimeMainActivity();
    var PackageManager = plus.android.importClass("android.content.pm.PackageManager");
    
    // 定义定位权限常量
    var FINE_PERMISSION = "android.permission.ACCESS_FINE_LOCATION";
    var COARSE_PERMISSION = "android.permission.ACCESS_COARSE_LOCATION";
    
    // 检查精确和粗略定位权限状态
    var hasFineLocation = main.checkSelfPermission(FINE_PERMISSION) === PackageManager.PERMISSION_GRANTED;
    var hasCoarseLocation = main.checkSelfPermission(COARSE_PERMISSION) === PackageManager.PERMISSION_GRANTED;
    
    if (hasFineLocation || hasCoarseLocation) {
        console.log("✅ 定位权限已授予");
        return true;
    } else {
        console.log("⚠️ 定位权限未授予");
        return false;
    }
}

function checkBatteryOptimizationStatus() {
    var main = plus.android.runtimeMainActivity();
    var Context = plus.android.importClass("android.content.Context");
    var PowerManager = plus.android.importClass("android.os.PowerManager");
    
    var powerManager = main.getSystemService(Context.POWER_SERVICE);
    var packageName = main.getPackageName();
    
    var isIgnoringBatteryOptimizations = powerManager.isIgnoringBatteryOptimizations(packageName);
    
    if (isIgnoringBatteryOptimizations) {
        console.log("✅ 应用已被白名单豁免，未受电池优化限制");
        return true;
    } else {
        console.log("⚠️ 应用受电池优化限制");
        return false;
    }
}

function openBatteryOptimization() {
    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 main = plus.android.runtimeMainActivity();
    var intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
    var uri = Uri.parse("package:" + main.getPackageName());
    intent.setData(uri);
    main.startActivity(intent);
}


function checkBackgroundRunningPermission() {
    var main = plus.android.runtimeMainActivity();
    var Context = plus.android.importClass("android.content.Context");
    var ActivityManager = plus.android.importClass("android.app.ActivityManager");

    var activityManager = main.getSystemService(Context.ACTIVITY_SERVICE);
    var runningAppProcesses = activityManager.getRunningAppProcesses();
    console.log(runningAppProcesses,'runningAppProcesses');
    var packageName = main.getPackageName();
    
	if('size' in runningAppProcesses){
		for (var i = 0; i < runningAppProcesses.size(); i++) {
		    var processInfo = runningAppProcesses.get(i);
		    if (processInfo.processName === packageName) {
		        console.log("✅ 应用正在后台运行");
		        return true;
		    }
		}
	}else{
		console.log("⚠️ 应用可能未开启后台运行权限");
		return false;	
	}
   
}


function checkAppLockStatus() {
    var main = plus.android.runtimeMainActivity();
    var Context = plus.android.importClass("android.content.Context");
    var AppOpsManager = plus.android.importClass("android.app.AppOpsManager");

    var appOps = main.getSystemService(Context.APP_OPS_SERVICE);
    var packageName = main.getPackageName();
    var uid = plus.android.importClass("android.os.Process").myUid();
	
    var mode = appOps.checkOpNoThrow("android:get_usage_stats", uid, packageName);
	console.log(AppOpsManager.OPSTR_GET_USAGE_STATS ,mode,AppOpsManager.MODE_ALLOWED);
    if (mode === AppOpsManager.MODE_ALLOWED) {
        console.log("✅ 应用未被应用锁限制");
        return true;
    } else {
        console.log("⚠️ 应用可能被应用锁限制");
        return false;
    }
}
function openAppLockSettings() {
    const brand = uni.getSystemInfoSync().brand.toLowerCase();
    console.log(brand);
    if (brand.includes("xiaomi")) {
        plus.runtime.openURL("miui://securitycenter",(res)=>{
			console.log(res,'test');
		}); // 小米 - 安全中心
    } else if (brand.includes("huawei")) {
        plus.runtime.openURL("huawei://settings/security/ApplicationLock"); // 华为 - 应用锁
    } else if (brand.includes("oppo")) {
        plus.runtime.openURL("oppo://securecenter/appLock"); // OPPO
    } else if (brand.includes("vivo")) {
        plus.runtime.openURL("vivosec://AppLock"); // VIVO
    } else {
        openGeneralSettings(); // 其他品牌通用方法
    }
}
function openGeneralSettings() {
    var Intent = plus.android.importClass("android.content.Intent");
    var Settings = plus.android.importClass("android.provider.Settings");

    var main = plus.android.runtimeMainActivity();
    var intent = new Intent(Settings.ACTION_SECURITY_SETTINGS); // 安全设置
    main.startActivity(intent);
}

function getBondedDevices() {
  // #ifdef APP-PLUS

	// 检查蓝牙是否可用
	const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter');
	const bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	
	if (!bluetoothAdapter) {
	  uni.showToast({ title: '设备不支持蓝牙', icon: 'none' });
	  return false;
	}
	
	if (!bluetoothAdapter.isEnabled()) {
	  uni.showToast({ title: '请先启用蓝牙', icon: 'none' });
	  return false;
	}
	
	// 获取已配对设备
	const bondedDevices = plus.android.invoke(bluetoothAdapter, 'getBondedDevices');
	const deviceArray = plus.android.invoke(bondedDevices, 'toArray');
	let isPaired = false
	// deviceArray.map(device => ({
	//   name: plus.android.invoke(device, 'getName') || '未知设备',
	//   address: plus.android.invoke(device, 'getAddress'),
	//   type: getDeviceType(plus.android.invoke(device, 'getBluetoothClass'))
	// }));
	const app = getApp();
	const car_sn=  uni.getStorageSync('car_info').car_sn
	const deviceId =app.globalData.connectionState[car_sn].deviceId
	if(!deviceId) return false
	//配对配对蓝牙设备是否在蓝牙列表里面
	deviceArray.map(device => {
		if(plus.android.invoke(device, 'getAddress')==deviceId){
			isPaired=true
		}
	});
	return isPaired

  // #endif
}

function getDeviceType(bluetoothClass) {
  if (!bluetoothClass) return '未知';
  const deviceClass = plus.android.invoke(bluetoothClass, 'getDeviceClass');
  // 这里可以添加更多设备类型判断
  return deviceClass;
}

//设备蓝牙权限是否开启
function checkBluetoothPermission() {
    // #ifdef APP-PLUS
	if (isIos) {
        // iOS 平台蓝牙权限检查
        // iOS 平台没有独立的蓝牙权限，但需要检查定位权限是否开启
        // 因为在 iOS 上，蓝牙扫描需要定位权限
        return judgeIosPermissionLocation();
    } else {
        // 安卓平台蓝牙权限检查
        // #ifdef APP-PLUS
        // 检查蓝牙是否可用
        const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter');
        const bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (!bluetoothAdapter) {
            console.log('设备不支持蓝牙');
            return false;
        }

        // 检查蓝牙是否已启用
        if (!bluetoothAdapter.isEnabled()) {
            console.log('蓝牙未启用');
            return false;
        }

        console.log('蓝牙已启用');
        return true;
        // #endif
    }
    // #endif
}

module.exports = {
	judgeIosPermission: judgeIosPermission,
	requestAndroidPermission: requestAndroidPermission,
	checkSystemEnableLocation: checkSystemEnableLocation,
	gotoAppPermissionSetting: gotoAppPermissionSetting,
	checkBatteryOptimizationStatus,
	checkAppLockStatus,
	openBatteryOptimization,
	checkBackgroundRunningPermission,
	requestAndroidPermissions,
	openAppLockSettings,//前往打开应用锁
	judgeIosPermissionLocationAlways,
	judgeIosPermissionLocationAccuracy,
	getBondedDevices,
	checkBluetoothPermission

}
