import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wallpaperx/common/components/dialog/remind_dialog.dart';

class PermissionUtil {
  /// 检测是否有权限
  /// [permissionList] 权限申请列表
  static Future<bool> checkPermission(List<Permission> permissionList) async {
    // 一个新待申请权限列表
    List<Permission> newPermissionList = [];
    // 遍历当前权限申请列表
    for (Permission permission in permissionList) {
      PermissionStatus status = await permission.status;
      // 如果不是允许状态就添加到新的申请列表中
      if (!status.isGranted) {
        newPermissionList.add(permission);
      }
    }

    // 如果需要重新申请的列表不是空的
    if (newPermissionList.isNotEmpty) {
      PermissionStatus permissionStatus = await _requestPermission(newPermissionList);
      switch (permissionStatus) {
        // 拒绝状态
        case PermissionStatus.denied:
            showFailedDialog(newPermissionList);
          return false;
        // 允许状态
        case PermissionStatus.granted:
        case PermissionStatus.limited:
        case PermissionStatus.provisional:
          return true;
        // 永久拒绝 活动限制
        case PermissionStatus.restricted:
        case PermissionStatus.permanentlyDenied:
            showFailedDialog(newPermissionList, isPermanentlyDenied: true);
          break;
      }
    } else {
      return true;
    }
    return false;
  }

  /// 获取新列表中的权限 如果有一项不合格就返回false
  static Future<PermissionStatus> _requestPermission(List<Permission> permissionList) async {
    Map<Permission, PermissionStatus> statuses = await permissionList.request();
    PermissionStatus currentPermissionStatus = PermissionStatus.granted;
    statuses.forEach((key, value) {
      if (!value.isGranted || !value.isLimited) {
        currentPermissionStatus = value;
        return;
      }
    });
    return currentPermissionStatus;
  }

  static Future<bool> checkLocationAlways() async {
    // 获取前置状态
    // Android没有这一步 ios会先访问这个再访问其他的
    PermissionStatus status = PermissionStatus.granted;
    status = await _checkSinglePermission(Permission.locationWhenInUse);

    // 获取第二个状态
    PermissionStatus status2 = PermissionStatus.denied;

    // 如果前置状态为成功才能执行获取第二个状态
    if (status.isGranted) {
      status2 = await _checkSinglePermission(Permission.locationAlways);
    }

    // 如果两个都成功那么就返回成功
    if (status.isGranted && status2.isGranted) {
      return true;

      // 如果有一个拒绝那么就失败了
    } else if (status.isDenied || status2.isDenied) {
      showFailedDialog(
          [Permission.locationWhenInUse, Permission.locationAlways]);
    } else {
      showFailedDialog(
        [Permission.locationWhenInUse, Permission.locationAlways],
        isPermanentlyDenied: true,
      );
    }
    return false;
  }

  static _checkSinglePermission(Permission permission) async {
    // 获取当前状态
    PermissionStatus status = await permission.status;
    PermissionStatus currentPermissionStatus = PermissionStatus.granted;

    // 如果它状态不是允许那么就去获取
    if (!status.isGranted) {
      currentPermissionStatus = await _requestPermission([permission]);
    }

    // 返回最终状态
    return currentPermissionStatus;
  }

  /// 权限拒绝后弹窗
  static showFailedDialog(List<Permission> permissionList, {bool isPermanentlyDenied = false}) async {
    Get.dialog(
      barrierDismissible: false,
      RemindDialog(
        content: await _getInstructions(permissionList),
        confirmText: isPermanentlyDenied ? 'Go Settings' : 'Confirm',
        confirmOnTap: () {
          if (isPermanentlyDenied) {
            openAppSettings();
          } else {
            checkPermission(permissionList);
          }
        },
      ),
    );
  }

  /// 获取权限使用说明
  static Future<String> _getInstructions(List<Permission> permissionList) async {
    late Permission failedPermission;

    // 遍历当前权限申请列表
    for (Permission permission in permissionList) {
      PermissionStatus status = await permission.status;

      // 如果不是允许状态就添加到新的申请列表中
      if (!status.isGranted || !status.isLimited) {
        failedPermission = permission;
        break;
      }
    }
    String explain = '';
    if (failedPermission == Permission.storage || failedPermission == Permission.photosAddOnly) {
      explain = 'We need access to your photo album so you can save wallpapers from the app to your album';
    }
    return explain;
  }
}
