import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/src/size_extension.dart';
import 'package:get/get.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wgshare/utils/color_util.dart';
import 'package:wgshare/utils/toast_utils.dart';
import 'package:wgshare/view/upgrade/util/load_file_cancel_request.dart';

import '../../utils/permission/PermissionService.dart';
import '../public_dialog.dart';

upgradeDialog(
  BuildContext context,
  String describe,
  String url,
  String appStoreUrl,
  String versionName, {
  String title = "提示",
  btnWidth = 116.0,
  btnHeight = 42.0,
  bool hideCancelBtn = false,
}) {
  showDialog(
      context: context,
      barrierDismissible: hideCancelBtn,
      builder: (_) => PopScope(
            canPop: hideCancelBtn,
            child: HintDialog(title, describe, url, appStoreUrl, versionName,
                btnWidth, btnHeight, hideCancelBtn),
          ));
}

class HintDialog extends StatefulWidget {
  final String title; //标题
  final String describe; //版本更新内容
  final String url;
  final String appStoreUrl;
  final String versionName;
  final double btnWidth; //按钮宽度
  final double btnHeight; //按钮高度
  final bool hideCancelBtn; //是否隐藏取消btn（实际用途还是否可以点击空白和返回键关闭）

  HintDialog(this.title, this.describe, this.url, this.appStoreUrl,
      this.versionName, this.btnWidth, this.btnHeight, this.hideCancelBtn);

  @override
  State<StatefulWidget> createState() {
    return HintDialogState();
  }
}

class HintDialogState extends State<HintDialog> {
  // 安装按钮状态，0：未点击、1：点击下载、2：下载成功、3：安装成功、4：安装失败
  int confirmBtnType = 0;

  // 按钮文字
  String btnStr = "立即更新";

  // 下载进度
  double progressValue = 0.0;

  // apk路径
  late String apkPath;

  late loadFileCancelRequest loadRequest;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        height: 400.h,
        margin: const EdgeInsets.only(left: 40, right: 40),
        padding:
            const EdgeInsets.only(top: 20, bottom: 20, left: 12, right: 12),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/upappbg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: _contentStyle(),
      ),
    );
  }

  ///内容区域样式
  _contentStyle() {
    return Column(
      children: <Widget>[
        // _title(),
        Expanded(
          child: Container(),
        ),
        _hintMsg(),
        Visibility(
          visible: confirmBtnType == 1 ? true : false,
          child: Container(
            width: double.infinity,
            height: 4.h,
            color: ColorUtil.Color_85_117_242,
            margin: const EdgeInsets.only(top: 12, left: 2, right: 2),
            child: LinearProgressIndicator(
              value: progressValue,
              valueColor:
                  const AlwaysStoppedAnimation(ColorUtil.Color_85_117_242),
              backgroundColor: ColorUtil.Color_185_184_184,
            ),
          ),
        ),
        GestureDetector(
          child: Container(
            width: double.infinity,
            height: 50.h,
            decoration: const BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(6)),
              color: ColorUtil.Color_85_117_242,
            ),
            margin: const EdgeInsets.only(top: 12),
            alignment: Alignment.center,
            child: Text(
              btnStr,
              style: TextStyle(
                  fontSize: 14.sp, color: ColorUtil.Color_255_255_255),
            ),
          ),
          onTap: () {
            if (Platform.isIOS) {
              _gotoAppStore();
            } else {
              if (confirmBtnType == 0) {
                _downloadApk();
              }
              if (confirmBtnType == 1) {
                Navigator.of(context).pop();
              }
              if (confirmBtnType == 2) {
                PermissionService.checkPermission(permissionList: [Permission.manageExternalStorage]).then((value){
                  if(value == true){
                    // 下载完成，调用安装APK函数
                    _installApk(apkPath);
                  }else{
                    publicDialog(context,
                        hideCancelBtn: true,
                        title: '请求权限说明',
                        describe:
                        'APP需要获取您的文件访问权限，用以确保新版本下载后可以正常安装。',
                        leftBtnStr: '拒绝',
                        rightBtnStr: '同意',
                        leftBtnCallback: () {
                        }, rightBtnCallback: () {
                          PermissionService.requestStoragePermissions();
                        });
                  }
                });
              }
              if (confirmBtnType == 3) {
                SystemNavigator.pop();
              }
              if (confirmBtnType == 4) {
                Navigator.of(context).pop();
              }
            }
          },
        ),
        Visibility(
          visible: widget.hideCancelBtn,
          child: GestureDetector(
            child: Container(
              margin: const EdgeInsets.only(top: 20),
              child: Text(
                "跳过此版本",
                style: TextStyle(
                    fontSize: 14.sp,
                    color: ColorUtil.Color_84_84_84
                ),
              ),
            ),
            onTap: (){
              Get.back();
            },
          ),
        )
      ],
    );
  }

  ///提示标题布局
  _title() {
    return Container(
      alignment: Alignment.center,
      margin: const EdgeInsets.only(bottom: 12),
      child: Text(widget.title,
          style: TextStyle(
              fontSize: 16.sp,
              color: ColorUtil.Color_85_117_242,
              fontWeight: FontWeight.w600,
              decoration: TextDecoration.none)),
    );
  }

  ///提示信息布局
  _hintMsg() {
    return SingleChildScrollView(
      child: Container(
        alignment: Alignment.topLeft,
        margin: const EdgeInsets.only(),
        child: Text(widget.describe,
            style: const TextStyle(
                fontSize: 14,
                color: ColorUtil.Color_244_244_244,
                decoration: TextDecoration.none,
                height: 1.4)),
      ),
    );
  }

  /// 下载APK
  _downloadApk() async {
    loadRequest = loadFileCancelRequest();
    try {
      // 设置apk下载路径
      var appDocDir = await getTemporaryDirectory();
      apkPath = "${appDocDir.path}/wgshare_${widget.versionName}.apk";

      loadRequest.load(widget.url, apkPath);

      loadRequest.setProgressCallbackListener((progress) {
        setState(() {
          progressValue = progress;
        });
      });

      loadRequest.setSuccessCallbackListener(() {
        setState(() {
          confirmBtnType = 2;
          btnStr = "安装";
        });
      });

      setState(() {
        confirmBtnType = 1;
        btnStr = "取消";
      });
    } catch (e) {
      debugPrint("检查更新-安卓下载失败：$e");
      setState(() {
        confirmBtnType = 0;
        btnStr = "更新";
      });
      ToastUtils.showError("下载失败");
    }
  }

  /// 安装APK
  _installApk(String path) async {
    await InstallPlugin.installApk(path, appId: "com.yuanxuan.wgshare").then((result) {
      debugPrint("检查更新-安卓安装成功：$result");
      setState(() {
        confirmBtnType = 3;
        btnStr = "关闭APP，重新打开";
      });
    }).catchError((error) {
      debugPrint("检查更新-安卓安装失败：$error");
      setState(() {
        confirmBtnType = 4;
        btnStr = "跳过";
      });
    });
  }

  /// 跳转苹果应用商店
  _gotoAppStore() async {
    await InstallPlugin.install(widget.appStoreUrl).then((result){
      debugPrint("检查更新-苹果安装成功：$result");
    }).catchError((error){
      debugPrint("检查更新-苹果安装失败：$error");
    });
  }
}
