/*
 * @Author: XianKaiQun
 * @Date: 2020-07-30 18:08:53
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-07-21 11:41:02
 * @Description: 
 */
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wisdom_cli/new/utils/modal.dart';
import 'package:wisdom_cli/new/utils/nav.dart';

///手机权限工具类
class WPermissionUtil {
  WPermissionUtil._();

  ///申请权限，如果选择拒绝，那么会出现去设置的引导框
  static Future<bool> request({
    ///传入Permission.xxxxx
    required Permission service,

    ///引导词
    String deniedText = '无法获取相对应权限,是否前往设置？',
    String? cancelText = '取消',

    ///如果用户拒绝，需不需要引导去App设置中修改
    bool guidance = true,
    String? title = '',
  }) async {
    if ((await service.request()).isGranted) {
      return true;
    } else {
      ///打开设置
      if (guidance) {
        final confirm = await (WModalUtil.showSync(
              deniedText,
              title: '申请您的${title}权限设置',
              confirmText: '前往设置',
              cancelText: cancelText ?? '取消',
            )) ??
            false;
        if (confirm) {
          await openAppSettings();
          if ((await service.request()).isGranted) {
            return true;
          }
        }
      }
    }

    return false;
  }

  ///获取相册权限
  static Future<bool> getPhotoPermission({String? deniedText}) async {
    if (Platform.isAndroid) {
      // 检查多种可能的权限
      bool hasStoragePermission = await Permission.storage.isGranted;
      bool hasPhotosPermission = await Permission.photos.isGranted;
      bool hasMediaLibraryPermission = await Permission.mediaLibrary.isGranted;
      print(hasStoragePermission);
      print(hasPhotosPermission);
      print(hasMediaLibraryPermission);
      // 如果任何一个权限已授予，则认为有相册访问权限
      if (hasPhotosPermission ||
          (hasStoragePermission && hasMediaLibraryPermission)) {
        return true;
      } else {
        // 显示权限用途说明对话框
        bool shouldProceed = await showDialog(
              context: WNavUtil.instance!.navigatorKey.currentContext!,
              builder: (context) => AlertDialog(
                title: Text('申请您的相册访问权限'),
                content: Text('我们需要访问您的相册以便您可以上传头像、任务图片、提交问题反馈等。'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(false),
                    child: Text('拒绝'),
                  ),
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(true),
                    child: Text('允许'),
                  ),
                ],
              ),
            ) ??
            false;
        if (shouldProceed == false) return false;
        bool permission = await Permission.photos.request().isGranted;
        bool permission1 = await Permission.storage.request().isGranted;
        bool permission2 = await Permission.mediaLibrary.request().isGranted;
        if (permission || (permission1 && permission2)) {
          return true;
        } else {
          bool confirm = await WModalUtil.showSync(
                '${deniedText != null ? deniedText : '无法获取相册权限,是否前往设置'}',
                title: '权限申请失败',
                confirmText: '前往设置',
              ) ??
              false;
          if (confirm) {
            await openAppSettings();
            return await Permission.photos.isGranted ||
                (await Permission.storage.isGranted &&
                    await Permission.mediaLibrary.isGranted);
          }
        }
      }
      return false;
    } else {
      bool isSuccess = await Permission.photos.request().isGranted;
      if (isSuccess) {
        return true;
      } else {
        final confirm = await (WModalUtil.showSync(
          '${deniedText != null ? deniedText : '无法获取相册权限,是否前往设置'}',
          title: '权限申请失败',
          confirmText: '前往设置',
        ) as Future<bool>);
        if (confirm) {
          await openAppSettings();
          bool permission = await Permission.photos.request().isGranted;
          return permission;
        }
      }
      return false;
    }
  }

  static Future<bool> getCameraPermission({String? deniedText}) async {
    if (Platform.isAndroid) {
      bool cameraPermission = await Permission.camera.isGranted;
      if (cameraPermission) {
        return true;
      }
      // 显示权限用途说明对话框
      bool shouldProceed = await showDialog(
            context: WNavUtil.instance!.navigatorKey.currentContext!,
            builder: (context) => AlertDialog(
              title: Text('申请您的相机权限'),
              content: Text('我们需要访问您的相机以便您可以拍摄照片上传头像、任务图片、提交问题反馈等。'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: Text('拒绝'),
                ),
                TextButton(
                  onPressed: () => Navigator.of(context).pop(true),
                  child: Text('允许'),
                ),
              ],
            ),
          ) ??
          false;

      if (shouldProceed) {
        bool permission = await Permission.camera.request().isGranted;
        if (permission) {
          return true;
        } else {
          final confirm = await (WModalUtil.showSync(
            '${deniedText != null ? deniedText : '无法获取相机权限,是否前往设置'}',
            title: '权限申请失败',
            confirmText: '前往设置',
          ) as Future<bool>);
          if (confirm) {
            await openAppSettings();
            bool permission = await getAndroidPermission();
            return permission;
          }
        }
        return false;
      }
      return false;
    } else {
      bool isSuccess = await Permission.camera.request().isGranted;
      if (isSuccess) {
        return true;
      } else {
        final confirm = await (WModalUtil.showSync(
          '${deniedText != null ? deniedText : '无法获取相机权限,是否前往设置'}',
          title: '权限申请失败',
          confirmText: '前往设置',
        ) as Future<bool>);
        if (confirm) {
          await openAppSettings();
          bool permission = await Permission.camera.request().isGranted;
          return permission;
        }
      }
    }

    return false;
  }

  static Future<bool> getAndroidPermission() async {
    // final androidInfo = await DeviceInfoPlugin().androidInfo;
    // if (androidInfo.version.sdkInt <= 32) {
    //   /// use [Permissions.storage.status]
    //   bool isSuccess = await Permission.storage.request().isGranted;
    //   if (isSuccess) {
    //     return true;
    //   }
    // } else {
    bool isSuccess = await Permission.photos.request().isGranted;
    if (isSuccess) {
      return true;
    }
    // }
    return false;
  }
}
