import 'package:flutter/material.dart';
import '../widget/Dialog.dart';
import 'dart:io';
import 'package:url_launcher/url_launcher.dart';
import 'package:package_info/package_info.dart';
import '../net/HttpManager.dart';
import '../net/Result.dart';

bool checkPhone(phone) {
  bool result = false;
  RegExp exp = RegExp(r'^1[3-9]\d{9}$');
  if (exp.hasMatch(phone)) {
    result = true;
  }
  return result;
}

int CompareVersion(String l, String r) {
  l = l.trim();
  r = r.trim();
  if (l == r) {
    return 0;
  }

  var lVers = l.split('.');
  var rVers = r.split('.');
  var length = lVers.length < rVers.length ? lVers.length : rVers.length;
  for (int i = 0; i < length; i++) {
    if (lVers[i] == rVers[i]) {
      continue;
    }

    return int.parse(lVers[i]).compareTo(int.parse(rVers[i]));
  }

  var temp = lVers.length < rVers.length ? rVers : lVers;
  for (int i = length; i < temp.length; i++) {
    if (int.parse(temp[i]) != 0) {
      return lVers.length < rVers.length ? -1 : 1;
    }
  }

  return 0;
}

Future<void> getVersion(BuildContext context) async {
  print('检查更新');
  PackageInfo packageInfo = await PackageInfo.fromPlatform();
  String version = packageInfo.version;
  Result versionres = await HttpManager.get('appVersion/getAppVersion?id=1');
  if (versionres.success&&versionres.data!=null) {
    if ((CompareVersion(version, versionres.data['androidVersion']) < 0 && Platform.isAndroid) ||
        (CompareVersion(version, versionres.data['iosVersion']) < 0 && Platform.isIOS)) {
      MyDialog.showDialog(context, '检测到新版本，是否立即更新?', isCancel: true, onsubmit: () async {
        String url = HttpManager.baseUrl + 'phone/#/downLoad';
        if (await canLaunch(url)) {
          await launch(url);
        } else {
          throw 'Could not launch $url';
        }
      });
    }
  }
}
