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 '../../common/store/business_store.dart';
import '../../utils/permission/PermissionService.dart';
import '../public_dialog.dart';

hideUpgradeDialog(
  BuildContext context,
  String describe,
  String apkSavePath,
  String appStoreUrl,
    int versionCode,{
  btnWidth = 116.0,
  btnHeight = 42.0,
  bool hideCancelBtn = false,
}) {
  showDialog(
      context: context,
      barrierDismissible: hideCancelBtn,
      builder: (_) => PopScope(
            canPop: hideCancelBtn,
            child: HintDialog(describe, apkSavePath, appStoreUrl, versionCode, btnWidth,
                btnHeight, hideCancelBtn),
          ));
}

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

  HintDialog(this.describe, this.apkSavePath, this.appStoreUrl, this.versionCode, this.btnWidth,
      this.btnHeight, this.hideCancelBtn);

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

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

  // 按钮文字
  String btnStr = "立即安装";

  // 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: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/upappbg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: _contentStyle(),
      ),
    );
  }

  ///内容区域样式
  _contentStyle() {
    return Column(
      children: <Widget>[
        // _title(),
        Expanded(
          child: Container(),
        ),
        _hintMsg(),
        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) {
                PermissionService.checkPermission(permissionList: [Permission.manageExternalStorage]).then((value){
                  if(value == true){
                    _installApk();
                  }else{
                    publicDialog(Get.context!,
                        hideCancelBtn: true,
                        title: '请求权限说明',
                        describe:
                        'APP需要获取您的文件访问权限，用以确保新版本下载后可以正常安装。',
                        leftBtnStr: '拒绝',
                        rightBtnStr: '同意',
                        leftBtnCallback: () {
                          BusinessStore.to.setIsRefuseHomeCheckPermission(true);
                        }, rightBtnCallback: () {
                          PermissionService.requestStoragePermissions().then((value){
                            if(value == true){
                              _installApk();
                            }
                          });
                        });
                  }
                });
              }
              /*if (confirmBtnType == 1) {
                SystemNavigator.pop();
              }
              if (confirmBtnType == 2) {
                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: () {
              BusinessStore.to.setSkipUpVersion(widget.versionCode);
              Get.back();
            },
          ),
        )
      ],
    );
  }

  ///提示信息布局
  _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
  _installApk() async {
    await InstallPlugin.installApk(widget.apkSavePath, appId: "com.yuanxuan.wgshare").then((result) {
      debugPrint("检查更新-安卓安装成功：$result");
      /*setState(() {
        confirmBtnType = 2;
        btnStr = "关闭APP，重新打开";
      });*/
      BusinessStore.to.erase();
    }).catchError((error) {
      debugPrint("检查更新-安卓安装失败：$error");
      /*setState(() {
        confirmBtnType = 2;
        btnStr = "跳过";
      });*/
    });
  }

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