import '../../utils/kr_log_util.dart';

class KRUserAvailableSubscribeItem {
  final int id;
  final String name;
  final int deviceLimit;
  final int download;
  final int upload;
  final int traffic;
  final String startTime;
  final String expireTime;
  final List<dynamic> list;
  final bool isTryOut; // 试用标志：true=试用，false=付费

  const KRUserAvailableSubscribeItem({
    this.id = 0,
    this.name = '',
    this.deviceLimit = 0,
    this.download = 0,
    this.upload = 0,
    this.traffic = 0,
    this.startTime = '',
    this.expireTime = '',
    this.list = const [],
    this.isTryOut = false,
  });

  factory KRUserAvailableSubscribeItem.fromJson(Map<String, dynamic> json) {
    // 从 subscribe 对象中获取订阅信息
    final subscribe = json['subscribe'] as Map<String, dynamic>?;

    // 时间字段可能是 int (毫秒时间戳) 或 String (ISO 8601)
    String convertTime(dynamic value) {
      if (value == null) return '';
      if (value is String) return value;
      if (value is int) {
        // 将毫秒时间戳转换为 ISO 8601 字符串
        return DateTime.fromMillisecondsSinceEpoch(value).toIso8601String();
      }
      return value.toString();
    }

    return KRUserAvailableSubscribeItem(
      id: json['id'] as int? ?? 0,
      name: subscribe?['name'] as String? ?? '',
      deviceLimit: subscribe?['device_limit'] as int? ?? 0,
      download: json['download'] as int? ?? 0,
      upload: json['upload'] as int? ?? 0,
      traffic: json['traffic'] as int? ?? 0,
      startTime: convertTime(json['start_time']),
      expireTime: convertTime(json['expire_time']),
      list: (json['list'] as List<dynamic>?) ?? const [],
      isTryOut: subscribe?['is_try_out'] as bool? ?? false,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'device_limit': deviceLimit,
      'download': download,
      'upload': upload,
      'traffic': traffic,
      'start_time': startTime,
      'expire_time': expireTime,
      'list': list,
      'is_try_out': isTryOut,
    };
  }
}

class KRUserAvailableSubscribeList {
  final List<KRUserAvailableSubscribeItem> list;

  const KRUserAvailableSubscribeList({
    this.list = const [],
  });

  factory KRUserAvailableSubscribeList.fromJson(Map<String, dynamic> json) {
    // KRLogUtil.kr_i('订阅json列表: ${json}', tag: 'KRUserAvailableSubscribeList');
    final List<dynamic> listData = (json['list'] as List<dynamic>?) ?? const [];
    return KRUserAvailableSubscribeList(
      list: listData
          .map((item) => KRUserAvailableSubscribeItem.fromJson(item as Map<String, dynamic>))
          .toList(),
    );
  }
}
