/// C2C订单类型
enum C2cOrderType {
  buy,  // 买入积分股（用积分值换积分股）
  sell, // 卖出积分股（用积分股换积分值）
}

/// C2C订单状态
enum C2cOrderStatus {
  pending,    // 待接单
  matched,    // 已匹配（等待付款）
  paid,       // 已付款（等待确认收款）
  completed,  // 已完成
  cancelled,  // 已取消
  expired,    // 已过期
}

/// C2C收款方式
enum C2cPaymentMethod {
  greenPoints, // 绿积分
  alipay,      // 支付宝
  wechat,      // 微信
  bank,        // 银行卡
}

/// C2C订单模型
class C2cOrderModel {
  final String orderNo;
  final C2cOrderType type;
  final String makerAccountSequence;
  final String? makerPhone;
  final String? makerNickname;
  final String? takerAccountSequence;
  final String? takerPhone;
  final String? takerNickname;
  final String price;           // 单价
  final String quantity;        // 数量（积分股）
  final String totalAmount;     // 总金额（积分值）
  final String minAmount;       // 最小交易量
  final String maxAmount;       // 最大交易量
  // 收款信息
  final C2cPaymentMethod? paymentMethod;  // 收款方式
  final String? paymentAccount;           // 收款账号
  final String? paymentQrCode;            // 收款二维码URL
  final String? paymentRealName;          // 收款人实名
  // 超时配置
  final int paymentTimeoutMinutes;        // 付款超时时间（分钟）
  final int confirmTimeoutMinutes;        // 确认收款超时时间（分钟）
  final DateTime? paymentDeadline;        // 付款截止时间
  final DateTime? confirmDeadline;        // 确认收款截止时间
  // 付款水单
  final String? paymentProofUrl;          // 付款水单图片URL
  // Bot 自动购买相关
  final bool botPurchased;                // 是否被 Bot 购买
  final String? sellerKavaAddress;        // 卖家 Kava 地址
  final String? paymentTxHash;            // dUSDT 支付交易哈希
  // 其他
  final C2cOrderStatus status;
  final String? remark;
  final DateTime createdAt;
  final DateTime? matchedAt;
  final DateTime? paidAt;
  final DateTime? completedAt;
  final DateTime? expiredAt;

  C2cOrderModel({
    required this.orderNo,
    required this.type,
    required this.makerAccountSequence,
    this.makerPhone,
    this.makerNickname,
    this.takerAccountSequence,
    this.takerPhone,
    this.takerNickname,
    required this.price,
    required this.quantity,
    required this.totalAmount,
    required this.minAmount,
    required this.maxAmount,
    // 收款信息
    this.paymentMethod,
    this.paymentAccount,
    this.paymentQrCode,
    this.paymentRealName,
    // 超时配置
    this.paymentTimeoutMinutes = 15,
    this.confirmTimeoutMinutes = 60,
    this.paymentDeadline,
    this.confirmDeadline,
    // 付款水单
    this.paymentProofUrl,
    // Bot 自动购买相关
    this.botPurchased = false,
    this.sellerKavaAddress,
    this.paymentTxHash,
    // 其他
    required this.status,
    this.remark,
    required this.createdAt,
    this.matchedAt,
    this.paidAt,
    this.completedAt,
    this.expiredAt,
  });

  factory C2cOrderModel.fromJson(Map<String, dynamic> json) {
    return C2cOrderModel(
      orderNo: json['orderNo'] ?? '',
      type: _parseOrderType(json['type']),
      makerAccountSequence: json['makerAccountSequence'] ?? '',
      makerPhone: json['makerPhone'],
      makerNickname: json['makerNickname'],
      takerAccountSequence: json['takerAccountSequence'],
      takerPhone: json['takerPhone'],
      takerNickname: json['takerNickname'],
      price: json['price']?.toString() ?? '0',
      quantity: json['quantity']?.toString() ?? '0',
      totalAmount: json['totalAmount']?.toString() ?? '0',
      minAmount: json['minAmount']?.toString() ?? '0',
      maxAmount: json['maxAmount']?.toString() ?? '0',
      // 收款信息
      paymentMethod: _parsePaymentMethod(json['paymentMethod']),
      paymentAccount: json['paymentAccount'],
      paymentQrCode: json['paymentQrCode'],
      paymentRealName: json['paymentRealName'],
      // 超时配置
      paymentTimeoutMinutes: json['paymentTimeoutMinutes'] ?? 15,
      confirmTimeoutMinutes: json['confirmTimeoutMinutes'] ?? 60,
      paymentDeadline: json['paymentDeadline'] != null
          ? DateTime.parse(json['paymentDeadline'])
          : null,
      confirmDeadline: json['confirmDeadline'] != null
          ? DateTime.parse(json['confirmDeadline'])
          : null,
      // 付款水单
      paymentProofUrl: json['paymentProofUrl'],
      // Bot 自动购买相关
      botPurchased: json['botPurchased'] ?? false,
      sellerKavaAddress: json['sellerKavaAddress'],
      paymentTxHash: json['paymentTxHash'],
      // 其他
      status: _parseOrderStatus(json['status']),
      remark: json['remark'],
      createdAt: json['createdAt'] != null
          ? DateTime.parse(json['createdAt'])
          : DateTime.now(),
      matchedAt: json['matchedAt'] != null
          ? DateTime.parse(json['matchedAt'])
          : null,
      paidAt: json['paidAt'] != null
          ? DateTime.parse(json['paidAt'])
          : null,
      completedAt: json['completedAt'] != null
          ? DateTime.parse(json['completedAt'])
          : null,
      expiredAt: json['expiredAt'] != null
          ? DateTime.parse(json['expiredAt'])
          : null,
    );
  }

