import 'dart:async';

import 'package:app_settings/app_settings.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:making_school_asignment_app/page/global_widget/my_text.dart';
import 'package:permission_handler/permission_handler.dart';

class PermissionDescribePage extends StatefulWidget {
  final String title;
  final String describe;
  final List<Permission> permissions;

  const PermissionDescribePage({required this.title, required this.describe, required this.permissions, super.key});

  @override
  State<PermissionDescribePage> createState() => _PermissionDescribePageState();
}

class _PermissionDescribePageState extends State<PermissionDescribePage> with WidgetsBindingObserver {
  Timer? _timerPermission;
  bool theOpenAppSettings = false;
  int theExecutionFrequency = 0;

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);

    Future.delayed(const Duration(seconds: 3), () {
      getCheckPermission(context);
    });
    super.initState();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print("-didChangeAppLifecycleState-$state");
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        break;
      case AppLifecycleState.resumed: //从后台切换前台，界面可见
        if (theOpenAppSettings) {
          getCheckPermission(context);
        }
        break;
      case AppLifecycleState.paused: // 界面不可见，后台
        break;
      case AppLifecycleState.detached: // APP结束时调用
        break;
      case AppLifecycleState.hidden:
      // TODO: Handle this case.
    }
  }

  @override
  void dispose() {
    _timerPermission?.cancel();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  void getCheckPermission(BuildContext context) async {
    theOpenAppSettings = false;
    theExecutionFrequency++;

    List<Permission> permissions = []; // 普通拒绝
    List<Permission> permanentRefusal = []; // 永久拒绝
    for (var i = 0; i < widget.permissions.length; i++) {
      var p = widget.permissions[i];
      var status = await p.status;
      var shouldShowRequestRationale = await p.shouldShowRequestRationale;
      if (!status.isGranted) {
        if (status.isDenied) {
          if (shouldShowRequestRationale) {
            /// 说明情况，再次發起权限请求（已经拒绝一次了）
            await showDialog(
              context: context,
              barrierDismissible: false,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: quickText(widget.title, fontWeight: FontWeight.bold),
                  content: quickText(widget.describe, maxLines: 20),
                  actions: [
                    ElevatedButton(
                      onPressed: () async => Navigator.of(context).pop(),
                      child: const Text('我已知晓'),
                    )
                  ],
                );
              },
            );
          }
          permissions.add(p);
        } else if (status.isPermanentlyDenied) {
          permanentRefusal.add(p);
        }
      }
    }

    if (permissions.isNotEmpty) {
      // 普通拒绝
      permanentRefusal.addAll(await getStoragePermission(context, permissions));
    }

    if (permanentRefusal.isNotEmpty) {
      /// 被永久拒绝了 需要弹出对话框说明 使用户自行操作
      await showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            content: quickText(widget.describe, maxLines: 20),
            title: quickText(widget.title, fontWeight: FontWeight.bold),
            actions: [
              ElevatedButton(
                onPressed: () async {
                  Navigator.of(context).pop();
                  theOpenAppSettings = true;
                  await AppSettings.openAppSettings(asAnotherTask: true);
                },
                child: const Text('前往APP权限设置'),
              )
            ],
          );
        },
      );
    } else {
      Navigator.of(Get.context ?? context).pop();
    }
  }

  /// 权限发起请求
  /// @param List<Permission> permissions   权限集合
  Future<List<Permission>> getStoragePermission(BuildContext context, List<Permission> permissions,
      [int executionFrequency = 0]) async {
    Map<Permission, PermissionStatus> statusRes = await permissions.request();

    List<Permission> permanentRefusal = []; // 永久拒绝

    List<Permission> keys = statusRes.keys.toList();

    for (var i = 0; i < keys.length; i++) {
      Permission key = keys[i];
      PermissionStatus status = statusRes[key]!;
      if (status.isPermanentlyDenied) {
        /// 添加永久拒绝的权限集合
        permanentRefusal.add(key);
      } else if (status.isDenied) {
        /// 如果权限被永久拒绝，我们可能需要引导用户到应用设置中手动开启权限，显示一个对话框，解释为什么需要这个权限
        /// 应用之前已经请求过该权限，并且用户选择了“拒绝”，但没有选择“不再询问”（即没有永久拒绝）。
        /// 系统认为向用户显示一个权限请求的说明是合适的，以便用户理解为什么应用需要这个权限。
        if (await key.shouldShowRequestRationale) {
          /// 说明情况，再次發起权限请求（已经拒绝一次了）
          /// TODO 对话框 说明情况 再发发起请求
          await showDialog(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return AlertDialog(
                title: quickText(widget.title, fontWeight: FontWeight.bold),
                content: quickText(widget.describe, maxLines: 20),
                actions: [
                  ElevatedButton(
                    onPressed: () async => Navigator.of(context).pop(),
                    child: const Text('我已知晓'),
                  )
                ],
              );
            },
          );
        }
        if (permissions.length == 1 && key == permissions[0]) {
          executionFrequency++;
        }
        if (executionFrequency <= 1) {
          var res = await getStoragePermission(context, [key], executionFrequency);
          permanentRefusal.addAll(res);
        } else {
          permanentRefusal.add(key);
        }

        // break;
      }
    }
    return permanentRefusal;
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
        canPop: false,
        child: Container(
          width: ScreenUtil().screenWidth,
          height: ScreenUtil().screenHeight,
          decoration: const BoxDecoration(color: Colors.transparent),
          child: Column(
            children: [
              SizedBox(height: ScreenUtil().screenHeight * 0.1),
              Container(
                width: ScreenUtil().screenWidth * 0.9,
                padding: EdgeInsets.symmetric(vertical: 20.h, horizontal: 20.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(10.r),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.5), // 阴影颜色
                      spreadRadius: 2, // 水平和垂直方向上扩展范围
                      blurRadius: 4, // 模糊半径
                      offset: const Offset(0, 3), // X 和 Y 的偏移量
                    ),
                  ],
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    quickText(widget.title, size: 24.sp),
                    quickText(widget.describe, maxLines: 20),
                  ],
                ),
              ),
              const Expanded(child: SizedBox()),
            ],
          ),
        ));
  }
}

