import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_update_dialog/flutter_update_dialog.dart';
import 'package:flutter_xupdate/flutter_xupdate.dart';
import 'package:package_info/package_info.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:zhiying_comm/util/shared_prefe_util.dart';
import 'package:zhiying_comm/util/update/app_update_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../log/let_log.dart';

///
/// App更新工具类
///
class AppUpdateUtil {
  static final String _IGNORE_VERSION = "xupdate_ignore_version";

  ///
  /// 初始化更新插件
  ///
  static void initXUpdate() {
    if (Platform.isAndroid) {
      FlutterXUpdate.init(

              ///是否输出日志
              debug: true,

              ///是否使用post请求
              isPost: false,

              ///post请求是否是上传json
              isPostJson: false,

              ///是否开启自动模式
              isWifiOnly: false,

              ///是否开启自动模式
              isAutoMode: false,

              ///需要设置的公共参数
              supportSilentInstall: false,

              ///在下载过程中，如果点击了取消的话，是否弹出切换下载方式的重试提示弹窗
              enableRetry: false)
          .then((value) {
        Logger.log('初始化成功: $value');
      }).catchError((error) {
        print(error);
      });

      FlutterXUpdate.setErrorHandler(onUpdateError: (Map<String, dynamic> message) async {
        Logger.warn(message);
      });

      FlutterXUpdate.setErrorHandler(onUpdateError: (Map<String, dynamic> message) async {
        Logger.warn(message);
      });
    } else {
      Logger.log('ios暂不支持XUpdate更新');
    }
  }

  ///
  /// 检查并且更新app
  ///
  /// @context 上下文
  /// @needToast 是否需要提示最新版本
  /// @mustShowDialog 是否必须弹窗(检查更新页面要弹窗)
  ///
  static void updateApp(BuildContext context, {bool needToast = false, bool mustShowDialog = false}) async {
    UpdateEntity updateEntity = await _checkAppUpdate();
    // 有新版本，进行更新
    if (!EmptyUtil.isEmpty(updateEntity) && updateEntity.hasUpdate) {
      if (Platform.isAndroid) {
        FlutterXUpdate.updateByInfo(
          updateEntity: updateEntity,
          supportBackgroundUpdate: true,
          enableIgnore: mustShowDialog || updateEntity.isForce,
          retryContent: '更新下载速度太慢了，是否考虑切换下载方式？',
          enableRetry: updateEntity.thirdParty,
          overrideGlobalRetryStrategy: true,
          retryUrl: updateEntity.thirdUrl,
        );
      } else if (Platform.isIOS) {
        bool ignore = await isIgnoreVersion(updateEntity?.versionCode?.toString());
        if ((!ignore || mustShowDialog) || updateEntity.isForce || !updateEntity.isIgnorable) {
          String updateUrl = updateEntity.downloadUrl;
          customStyle(context, updateEntity, onUpdate: () {
            // 打开第三方sdk
            launch(updateUrl, forceSafariVC: true, enableJavaScript: true, forceWebView: true);
            Navigator.pop(context);
          });
        }
      }
    } else {
      if (needToast) Fluttertoast.showToast(msg: '已经是最新版本了~');
    }
  }

  /// 检查是否有新版本
  static Future<UpdateEntity> _checkAppUpdate() async {
    try {

      // var result = {
      //   "code": 1,
      //   "data": {
      //     "app_download_thirdparty_url": "https://android.myapp.com/myapp/detail.htm?apkName=com.hairuyi.www&ADTAG=mobile",
      //     "app_download_url": "http://fir.osant.cn/zhiyi",
      //     "app_version": "1",
      //     "app_version_name": "1.0.0",
      //     "content": "更新接口\n完善app页面\n更新站长后台",
      //     "dialog": "1",
      //     "is_force": "0",
      //     "is_ignore": "0",
      //     "is_thirdparty": "1",
      //     "tip": "有新版下载"
      //   },
      //   "msg": "ok"
      // };
      var result = await NetUtil.post('/api/v1/appcheck', method: NetMethod.GET);
      AppUpdateModel model = AppUpdateModel.fromJson(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
      if (!EmptyUtil.isEmpty(model)) {
        return UpdateEntity(
          hasUpdate: model?.dialog == '1',
          isIgnorable: model?.isIgnore == '1' && model?.isForce != '1',
          isForce: model?.isForce == '1',
          versionCode: int.parse(model?.appVersion ?? '1'),
          versionName: model?.appVersionName,
          downloadUrl: model?.appDownloadUrl,
          updateContent: model?.content,
          tip: model?.tip,
          thirdUrl: model?.appDownloadThirdpartyUrl,
          thirdParty: model?.isThirdparty == '1',
        );
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  // IOS 样式
  static void customStyle(BuildContext context, UpdateEntity updateEntity, {@required VoidCallback onUpdate}) {
    UpdateDialog.showUpdate(context,
        width: 250,
        title: "是否升级到${updateEntity?.versionName ?? '1.0.0'}版本？",
        updateContent: updateEntity?.updateContent ?? '',
        titleTextSize: 14,
        contentTextSize: 12,
        buttonTextSize: 12,
        // topImage: Image.asset('assets/bg_update_top.png'),
        extraHeight: 5,
        radius: 8,
        themeColor: Colors.redAccent,
        progressBackgroundColor: Color(0x5AFFAC5D),
        isForce: updateEntity?.isForce ?? false,
        updateButtonText: '升级',
        ignoreButtonText: '忽略此版本',
        enableIgnore: updateEntity?.isIgnorable ?? false, onIgnore: () {
      saveIgnoreVersion(updateEntity?.versionCode?.toString());
      Navigator.pop(context);
    }, onUpdate: onUpdate);
  }

  // 保存忽略的版本号码
  static void saveIgnoreVersion(String newVersion) async {
    if (!EmptyUtil.isEmpty(newVersion)) {
      await SharedPreferencesUtil.setStringValue(_IGNORE_VERSION, newVersion);
    }
  }

  // 是否是忽略版本
  static Future<bool> isIgnoreVersion(String newVersion) async {
    String oldVersion = await SharedPreferencesUtil.getStringValue(_IGNORE_VERSION);
    if (!EmptyUtil.isEmpty(oldVersion) && !EmptyUtil.isEmpty(newVersion)) {
      return oldVersion == newVersion;
    }
    return false;
  }
}
