/// 版本信息 — POST uc/ancillary/system/app/version/0
class AppVersion {
  final String id;
  final String publishTime;
  final String remark;
  final String newVersion;
  final String downloadUrl;
  final String platform;
  final String lowestVersion;
  final String updateDescription;

  const AppVersion({
    this.id = '',
    this.publishTime = '',
    this.remark = '',
    this.newVersion = '',
    this.downloadUrl = '',
    this.platform = '',
    this.lowestVersion = '',
    this.updateDescription = '',
  });

  factory AppVersion.fromJson(Map<String, dynamic> json) {
    return AppVersion(
      id: json['id']?.toString() ?? '',
      publishTime: json['publishTime']?.toString() ?? '',
      remark: json['remark']?.toString() ?? '',
      newVersion: json['version']?.toString() ?? '',
      downloadUrl: json['downloadUrl']?.toString() ?? '',
      platform: json['platform']?.toString() ?? '',
      lowestVersion: json['lowestVersion']?.toString() ?? '',
      updateDescription: json['updateDescription']?.toString() ?? '',
    );
  }

  /// 是否有新版本（newVersion > currentVersion）
  bool hasNewVersion(String currentVersion) {
    return _compareVersion(newVersion, currentVersion) > 0;
  }

  /// 是否需要强制更新（lowestVersion > currentVersion）
  bool isForceUpdate(String currentVersion) {
    if (lowestVersion.isEmpty) return false;
    return _compareVersion(lowestVersion, currentVersion) > 0;
  }

  /// 版本号比较：按 . 分割逐段比较
  /// 返回 >0 表示 a > b, <0 表示 a < b, 0 表示相等
  static int _compareVersion(String a, String b) {
    if (a.isEmpty || b.isEmpty) return 0;
    final partsA = a.split('.').map((e) => int.tryParse(e) ?? 0).toList();
    final partsB = b.split('.').map((e) => int.tryParse(e) ?? 0).toList();
    final maxLen = partsA.length > partsB.length ? partsA.length : partsB.length;
    for (var i = 0; i < maxLen; i++) {
      final va = i < partsA.length ? partsA[i] : 0;
      final vb = i < partsB.length ? partsB[i] : 0;
      if (va != vb) return va - vb;
    }
    return 0;
  }
}
