import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:shared/utils/device_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/dialog/app_default_dialog.dart';
import 'package:widgets/dialog/permission_desc_dialog.dart';

import '../dialog/dialog_engine.dart';

/*
 * 动态权限的申请与校验
 */
class PermissionEngine {
  // 私有构造函数
  PermissionEngine._privateConstructor();

  // 单例实例
  static final PermissionEngine _instance = PermissionEngine._privateConstructor();

  // 获取单例实例的访问点
  factory PermissionEngine() {
    return _instance;
  }

  /// 申请多媒体相册权限
  void requestPhotosPermission(void Function() success) async {
    //相册的选项
    if (DeviceUtils.isIOS) {
      //申请授权
      final value = await PhotoManager.requestPermissionExtend();
      if (value.hasAccess) {
        //已授权
        Log.d("相册已授权");
        success();
      } else if (value == PermissionState.limited) {
        Log.d("相册访问受限，去设置受限");
        PhotoManager.presentLimited();
      } else {
        Log.d("相册无授权，去设置");
        DialogEngine.show(
          widget: AppDefaultDialog(
            title: "Alert",
            message: 'No album permission, go to settings?',
            confirmAction: () {
              PhotoManager.openSetting();
            },
          ),
        );
      }
    } else {
      //Android是否有SD卡权限
      var status = await Permission.storage.status;
      late PermissionState ps;
      if (status.isGranted) {
        // 已经授权
        success();
      } else {
        // 未授权，则准备发起一次申请
        var permissionRequestFuture = PhotoManager.requestPermissionExtend();

        // 延迟500毫秒的Future
        var delayFuture = Future.delayed(const Duration(milliseconds: 500), () => 'delay');

        // 使用Future.any等待上述两个Future中的任何一个完成
        var firstCompleted = await Future.any([permissionRequestFuture, delayFuture]);

        // 判断响应结果
        if (firstCompleted == 'delay') {
          Log.d("判断响应结果:1");
          // 如果是延迟Future完成了，表示500毫秒内没有获得权限响应，显示对话框
          _showPermissionDialog("“YY Employer” would like to access your multimedia album for functions such as image uploading and saving. Please allow me to obtain your permission");
          // 再次等待权限请求结果
          ps = await permissionRequestFuture;
          DialogEngine.dismiss(tag: "permission");
        } else {
          Log.d("判断响应结果:2");
          // 权限请求已完成，立刻取消对话框展示（如果已经展示的话）
          DialogEngine.dismiss(tag: "permission");
          ps = firstCompleted as PermissionState;
        }

        if (ps.isAuth) {
          // 用户授权
          success();
        } else {
          // 权限被拒绝
          await DialogEngine.show(
            widget: AppDefaultDialog(
                message: "Please set the permission to open the photo album on your phone",
                title: "Alert",
                confirmAction: () {
                  openAppSettings();
                }),
          );
        }
      }
    }
  }

  /// 申请相机权限
  void requestCameraPermission(void Function() success) async {
    // 获取当前的权限
    var status = await Permission.camera.status;
    if (status.isGranted) {
      // 已经授权
      success();
    } else {
      // 未授权，则准备发起一次申请
      var permissionRequestFuture = Permission.camera.request();

      // 延迟500毫秒的Future
      var delayFuture = Future.delayed(const Duration(milliseconds: 500), () => 'delay');

      // 使用Future.any等待上述两个Future中的任何一个完成
      var firstCompleted = await Future.any([permissionRequestFuture, delayFuture]);

      // 判断响应结果
      if (firstCompleted == 'delay') {
        // 如果是延迟Future完成了，表示500毫秒内没有获得权限响应，显示对话框
        _showPermissionDialog("“YY Employer” requests to use your camera permission for functions such as taking avatars, uploading and saving images. Please allow me to obtain your permission");
        // 再次等待权限请求结果
        status = await permissionRequestFuture;
        DialogEngine.dismiss(tag: "permission");
      } else {
        // 权限请求已完成，立刻取消对话框展示（如果已经展示的话）
        DialogEngine.dismiss(tag: "permission");
        status = firstCompleted as PermissionStatus;
      }

      if (status.isGranted) {
        // 用户授权
        success();
      } else {
        // 权限被拒绝
        await DialogEngine.show(
          widget: AppDefaultDialog(
              message: "Please set the permission to open the camera on your phone",
              title: "Alert",
              confirmAction: () {
                openAppSettings();
              }),
        );
      }
    }
  }

