import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

class Permissions {
  // 请求视频访问权限
  static Future<bool> requestVideoPermission() async {
    if (Platform.isAndroid) {
      final deviceInfoPlugin = DeviceInfoPlugin();
      final androidInfo = await deviceInfoPlugin.androidInfo;
      final sdkInt = androidInfo.version.sdkInt;

      if (sdkInt >= 33) {
        final status = await Permission.videos.request();
        return status.isGranted;
      } else {
        final status = await Permission.storage.request();
        return status.isGranted;
      }
    } else if (Platform.isIOS) {
      final status = await Permission.photos.request();
      return status.isGranted;
    }
    return false;
  }

  // 请求相机权限
  static Future<bool> requestCameraPermission() async {
    return await _checkAndRequest(Permission.camera);
  }

  // 请求麦克风权限
  static Future<bool> requestMicrophonePermission() async {
    return await _checkAndRequest(Permission.microphone);
  }

  // 请求麦克风权限
  static Future<bool> requestPhotoPermission() async {
    return await _checkAndRequest(Permission.microphone);
  }

  // 封装公共权限处理逻辑
  static Future<bool> _checkAndRequest(Permission permission) async {
    final status = await permission.status;

    if (status.isGranted) return true;

    final result = await permission.request();

    if (result.isGranted) return true;

    if (result.isPermanentlyDenied) {
      _showPermissionDialog();
    } else {
      Get.snackbar('权限请求失败', '无法访问，请授权对应权限后重试');
    }

    return false;
  }

  // 跳转设置的提示弹窗
  static void _showPermissionDialog() {
    Get.defaultDialog(
      title: '需要权限',
      middleText: '请前往系统设置中手动开启权限',
      textCancel: '取消',
      textConfirm: '去设置',
      onConfirm: () async {
        Get.back();
        await openAppSettings();
      },
    );
  }
}
