import 'dart:ui';
import 'package:permission_handler/permission_handler.dart';

/// 封装通用权限处理方法
/// - [permissions] 需要检查的权限列表
/// - [onGranted] 当所有权限都被授予时调用的回调
/// - [onDenied] 当有权限被拒绝时调用的回调
/// - [onPermanentlyDenied] 当有权限被永久拒绝时调用的回调（可选，默认打开设置页）
Future<void> checkPermission({
  required List<Permission> permissions,
  required VoidCallback onGranted,
  VoidCallback? onDenied,
  VoidCallback? onPermanentlyDenied,
}) async {
  // 判断当前权限状态
  Map<Permission, PermissionStatus> statuses = {};
  for (final permission in permissions) {
    statuses[permission] = await permission.status;
  }

  // 筛选出未授权的权限
  final needRequest = statuses.entries
      .where((entry) => !entry.value.isGranted)
      .map((entry) => entry.key)
      .toList();
  // 如果全部已有权限
  if (needRequest.isEmpty) {
    onGranted();
    return;
  }

  // 请求未授权的权限
  final requestResult = await needRequest.request();

  //是否全部授权
  bool allGranted = true;
  //是否有任何一个授权了
  bool anyPermanentlyDenied = false;

  for (final permission in permissions) {
    final status = requestResult[permission] ?? await permission.status;

    if (status.isPermanentlyDenied) {
      anyPermanentlyDenied = true;
      allGranted = false;
      break;
    } else if (!status.isGranted) {
      allGranted = false;
    }
  }

  if (allGranted) {
    onGranted();
  } else if (anyPermanentlyDenied) {
    if (onPermanentlyDenied != null) {
      onPermanentlyDenied();
    } else {
      openAppSettings(); // 可选：默认打开设置页
    }
  } else {
    if (onDenied != null) {
      onDenied();
    }
  }
}