class PermissionDescribeUtil {
  static PermissionDescribeUtil? _instance;

  PermissionDescribeUtil._internal();

  static PermissionDescribeUtil get instance => _instance ??= PermissionDescribeUtil._internal();

  /// 发起权限请求
  Future<void> toLaunchPermissionRequest(
    BuildContext context, {
    required String title,
    required String describe,
    required List<Permission> permissions,
  }) async {
    var isGranted = false;
    for (var i = 0; i < permissions.length; i++) {
      var p = permissions[i];
      if (!(await p.status.isGranted)) {
        isGranted = true;
        break;
      }
    }
    if (isGranted) {
      await Navigator.of(Get.context ?? context).push(PageRouteBuilder(
          opaque: false,
          pageBuilder: (context, animation, secondaryAnimation) {
            return PermissionDescribePage(
              title: title,
              describe: describe,
              permissions: permissions,
            );
          }));
    }

    // await Navigator.of(context).push(
    //   transparentRoute<PermissionDescribePage>(
    //     builder: (context) => PermissionDescribePage(
    //       title: title,
    //       describe: describe,
    //       permissions: permissions,
    //     ),
    //   ),
    // );
  }
}

// Route transparentRoute<T>({
//   required WidgetBuilder builder,
//   RouteSettings? settings,
// }) {
//   return PageRouteBuilder<T>(
//     pageBuilder: (
//       BuildContext context,
//       Animation<double> animation,
//       Animation<double> secondaryAnimation,
//     ) {
//       return builder(context);
//     },
//     transitionsBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
//       return child;
//     },
//     barrierDismissible: false, // 允许点击返回按钮关闭页面
//     // barrierColor: Colors.transparent, // 透明屏障颜色
//   );
// }
