
import 'dart:convert';

import 'package:app/request/api/common_api.dart';
import 'package:app/utils/common.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';

import 'version_ui.dart';


///显示版本更新弹窗
void showUpdateDialog(BuildContext context) async {
  PackageInfo packageInfo = await PackageInfo.fromPlatform();
  //如果是安卓
  if (isAndroid()) {
    //版本信息
    var versionRes = await getAppVersionApi();

    //比较版本
    int compareResult = compareVersions(
      packageInfo.version,
      versionRes.latestVersion,
    );
    if (compareResult > -1) {
      return;
    }

    //如果是最新版本
    showGeneralDialog(
      context: context,
      barrierDismissible: false,
      barrierLabel: "Update",
      transitionDuration: const Duration(milliseconds: 300),
      pageBuilder: (context, animation, secondaryAnimation) {
        return PopScope(
          canPop: false,
          child: AppUpdateUi(
            version: versionRes.latestVersion,
            updateNotice: versionRes.updateContent,
            uploadUrl: versionRes.downloadUrl,
          ),
        );
      },
    );
  } else {
    var res = await Dio().get("https://itunes.apple.com/lookup?bundleId=com.curainhealth.akhome");
    Map<String, dynamic> resJson = json.decode(res.data);
    if (resJson['results'].length == 0) {
      return;
    }
    var newVersion = resJson['results'][0]['version'];
    //比较版本
    int compareResult = compareVersions(
      packageInfo.version,
      newVersion,
    );
    if (compareResult > 0) {
      return;
    }

  }
}

///比较版本号
int compareVersions(String version1, String version2) {
  List<String> v1Parts = version1.split('.');
  List<String> v2Parts = version2.split('.');
  int length = v1Parts.length > v2Parts.length ? v1Parts.length : v2Parts.length;

  for (int i = 0; i < length; i++) {
    int v1Part = i < v1Parts.length ? int.tryParse(v1Parts[i]) ?? 0 : 0;
    int v2Part = i < v2Parts.length ? int.tryParse(v2Parts[i]) ?? 0 : 0;

    if (v1Part > v2Part) return 1;
    if (v1Part < v2Part) return -1;
  }
  return 0;
}
