import 'dart:convert';
import 'dart:io';

import 'package:al_downloader/al_downloader.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:wgshare/utils/toast_utils.dart';
import 'package:wgshare/view/upgrade/hide_upgrade_dialog.dart';
import '../../../common/models/app_updata_info_entity.dart';
import '../../../common/store/business_store.dart';
import '../../../utils/routeUtil.dart';
import 'entity/upgrade_entity.dart';

class HideCheckVersion{
  Future<Map> request(String url) async{
    Response response = await Dio().get(url);
    return response.data;
  }

  Future<void> doHttpHideCheckVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String versionCode = packageInfo.buildNumber;

    if(null != BusinessStore.to.appUpdataInfoEntity.value){
      ToastUtils.showSuccess('00000');
      if(int.tryParse(versionCode)! < BusinessStore.to.appUpdataInfoEntity.value!.versionCode){
        ToastUtils.showSuccess('11111--缓存跳过版本${BusinessStore.to.skipUpVersion}-缓存安装版本${BusinessStore.to.appUpdataInfoEntity.value!.versionCode}');
        if(null != BusinessStore.to.skipUpVersion){
          if(BusinessStore.to.skipUpVersion! < BusinessStore.to.appUpdataInfoEntity.value!.versionCode){
            hideUpgradeDialog(
              RouteUtil.getContext(),
              BusinessStore.to.appUpdataInfoEntity.value!.versionDescribe,
              hideCancelBtn: BusinessStore.to.appUpdataInfoEntity.value!.updateType == 1 ? false : true,
              BusinessStore.to.appUpdataInfoEntity.value!.apkSavePath,
              BusinessStore.to.appUpdataInfoEntity.value!.appStoreUrl,
              BusinessStore.to.appUpdataInfoEntity.value!.versionCode,
            );
          }else{
            ToastUtils.showSuccess('22222');
            doHttpUp();
          }
        }else{
          doHttpUp();
        }
      }else{
        ToastUtils.showSuccess('33333');
        BusinessStore.to.erase();
      }
    }else{
      ToastUtils.showSuccess('44444');
      doHttpUp();
    }
  }

  Future<void> doHttpUp() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String versionCode = packageInfo.buildNumber;

    Future<Map> map = request("http://192.168.2.9:8827/latest.json");
    map.then((result) async {
      var jsonStr = json.encode(result);
      var listDynamic = jsonDecode(jsonStr);
      UpgradeEntity upgradeEntity = UpgradeEntity.fromJson(listDynamic);

      debugPrint('55555${upgradeEntity.code}-${upgradeEntity.data.versionCode}-${upgradeEntity.data.androidurl}');
      ToastUtils.showSuccess('55555${upgradeEntity.code}-${upgradeEntity.data.versionCode}-${upgradeEntity.data.androidurl}');

      if(upgradeEntity.code == 200){

        debugPrint("检查更新-服务器版本信息：$jsonStr");
        debugPrint("检查更新-当前版本号：$versionCode");

        if(int.tryParse(versionCode)! < upgradeEntity.data.versionCode){
          if((BusinessStore.to.skipUpVersion ?? 0) < upgradeEntity.data.versionCode){
            if (Platform.isAndroid) {
              /// 下载APK
              try {
                var appDocDir = await getTemporaryDirectory();
                var apkSavePath = "${appDocDir.path}/wgshare_up.apk";
                // String url = "https://www.onlinedown.net/iopdfbhjl/632869?module=download&t=website&v=20241229163449";
                // String url = "https://s3.cn-north-1.amazonaws.com.cn/mtab.kezaihui.com/apk/takeaway_phone_release_1.apk";
                String url = upgradeEntity.data.androidurl;
                ALDownloader.download(url,
                    directoryPath: "${appDocDir.path}/",
                    fileName: "wgshare_up.apk",
                    handlerInterface:
                    ALDownloaderHandlerInterface(progressHandler: (progress) {
                      debugPrint('检查更新 | 下载进度 = $progress, url = $url');
                      ToastUtils.showSuccess('下载进度$progress');
                    }, succeededHandler: () {
                      debugPrint('检查更新 | 下载成功, url = $url');
                      debugPrint('检查更新，当前路由是：${RouteUtil.getRoute()}');
                      debugPrint('检查更新，APK保存路径：$apkSavePath');

                      BusinessStore.to.setAppUpdataInfo(AppUpdataInfoEntity(
                          upgradeEntity.data.versionCode,
                          upgradeEntity.data.versionName,
                          upgradeEntity.data.updateType,
                          upgradeEntity.data.versionDescribe,
                          upgradeEntity.data.androidurl,
                          upgradeEntity.data.appStoreUrl,
                          apkSavePath
                      ));

                      if (RouteUtil.getRoute() == '/meetingMainPage') {
                        ToastUtils.showInfo(
                            "新版本静默下载完毕\n将择机通知安装",
                            duration: const Duration(milliseconds: 3000));
                      } else {
                        hideUpgradeDialog(
                          RouteUtil.getContext(),
                          upgradeEntity.data.versionDescribe,
                          hideCancelBtn: upgradeEntity.data.updateType == 1 ? false : true,
                          apkSavePath,
                          '',
                          upgradeEntity.data.versionCode,
                        );
                      }
                    }, failedHandler: () {
                      debugPrint('检查更新 | 下载失败, url = $url');
                    }, pausedHandler: () {
                      debugPrint('检查更新 | 下载暂停, url = $url');
                    }));
              } catch (e) {
                debugPrint("检查更新-安卓下载失败：$e");
              }
            }else{
              hideUpgradeDialog(
                RouteUtil.getContext(),
                upgradeEntity.data.versionDescribe,
                hideCancelBtn: upgradeEntity.data.updateType == 1 ? false : true,
                '',
                upgradeEntity.data.appStoreUrl,
                upgradeEntity.data.versionCode,
              );
            }
          }
        }else{
          return;
        }
      }else{
        return;
      }
    });
  }
}

