/*
 * @Descripttion: 下载APK
 * @version: DownloadApk
 * @Author: wy
 * @Date: 2020-07-30 15:54:40
 * @LastEditors: wangyang 1147192855@qq.com
 * @LastEditTime: 2022-08-02 15:12:21
 */
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:marking_app/provider/upgrade_provider.dart';
// import 'package:install_plugin_v2/install_plugin_v2.dart';
import 'package:marking_app/utils/app_upgrade/model/UpdateAppEvent.dart';
import 'package:marking_app/utils/index.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';

class DownloadApk {
  /// 下载安卓更新包
  static Future<File?> _downloadAndroid(context, UpdateAppEvent event, WidgetRef ref) async {
    /// 创建存储文件
    Directory? storageDir = await getExternalStorageDirectory();
    final storagePath = storageDir?.path ?? '/';
    String version = event.version.replaceAll(".", "-");
    File file = new File('$storagePath/${event.appName}v$version.apk');
    if (await file.exists()) await file.delete();
    if (!file.existsSync()) file.createSync();
    try {
      /// 发起下载请求
      Response response = await Dio().get(
        event.link,
        onReceiveProgress: (num received, num total) {
          showDownloadProgress(context, received, total, ref);
        },
        options: Options(
          responseType: ResponseType.bytes,
          followRedirects: false,
        ),
      );
      file.writeAsBytesSync(response.data);
      return file;
    } catch (e) {
      print(e);
      // toPrint(val: e);
    }
  }

  // 安装apk
  static Future<bool> installApk(context, UpdateAppEvent event, WidgetRef ref) async {
    File? _apkFile = await _downloadAndroid(context, event, ref);
    if (_apkFile == null) return false;
    String _apkFilePath = _apkFile.path;
    if (_apkFilePath.isEmpty) {
      debugPrint('make sure the apk file is set');
      return false;
    }

    Map<Permission, PermissionStatus> statuses = await [Permission.storage].request();

    if (statuses[Permission.storage]!.isGranted) {
      // String? result = await InstallPlugin.installApk(_apkFilePath, appId: event.packageName).catchError((error) {
      //   debugPrint('install apk error: $error');
      // });
      // debugPrint('install apk $result');
      // ToastUtils.getFluttertoast(context: context, msg: 'install apk $result');
      try {
        final result = await InstallPlugin.installApk(_apkFilePath, appId: event.packageName);
        print('这是是执行安装的程序：' + result.runtimeType.toString());
        if (result['isSuccess'] ?? false) {
          ToastUtils.showSuccess('install apk $result');
          RestartWidget.restartApp(context); // 安装成功 重启APP
          return true;
        }
      } catch (e) {}
    } else {
      debugPrint('Permission request fail!');
    }

    return false;
  }

  /// 展示下载进度
  static void showDownloadProgress(context, num received, num total, WidgetRef ref) {
    if (total != -1) {
      double progress = double.parse((received / total).toStringAsFixed(2));
      debugPrint('下载进度$progress');
      ref.read(upgradeProvider.notifier).setVal(progress);
    }
  }
}

class RestartWidget extends StatefulWidget {
  final Widget child;

  RestartWidget({required this.child});

  static restartApp(BuildContext context) {
    final _RestartWidgetState? state = context.findAncestorStateOfType<_RestartWidgetState>();
    state?.restartApp();
  }

  @override
  _RestartWidgetState createState() => _RestartWidgetState();
}

class _RestartWidgetState extends State<RestartWidget> {
  Key key = UniqueKey();

  void restartApp() {
    setState(() {
      key = UniqueKey();
    });
  }

  @override
  Widget build(BuildContext context) {
    return KeyedSubtree(
      key: key,
      child: widget.child,
    );
  }
}
