/*
 * @Descripttion: 获取本地权限
 * @version: UpgradePermission
 * @Author: wy
 * @Date: 2020-07-30 15:41:39
 * @LastEditors: wangyang 1147192855@qq.com
 * @LastEditTime: 2022-08-01 14:08:57
 */
import 'package:app_installer/app_installer.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import 'model/UpdateAppEvent.dart';

class UpgradePermission {
  final String _flatform;
  const UpgradePermission(this._flatform);

  /// 检查是否有权限，用于安卓
  /// noExecutions 执行次数
  Future<bool> checkPermission(BuildContext context, UpdateAppEvent updateAppEvent, [int? noExecutions]) async {
    noExecutions ??= 1;
    if (_flatform != 'android') return true; // 非安卓
    var status = await Permission.storage.request();
    if (status.isGranted) return true;

    if (status.isDenied) {
      // 普通拒绝 可以再进行提示

      await showDialog<bool>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text("权限提示"),
            content: const Text("无法获取存储权限，请同意获取设备存储权限"),
            actions: [
              MaterialButton(
                color: Theme.of(context).primaryColor,
                child: const Text("同意", style: TextStyle(color: Colors.white)),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ],
          );
        },
      );

      if (noExecutions < 2) return checkPermission(context, updateAppEvent, ++noExecutions);
      // 执行次数大于2次，就不再询问直接打开设置权限页面（防止某些机型不会弹起权限询问交互弹框）
    }

    // 拒绝并不再提示
    bool? res = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("权限提示"),
          content: const Text("储存权限被永久拒绝，并且不再提示。请前往设置页面同意储存权限"),
          actions: [
            MaterialButton(
              color: Colors.green.shade900,
              child: const Text("其它方式更新", style: TextStyle(color: Colors.white)),
              onPressed: () => Navigator.of(context).pop(false),
            ),
            MaterialButton(
              color: Theme.of(context).primaryColor,
              child: const Text("前往设置", style: TextStyle(color: Colors.white)),
              onPressed: () => Navigator.of(context).pop(true),
            ),
          ],
        );
      },
    );
    if (res == null || !res) {
      // 其他方式下载
      // await SystemNavigator.pop(); // 退出APP
      var options = ['应用市场更新APP', '浏览器下载并安装APP'];
      var uri = Uri.parse('market://details?id=${updateAppEvent.packageName}'); // 应用市场URI
      // if (!await canLaunchUrl(uri)) options.removeAt(0); // 如果不能打开应用市场 就屏蔽掉 这个安装方式
      String? option = await showCustomModalBottomSheet(context, options);
      if (option == '应用市场更新APP') {
        if (await canLaunchUrl(uri)) {
          await launchUrl(uri);
        } else {
          await AppInstaller.goStore(updateAppEvent.packageName, 'iOSAppId');
        }
      }
      if (option == '浏览器下载并安装APP') await launchUrl(Uri.parse(updateAppEvent.link));
    } else
      await openAppSettings();
    return false;
  }

  // 其他方式下载选择
  static Future<String?> showCustomModalBottomSheet(context, List<String> options) async {
    return showModalBottomSheet<String>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return Container(
          clipBehavior: Clip.antiAlias,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: const Radius.circular(20.0),
              topRight: const Radius.circular(20.0),
            ),
          ),
          height: MediaQuery.of(context).size.height / 4.0,
          child: Column(children: [
            SizedBox(
              height: 50,
              child: Stack(
                textDirection: TextDirection.rtl,
                children: [
                  Center(child: Text('选择其它方式更新APP', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0))),
                  IconButton(icon: Icon(Icons.close), onPressed: () => Navigator.of(context).pop()),
                ],
              ),
            ),
            Divider(height: 1.0),
            Expanded(
              child: ListView.builder(
                itemCount: options.length,
                itemBuilder: (BuildContext context, int index) {
                  var name = options[index];
                  return ListTile(
                    title: Text(name),
                    trailing: Icon(name.contains('浏览器') ? Icons.browser_updated_outlined : Icons.local_grocery_store_outlined),
                    onTap: () => Navigator.of(context).pop(name),
                  );
                },
              ),
            ),
          ]),
        );
      },
    );
  }
}
