import 'package:decimal/decimal.dart';

/// 账户信息
class AccountInfo {
  final String name;
  final Decimal balance;
  final Decimal frozenBalance;
  final Decimal frozenMargin;
  final Decimal currentCapital;

  const AccountInfo({
    required this.name,
    required this.balance,
    required this.frozenBalance,
    required this.frozenMargin,
    required this.currentCapital,
  });

  factory AccountInfo.fromJson(Map<String, dynamic> json) {
    return AccountInfo(
      name: json['name']?.toString() ?? '',
      balance: Decimal.tryParse(json['balance']?.toString() ?? '0') ?? Decimal.zero,
      frozenBalance: Decimal.tryParse(json['frozenBalance']?.toString() ?? '0') ?? Decimal.zero,
      frozenMargin: Decimal.tryParse(json['frozenMargin']?.toString() ?? '0') ?? Decimal.zero,
      currentCapital: Decimal.tryParse(json['currentCapital']?.toString() ?? '0') ?? Decimal.zero,
    );
  }
}

/// 合约钱包数据 - GET swap/wallet-new/get
class TodayPnl {
  /// 今日盈亏金额
  final Decimal revenue;

  /// 今日盈亏率(%)，后端分母为 0 或 null 时返回 null
  final Decimal? revenueRate;

  /// 总资产（cashBalance）
  final Decimal cashBalance;

  /// 合约账户当前权益（currentCapital）
  final Decimal currentCapital;

  /// 各账户信息列表
  final List<AccountInfo> accountInfoList;

  TodayPnl({
    Decimal? revenue,
    this.revenueRate,
    Decimal? cashBalance,
    Decimal? currentCapital,
    List<AccountInfo>? accountInfoList,
  })  : revenue = revenue ?? Decimal.zero,
        cashBalance = cashBalance ?? Decimal.zero,
        currentCapital = currentCapital ?? Decimal.zero,
        accountInfoList = accountInfoList ?? [];

  /// 涨跌趋势：正=true, 负=false, 零=null
  bool? get isUpTrend {
    if (revenue == Decimal.zero) return null;
    return revenue > Decimal.zero;
  }

  factory TodayPnl.fromJson(Map<String, dynamic> json) {
    final accountList = json['accountInfoList'] as List?;
    final accountInfoList = accountList
        ?.map((e) => AccountInfo.fromJson(e as Map<String, dynamic>))
        .toList() ?? [];

    return TodayPnl(
      revenue: Decimal.tryParse(json['currentTodayRevenue']?.toString() ?? ''),
      revenueRate: Decimal.tryParse(json['todayRevenueRate']?.toString() ?? ''),
      cashBalance: Decimal.tryParse(json['cashBalance']?.toString() ?? ''),
      currentCapital: Decimal.tryParse(json['currentCapital']?.toString() ?? ''),
      accountInfoList: accountInfoList,
    );
  }
}