  /// 校验并申请定位权限
  Future<bool> requestLocationPermission() async {
    // 获取当前的权限
    var status = await Permission.location.status;
    if (status.isGranted) {
      // 已经授权
      return true;
    } else {
      // 未授权，则准备发起一次申请
      var permissionRequestFuture = Permission.location.request();

      // 延迟500毫秒的Future
      var delayFuture = Future.delayed(const Duration(milliseconds: 500), () => 'delay');

      // 使用Future.any等待上述两个Future中的任何一个完成
      var firstCompleted = await Future.any([permissionRequestFuture, delayFuture]);

      // 判断响应结果
      if (firstCompleted == 'delay') {
        // 如果是延迟Future完成了，表示500毫秒内没有获得权限响应，显示对话框
        _showPermissionDialog("“YY Employer” want to access your location permission to obtain your location and recommend nearby information");
        // 再次等待权限请求结果
        status = await permissionRequestFuture;
        DialogEngine.dismiss(tag: "permission");
      } else {
        Log.d("权限请求已完成,立刻取消对话框展示");
        // 权限请求已完成，立刻取消对话框展示（如果已经展示的话）
        DialogEngine.dismiss(tag: "permission");
        status = firstCompleted as PermissionStatus;
      }

      if (status.isGranted) {
        // 用户授权
        return true;
      } else {
        // 权限被拒绝
        await DialogEngine.show(
          widget: AppDefaultDialog(
              message: "Please go to your phone settings to enable location permission",
              title: "Alert",
              confirmAction: () {
                openAppSettings();
              }),
        );
        return false;
      }
    }
  }

  /// 申请拨打电话权限
  void requestCallPhonePermission(void Function() success) async {
    // 获取当前的权限
    var status = await Permission.phone.status;
    if (status.isGranted) {
      // 已经授权
      success();
    } else {
      // 未授权，则准备发起一次申请
      var permissionRequestFuture = Permission.phone.request();

      // 延迟500毫秒的Future
      var delayFuture = Future.delayed(const Duration(milliseconds: 500), () => 'delay');

      // 使用Future.any等待上述两个Future中的任何一个完成
      var firstCompleted = await Future.any([permissionRequestFuture, delayFuture]);

      // 判断响应结果
      if (firstCompleted == 'delay') {
        // 如果是延迟Future完成了，表示500毫秒内没有获得权限响应，显示对话框
        _showPermissionDialog("“YY Employer”requires permission to make phone calls for communication. Please allow access to this permission");
        // 再次等待权限请求结果
        status = await permissionRequestFuture;
        DialogEngine.dismiss(tag: "permission");
      } else {
        // 权限请求已完成，立刻取消对话框展示（如果已经展示的话）
        DialogEngine.dismiss(tag: "permission");
        status = firstCompleted as PermissionStatus;
      }

      if (status.isGranted) {
        // 用户授权
        success();
      } else {
        // 权限被拒绝
        await DialogEngine.show(
          widget: AppDefaultDialog(
              message: "Please go to your phone settings to enable phone calls permission",
              title: "Alert",
              confirmAction: () {
                openAppSettings();
              }),
        );
      }
    }
  }

  //顶部展示权限声明详情弹窗
  void _showPermissionDialog(String desc) {
    DialogEngine.show(
      clickMaskDismiss: false,
      backDismiss: true,
      tag: "permission",
      maskColor: Colors.transparent,
      widget: PermissionDescDialog(desc),
    );
  }
}