  static C2cOrderType _parseOrderType(String? type) {
    switch (type?.toUpperCase()) {
      case 'BUY':
        return C2cOrderType.buy;
      case 'SELL':
        return C2cOrderType.sell;
      default:
        return C2cOrderType.buy;
    }
  }

  static C2cPaymentMethod? _parsePaymentMethod(String? method) {
    if (method == null) return null;
    // 支持逗号分隔的多种支付方式（如 "GREEN_POINTS,ALIPAY"），取第一个作为主要方式
    final primary = method.split(',').first.trim().toUpperCase();
    switch (primary) {
      case 'GREEN_POINTS':
        return C2cPaymentMethod.greenPoints;
      case 'ALIPAY':
        return C2cPaymentMethod.alipay;
      case 'WECHAT':
        return C2cPaymentMethod.wechat;
      case 'BANK':
        return C2cPaymentMethod.bank;
      default:
        return null;
    }
  }

  static C2cOrderStatus _parseOrderStatus(String? status) {
    switch (status?.toUpperCase()) {
      case 'PENDING':
        return C2cOrderStatus.pending;
      case 'MATCHED':
        return C2cOrderStatus.matched;
      case 'PAID':
        return C2cOrderStatus.paid;
      case 'COMPLETED':
        return C2cOrderStatus.completed;
      case 'CANCELLED':
        return C2cOrderStatus.cancelled;
      case 'EXPIRED':
        return C2cOrderStatus.expired;
      default:
        return C2cOrderStatus.pending;
    }
  }

  bool get isBuy => type == C2cOrderType.buy;
  bool get isSell => type == C2cOrderType.sell;
  bool get isPending => status == C2cOrderStatus.pending;
  bool get isMatched => status == C2cOrderStatus.matched;
  bool get isPaid => status == C2cOrderStatus.paid;
  bool get isCompleted => status == C2cOrderStatus.completed;
  bool get isCancelled => status == C2cOrderStatus.cancelled;
  bool get isBotPurchased => botPurchased && paymentTxHash != null;

  String get typeText => isBuy ? '买入' : '卖出';

  /// 收款方式文本
  String get paymentMethodText {
    switch (paymentMethod) {
      case C2cPaymentMethod.greenPoints:
        return '绿积分';
      case C2cPaymentMethod.alipay:
        return '支付宝';
      case C2cPaymentMethod.wechat:
        return '微信';
      case C2cPaymentMethod.bank:
        return '银行卡';
      default:
        return '未设置';
    }
  }

  /// 是否有收款信息
  bool get hasPaymentInfo => paymentMethod != null && paymentAccount != null;

  /// 获取付款剩余时间（秒）
  int? get paymentRemainingSeconds {
    if (paymentDeadline == null) return null;
    final remaining = paymentDeadline!.difference(DateTime.now()).inSeconds;
    return remaining > 0 ? remaining : 0;
  }

  /// 获取确认收款剩余时间（秒）
  int? get confirmRemainingSeconds {
    if (confirmDeadline == null) return null;
    final remaining = confirmDeadline!.difference(DateTime.now()).inSeconds;
    return remaining > 0 ? remaining : 0;
  }

  String get statusText {
    switch (status) {
      case C2cOrderStatus.pending:
        return '待接单';
      case C2cOrderStatus.matched:
        return '待付款';
      case C2cOrderStatus.paid:
        return '待确认';
      case C2cOrderStatus.completed:
        return '已完成';
      case C2cOrderStatus.cancelled:
        return '已取消';
      case C2cOrderStatus.expired:
        return '已过期';
    }
  }
}

/// C2C订单列表分页模型
class C2cOrdersPageModel {
  final List<C2cOrderModel> data;
  final int total;
  final int page;
  final int pageSize;

  C2cOrdersPageModel({
    required this.data,
    required this.total,
    required this.page,
    required this.pageSize,
  });

  factory C2cOrdersPageModel.fromJson(Map<String, dynamic> json) {
    final List<dynamic> dataList = json['data'] ?? [];
    return C2cOrdersPageModel(
      data: dataList.map((e) => C2cOrderModel.fromJson(e)).toList(),
      total: json['total'] ?? 0,
      page: json['page'] ?? 1,
      pageSize: json['pageSize'] ?? 10,
    );
  }
}
