import 'package:flutter/foundation.dart';
import '../network/api_client.dart';

/// 余额信息
class BalanceInfo {
  final double available;
  final double frozen;

  BalanceInfo({
    required this.available,
    required this.frozen,
  });

  factory BalanceInfo.fromJson(Map<String, dynamic> json) {
    return BalanceInfo(
      available: (json['available'] ?? 0).toDouble(),
      frozen: (json['frozen'] ?? 0).toDouble(),
    );
  }
}

/// 各币种余额
class BalancesInfo {
  final BalanceInfo usdt;
  final BalanceInfo dst;
  final BalanceInfo bnb;
  final BalanceInfo og;
  final BalanceInfo rwad;

  BalancesInfo({
    required this.usdt,
    required this.dst,
    required this.bnb,
    required this.og,
    required this.rwad,
  });

  factory BalancesInfo.fromJson(Map<String, dynamic> json) {
    return BalancesInfo(
      usdt: BalanceInfo.fromJson(json['usdt'] ?? {}),
      dst: BalanceInfo.fromJson(json['dst'] ?? {}),
      bnb: BalanceInfo.fromJson(json['bnb'] ?? {}),
      og: BalanceInfo.fromJson(json['og'] ?? {}),
      rwad: BalanceInfo.fromJson(json['rwad'] ?? {}),
    );
  }
}

/// 奖励信息
class RewardsInfo {
  final double pendingUsdt;
  final double pendingHashpower;
  final DateTime? pendingExpireAt;
  final double settleableUsdt;
  final double settleableHashpower;
  final double settledTotalUsdt;
  final double settledTotalHashpower;
  final double expiredTotalUsdt;
  final double expiredTotalHashpower;

  RewardsInfo({
    required this.pendingUsdt,
    required this.pendingHashpower,
    this.pendingExpireAt,
    required this.settleableUsdt,
    required this.settleableHashpower,
    required this.settledTotalUsdt,
    required this.settledTotalHashpower,
    required this.expiredTotalUsdt,
    required this.expiredTotalHashpower,
  });

  factory RewardsInfo.fromJson(Map<String, dynamic> json) {
    return RewardsInfo(
      pendingUsdt: (json['pendingUsdt'] ?? 0).toDouble(),
      pendingHashpower: (json['pendingHashpower'] ?? 0).toDouble(),
      pendingExpireAt: json['pendingExpireAt'] != null
          ? DateTime.tryParse(json['pendingExpireAt'])
          : null,
      settleableUsdt: (json['settleableUsdt'] ?? 0).toDouble(),
      settleableHashpower: (json['settleableHashpower'] ?? 0).toDouble(),
      settledTotalUsdt: (json['settledTotalUsdt'] ?? 0).toDouble(),
      settledTotalHashpower: (json['settledTotalHashpower'] ?? 0).toDouble(),
      expiredTotalUsdt: (json['expiredTotalUsdt'] ?? 0).toDouble(),
      expiredTotalHashpower: (json['expiredTotalHashpower'] ?? 0).toDouble(),
    );
  }

  /// 计算待领取剩余时间（秒）
  /// [2026-03-01] 当 pendingUsdt=0 时（已全部结算），倒计时无意义，返回 0
  int get pendingRemainingSeconds {
    if (pendingExpireAt == null) return 0;
    if (pendingUsdt <= 0) return 0;
    final remaining = pendingExpireAt!.difference(DateTime.now()).inSeconds;
    return remaining > 0 ? remaining : 0;
  }
}

/// 钱包响应
class WalletResponse {
  final String walletId;
  final String userId;
  final BalancesInfo balances;
  final double hashpower;
  final RewardsInfo rewards;
  final String status;

  WalletResponse({
    required this.walletId,
    required this.userId,
    required this.balances,
    required this.hashpower,
    required this.rewards,
    required this.status,
  });

  factory WalletResponse.fromJson(Map<String, dynamic> json) {
    return WalletResponse(
      walletId: json['walletId'] ?? '',
      userId: json['userId'] ?? '',
      balances: BalancesInfo.fromJson(json['balances'] ?? {}),
      hashpower: (json['hashpower'] ?? 0).toDouble(),
      rewards: RewardsInfo.fromJson(json['rewards'] ?? {}),
      status: json['status'] ?? '',
    );
  }
}

/// 领取奖励响应
class ClaimRewardsResponse {
  final String message;

  ClaimRewardsResponse({required this.message});

  factory ClaimRewardsResponse.fromJson(Map<String, dynamic> json) {
    return ClaimRewardsResponse(
      message: json['message'] ?? '',
    );
  }
}

/// [2026-03-01] 预种结算结果
class SettlePrePlantingResult {
  final bool success;
  final double settledAmount;
  final double balanceAfter;
  final String? error;

  SettlePrePlantingResult({
    required this.success,
    required this.settledAmount,
    required this.balanceAfter,
    this.error,
  });

  factory SettlePrePlantingResult.fromJson(Map<String, dynamic> json) {
    return SettlePrePlantingResult(
      success: json['success'] ?? false,
      settledAmount: (json['settledAmount'] ?? 0).toDouble(),
      balanceAfter: (json['balanceAfter'] ?? 0).toDouble(),
      error: json['error'],
    );
  }
}

/// [2026-03-01] wallet-service 的待领取奖励条目
/// 对应 GET /wallet/pending-rewards 返回的 pending_rewards 表记录
class WalletPendingRewardItem {
  final String id;
  final double usdtAmount;
  final double hashpowerAmount;
  final String sourceOrderId;
  final String allocationType;
  final DateTime expireAt;
  final String status;
  final DateTime createdAt;

  WalletPendingRewardItem({
    required this.id,
    required this.usdtAmount,
    required this.hashpowerAmount,
    required this.sourceOrderId,
    required this.allocationType,
    required this.expireAt,
    required this.status,
    required this.createdAt,
  });

  factory WalletPendingRewardItem.fromJson(Map<String, dynamic> json) {
    return WalletPendingRewardItem(
      id: json['id']?.toString() ?? '',
      usdtAmount: (json['usdtAmount'] ?? 0).toDouble(),
      hashpowerAmount: (json['hashpowerAmount'] ?? 0).toDouble(),
      sourceOrderId: json['sourceOrderId'] ?? '',
      allocationType: json['allocationType'] ?? '',
      expireAt: DateTime.tryParse(json['expireAt'] ?? '') ?? DateTime.now(),
      status: json['status'] ?? '',
      createdAt: DateTime.tryParse(json['createdAt'] ?? '') ?? DateTime.now(),
    );
  }

  /// 是否为预种奖励（通过订单号前缀 PPL 判断）
  bool get isPrePlanting => sourceOrderId.startsWith('PPL');
}

/// 手续费类型
enum FeeType {
  fixed,     // 固定金额
  percentage, // 百分比
}

/// 手续费配置
class FeeConfig {
  final FeeType feeType;
  final double feeValue;
  final double minFee;
  final double maxFee;
  final String? memo;

  FeeConfig({
    required this.feeType,
    required this.feeValue,
    required this.minFee,
    required this.maxFee,
    this.memo,
  });

  factory FeeConfig.fromJson(Map<String, dynamic> json) {
    return FeeConfig(
      feeType: json['feeType'] == 'FIXED' ? FeeType.fixed : FeeType.percentage,
      feeValue: (json['feeValue'] ?? 2).toDouble(),
      minFee: (json['minFee'] ?? 0).toDouble(),
      maxFee: (json['maxFee'] ?? 0).toDouble(),
      memo: json['memo'],
    );
  }

  /// 计算手续费
  double calculateFee(double amount) {
    if (feeType == FeeType.fixed) {
      return feeValue;
    } else {
      double fee = amount * feeValue;
      if (minFee > 0 && fee < minFee) fee = minFee;
      if (maxFee > 0 && fee > maxFee) fee = maxFee;
      return fee;
    }
  }

  /// 计算给定余额下的最大可转金额
  /// 因为手续费由发送方承担，所以 总花费 = 转账金额 + 手续费
  /// 返回能够使 转账金额 + 手续费 <= balance 的最大转账金额
  double calculateMaxAmount(double balance) {
    if (balance <= 0) return 0;

    if (feeType == FeeType.fixed) {
      // 固定费率: maxAmount = balance - fixedFee
      final maxAmount = balance - feeValue;
      return maxAmount > 0 ? maxAmount : 0;
    } else {
      // 百分比费率: 总花费 = amount * (1 + rate)
      // 所以 maxAmount = balance / (1 + rate)
      final maxAmount = balance / (1 + feeValue);

      // 检查最小/最大手续费限制
      final fee = calculateFee(maxAmount);
      final actualTotal = maxAmount + fee;

      // 如果由于 minFee 导致超出余额，需要重新计算
      if (actualTotal > balance && minFee > 0) {
        // 使用 minFee 计算: maxAmount = balance - minFee
        final adjustedMax = balance - minFee;
        return adjustedMax > 0 ? adjustedMax : 0;
      }

      return maxAmount > 0 ? maxAmount : 0;
    }
  }

  /// 获取费率描述
  String get description {
    if (feeType == FeeType.fixed) {
      return '固定 ${feeValue.toStringAsFixed(0)} 绿积分/笔';
    } else {
      return '${(feeValue * 100).toStringAsFixed(2)}%';
    }
  }
}

/// 提现记录项 (从 GET /wallet/withdrawals 获取)
class WithdrawalHistoryItem {
  final String orderNo;
  final double amount;
  final double fee;
  final double netAmount;
  final String chainType;
  final String toAddress;
  final String? txHash;
  final String status;
  final DateTime createdAt;

  WithdrawalHistoryItem({
    required this.orderNo,
    required this.amount,
    required this.fee,
    required this.netAmount,
    required this.chainType,
    required this.toAddress,
    this.txHash,
    required this.status,
    required this.createdAt,
  });

  factory WithdrawalHistoryItem.fromJson(Map<String, dynamic> json) {
    return WithdrawalHistoryItem(
      orderNo: json['orderNo'] ?? '',
      amount: (json['amount'] ?? 0).toDouble(),
      fee: (json['fee'] ?? 0).toDouble(),
      netAmount: (json['netAmount'] ?? 0).toDouble(),
      chainType: json['chainType'] ?? '',
      toAddress: json['toAddress'] ?? '',
      txHash: json['txHash'],
      status: json['status'] ?? '',
      createdAt: DateTime.tryParse(json['createdAt'] ?? '') ?? DateTime.now(),
    );
  }

  /// 获取状态的中文名称
  String get statusName {
    switch (status) {
      case 'PENDING':
        return '待处理';
      case 'FROZEN':
        return '已冻结';
      case 'CONFIRMED':
        return '已确认';
      case 'COMPLETED':
        return '已完成';
      case 'FAILED':
        return '失败';
      case 'CANCELLED':
        return '已取消';
      default:
        return status;
    }
  }

  /// 获取链类型的中文名称
  String get chainTypeName {
    switch (chainType) {
      case 'KAVA':
        return 'KAVA';
      case 'BSC':
        return 'BSC';
      case 'INTERNAL':
        return '内部划转';
      default:
        return chainType;
    }
  }

  /// 获取截断的地址显示
  String get shortAddress {
    if (toAddress.length <= 16) return toAddress;
    return '${toAddress.substring(0, 8)}...${toAddress.substring(toAddress.length - 6)}';
  }
}

/// 钱包服务
///
/// 提供钱包余额查询、奖励领取等功能
/// 调用 wallet-service 的 API
class WalletService {
  final ApiClient _apiClient;

  WalletService({required ApiClient apiClient}) : _apiClient = apiClient;

  /// 获取我的钱包信息
  ///
  /// 调用 GET /wallet/my-wallet (wallet-service)
  Future<WalletResponse> getMyWallet() async {
    try {
      debugPrint('[WalletService] ========== 获取钱包信息 ==========');
      debugPrint('[WalletService] 请求: GET /wallet/my-wallet');

      final response = await _apiClient.get('/wallet/my-wallet');

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');
      debugPrint('[WalletService] 响应数据类型: ${response.data.runtimeType}');

      if (response.statusCode == 200) {
        final responseData = response.data as Map<String, dynamic>;
        debugPrint('[WalletService] 原始响应数据: $responseData');

        // API 返回格式: { success: true, data: {...}, timestamp: "..." }
        // 需要解包内层的 data 字段
        final data = responseData['data'] as Map<String, dynamic>? ?? responseData;
        debugPrint('[WalletService] 解包后数据: $data');

        // 解析并打印详细信息
        final wallet = WalletResponse.fromJson(data);
        debugPrint('[WalletService] -------- 解析结果 --------');
        debugPrint('[WalletService] walletId: ${wallet.walletId}');
        debugPrint('[WalletService] userId: ${wallet.userId}');
        debugPrint('[WalletService] status: ${wallet.status}');
        debugPrint('[WalletService] hashpower: ${wallet.hashpower}');
        debugPrint('[WalletService] -------- 余额信息 --------');
        debugPrint('[WalletService] USDT: available=${wallet.balances.usdt.available}, frozen=${wallet.balances.usdt.frozen}');
        debugPrint('[WalletService] DST: available=${wallet.balances.dst.available}, frozen=${wallet.balances.dst.frozen}');
        debugPrint('[WalletService] -------- 奖励信息 --------');
        debugPrint('[WalletService] pendingUsdt: ${wallet.rewards.pendingUsdt}');
        debugPrint('[WalletService] pendingHashpower: ${wallet.rewards.pendingHashpower}');
        debugPrint('[WalletService] pendingExpireAt: ${wallet.rewards.pendingExpireAt}');
        debugPrint('[WalletService] pendingRemainingSeconds: ${wallet.rewards.pendingRemainingSeconds}');
        debugPrint('[WalletService] settleableUsdt: ${wallet.rewards.settleableUsdt}');
        debugPrint('[WalletService] settleableHashpower: ${wallet.rewards.settleableHashpower}');
        debugPrint('[WalletService] settledTotalUsdt: ${wallet.rewards.settledTotalUsdt}');
        debugPrint('[WalletService] settledTotalHashpower: ${wallet.rewards.settledTotalHashpower}');
        debugPrint('[WalletService] expiredTotalUsdt: ${wallet.rewards.expiredTotalUsdt}');
        debugPrint('[WalletService] expiredTotalHashpower: ${wallet.rewards.expiredTotalHashpower}');
        debugPrint('[WalletService] ================================');

        return wallet;
      }

      debugPrint('[WalletService] 请求失败，状态码: ${response.statusCode}');
      debugPrint('[WalletService] 响应内容: ${response.data}');
      throw Exception('获取钱包信息失败: ${response.statusCode}');
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 获取钱包信息异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  /// 领取奖励
  ///
  /// 调用 POST /wallet/claim-rewards (wallet-service)
  /// 将待领取的奖励转为可结算状态
  Future<ClaimRewardsResponse> claimRewards() async {
    try {
      debugPrint('[WalletService] ========== 领取奖励 ==========');
      debugPrint('[WalletService] 请求: POST /wallet/claim-rewards');

      final response = await _apiClient.post('/wallet/claim-rewards');

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');
      debugPrint('[WalletService] 响应数据: ${response.data}');

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        final result = ClaimRewardsResponse.fromJson(data);
        debugPrint('[WalletService] 领取成功: ${result.message}');
        debugPrint('[WalletService] ================================');
        return result;
      }

      debugPrint('[WalletService] 领取失败，状态码: ${response.statusCode}');
      throw Exception('领取奖励失败: ${response.statusCode}');
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 领取奖励异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  /// 结算收益
  ///
  /// 调用 POST /wallet/settle (wallet-service)
  /// 将可结算的USDT兑换为指定币种
  Future<String> settleRewards({
    required double usdtAmount,
    required String settleCurrency,
  }) async {
    try {
      debugPrint('[WalletService] ========== 结算收益 ==========');
      debugPrint('[WalletService] 请求: POST /wallet/settle');
      debugPrint('[WalletService] 参数: usdtAmount=$usdtAmount, settleCurrency=$settleCurrency');

      final response = await _apiClient.post(
        '/wallet/settle',
        data: {
          'usdtAmount': usdtAmount,
          'settleCurrency': settleCurrency,
        },
      );

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');
      debugPrint('[WalletService] 响应数据: ${response.data}');

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        final orderId = data['settlementOrderId'] ?? '';
        debugPrint('[WalletService] 结算成功: orderId=$orderId');
        debugPrint('[WalletService] ================================');
        return orderId;
      }

      debugPrint('[WalletService] 结算失败，状态码: ${response.statusCode}');
      throw Exception('结算失败: ${response.statusCode}');
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 结算收益异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  /// [2026-03-01] 获取 wallet-service 中的待领取奖励列表
  ///
  /// 调用 GET /wallet/pending-rewards (wallet-service)
  /// 返回 pending_rewards 表中 status=PENDING 的记录，包含正常认种和预种两种来源。
  /// 用于在 profile 页面识别预种的待领取条目（sourceOrderId 以 PPL 开头），
  /// 合并到 reward-service 的待领取列表中统一展示。
  Future<List<WalletPendingRewardItem>> getWalletPendingRewards() async {
    try {
      debugPrint('[WalletService] ========== 获取待领取奖励列表 ==========');
      debugPrint('[WalletService] 请求: GET /wallet/pending-rewards');

      final response = await _apiClient.get('/wallet/pending-rewards');

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');

      if (response.statusCode == 200) {
        final responseData = response.data;

        List<dynamic> dataList;
        if (responseData is List) {
          dataList = responseData;
        } else if (responseData is Map<String, dynamic>) {
          dataList = responseData['data'] as List<dynamic>? ?? [];
        } else {
          dataList = [];
        }

        debugPrint('[WalletService] 解析到 ${dataList.length} 条待领取奖励');

        final items = dataList
            .map((item) => WalletPendingRewardItem.fromJson(item as Map<String, dynamic>))
            .toList();

        debugPrint('[WalletService] ================================');
        return items;
      }

      throw Exception('获取待领取奖励列表失败: ${response.statusCode}');
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 获取待领取奖励列表异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  /// [2026-03-01] 结算预种可结算收益
  ///
  /// 调用 POST /wallet/settle-pre-planting (wallet-service)
  /// 将 wallet 中剩余的 settleable_usdt（预种部分）转入钱包余额。
  /// 在 reward-service 的 settleToBalance 之后串行调用，
  /// 如果 settleable_usdt 已被全部结算则直接返回 success（幂等）。
  Future<SettlePrePlantingResult> settlePrePlanting() async {
    try {
      debugPrint('[WalletService] ========== 结算预种可结算收益 ==========');
      debugPrint('[WalletService] 请求: POST /wallet/settle-pre-planting');

      final response = await _apiClient.post('/wallet/settle-pre-planting');

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');
      debugPrint('[WalletService] 响应数据: ${response.data}');

      if (response.statusCode == 200 || response.statusCode == 201) {
        final responseData = response.data as Map<String, dynamic>;
        final data = responseData['data'] as Map<String, dynamic>? ?? responseData;
        final result = SettlePrePlantingResult.fromJson(data);
        debugPrint('[WalletService] 预种结算结果: success=${result.success}, settledAmount=${result.settledAmount}');
        debugPrint('[WalletService] ================================');
        return result;
      }

      debugPrint('[WalletService] 预种结算失败，状态码: ${response.statusCode}');
      return SettlePrePlantingResult(success: false, settledAmount: 0, balanceAfter: 0, error: '请求失败: ${response.statusCode}');
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 预种结算异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      return SettlePrePlantingResult(success: false, settledAmount: 0, balanceAfter: 0, error: e.toString());
    }
  }

  /// 发送提取验证短信
  ///
  /// 调用 POST /wallet/withdraw/send-sms (wallet-service)
  Future<void> sendWithdrawSmsCode() async {
    try {
      debugPrint('[WalletService] ========== 发送提取验证短信 ==========');
      debugPrint('[WalletService] 请求: POST /wallet/withdraw/send-sms');

      final response = await _apiClient.post('/wallet/withdraw/send-sms');

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');
      debugPrint('[WalletService] 响应数据: ${response.data}');

      if (response.statusCode == 200 || response.statusCode == 201) {
        debugPrint('[WalletService] 发送成功');
        debugPrint('[WalletService] ================================');
        return;
      }

      debugPrint('[WalletService] 发送失败，状态码: ${response.statusCode}');

      String errorMessage = '发送验证码失败';
      if (response.data is Map<String, dynamic>) {
        final errorData = response.data as Map<String, dynamic>;
        errorMessage = errorData['message'] ?? errorData['error'] ?? errorMessage;
      }
      throw Exception(errorMessage);
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 发送提取验证短信异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  /// 提取积分
  ///
  /// 调用 POST /wallet/withdraw (wallet-service)
  /// 将积分提取到指定地址
  Future<WithdrawResponse> withdrawUsdt({
    required double amount,
    required String toAddress,
    required String chainType,
    required String smsCode,
    required String password,
  }) async {
    try {
      debugPrint('[WalletService] ========== 提取积分 ==========');
      debugPrint('[WalletService] 请求: POST /wallet/withdraw');
      debugPrint('[WalletService] 参数: amount=$amount, toAddress=$toAddress, chainType=$chainType');

      final Map<String, dynamic> data = {
        'amount': amount,
        'toAddress': toAddress,
        'chainType': chainType,
        'smsCode': smsCode,
        'password': password,
      };

      final response = await _apiClient.post(
        '/wallet/withdraw',
        data: data,
      );

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');
      debugPrint('[WalletService] 响应数据: ${response.data}');

      if (response.statusCode == 200 || response.statusCode == 201) {
        final responseData = response.data as Map<String, dynamic>;
        // 处理可能的嵌套 data 结构
        final data = responseData['data'] as Map<String, dynamic>? ?? responseData;
        final result = WithdrawResponse.fromJson(data);
        debugPrint('[WalletService] 提取成功: orderNo=${result.orderNo}');
        debugPrint('[WalletService] ================================');
        return result;
      }

      debugPrint('[WalletService] 提取失败，状态码: ${response.statusCode}');

      // 尝试解析错误信息
      String errorMessage = '提取失败: ${response.statusCode}';
      if (response.data is Map<String, dynamic>) {
        final errorData = response.data as Map<String, dynamic>;
        errorMessage = errorData['message'] ?? errorData['error'] ?? errorMessage;
      }
      throw Exception(errorMessage);
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 提取积分异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  /// 获取提取记录列表
  ///
  /// 调用 GET /wallet/withdrawals (wallet-service)
  Future<List<WithdrawRecord>> getWithdrawals() async {
    try {
      debugPrint('[WalletService] ========== 获取提取记录 ==========');
      debugPrint('[WalletService] 请求: GET /wallet/withdrawals');

      final response = await _apiClient.get('/wallet/withdrawals');

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');

      if (response.statusCode == 200) {
        final responseData = response.data as Map<String, dynamic>;
        final dataList = responseData['data'] as List<dynamic>? ??
                         (response.data is List ? response.data as List<dynamic> : []);

        final records = dataList
            .map((item) => WithdrawRecord.fromJson(item as Map<String, dynamic>))
            .toList();

        debugPrint('[WalletService] 获取成功: ${records.length} 条记录');
        debugPrint('[WalletService] ================================');
        return records;
      }

      debugPrint('[WalletService] 获取失败，状态码: ${response.statusCode}');
      throw Exception('获取提取记录失败: ${response.statusCode}');
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 获取提取记录异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  // =============== 账本流水相关 API ===============

  /// 获取账本流水列表
  ///
  /// 调用 GET /wallet/ledger/my-ledger (wallet-service)
  Future<PaginatedLedger> getLedger({
    int page = 1,
    int pageSize = 20,
    String? entryType,
    String? assetType,
    DateTime? startDate,
    DateTime? endDate,
  }) async {
    try {
      debugPrint('[WalletService] ========== 获取账本流水 ==========');
      debugPrint('[WalletService] 请求: GET /wallet/ledger/my-ledger');
      debugPrint('[WalletService] 参数: page=$page, pageSize=$pageSize, entryType=$entryType');

      final queryParams = <String, String>{
        'page': page.toString(),
        'pageSize': pageSize.toString(),
      };
      if (entryType != null) queryParams['entryType'] = entryType;
      if (assetType != null) queryParams['assetType'] = assetType;
      if (startDate != null) queryParams['startDate'] = startDate.toIso8601String();
      if (endDate != null) queryParams['endDate'] = endDate.toIso8601String();

      final queryString = queryParams.entries.map((e) => '${e.key}=${e.value}').join('&');
      final response = await _apiClient.get('/wallet/ledger/my-ledger?$queryString');

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');

      if (response.statusCode == 200) {
        final responseData = response.data as Map<String, dynamic>;
        final data = responseData['data'] as Map<String, dynamic>? ?? responseData;

        // 调试：打印原始流水数据
        debugPrint('[WalletService] ======== 原始流水数据 ========');
        final dataList = data['data'] as List<dynamic>? ?? [];
        for (int i = 0; i < dataList.length && i < 5; i++) {
          final entry = dataList[i] as Map<String, dynamic>;
          debugPrint('[WalletService] 流水[$i]: entryType=${entry['entryType']}, allocationType=${entry['allocationType']}, memo=${entry['memo']}');
        }
        debugPrint('[WalletService] ================================');

        final result = PaginatedLedger.fromJson(data);
        debugPrint('[WalletService] 获取成功: ${result.data.length} 条流水, 共 ${result.total} 条');

        // 调试：打印解析后的流水数据
        debugPrint('[WalletService] ======== 解析后流水数据 ========');
        for (int i = 0; i < result.data.length && i < 5; i++) {
          final entry = result.data[i];
          debugPrint('[WalletService] 流水[$i]: entryType=${entry.entryType}, allocationType=${entry.allocationType}, displayName=${entry.displayName}');
        }
        debugPrint('[WalletService] ================================');
        return result;
      }

      throw Exception('获取账本流水失败: ${response.statusCode}');
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 获取账本流水异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  /// 获取流水统计
  ///
  /// 调用 GET /wallet/ledger/statistics (wallet-service)
  Future<LedgerStatistics> getLedgerStatistics() async {
    try {
      debugPrint('[WalletService] ========== 获取流水统计 ==========');
      debugPrint('[WalletService] 请求: GET /wallet/ledger/statistics');

      final response = await _apiClient.get('/wallet/ledger/statistics');

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');

      if (response.statusCode == 200) {
        final responseData = response.data as Map<String, dynamic>;
        final data = responseData['data'] as Map<String, dynamic>? ?? responseData;
        final result = LedgerStatistics.fromJson(data);
        debugPrint('[WalletService] 获取成功: 总收入=${result.totalIncome}, 总支出=${result.totalExpense}');
        debugPrint('[WalletService] ================================');
        return result;
      }

      throw Exception('获取流水统计失败: ${response.statusCode}');
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 获取流水统计异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  /// 获取流水趋势
  ///
  /// 调用 GET /wallet/ledger/trend (wallet-service)
  Future<LedgerTrend> getLedgerTrend({int days = 30}) async {
    try {
      debugPrint('[WalletService] ========== 获取流水趋势 ==========');
      debugPrint('[WalletService] 请求: GET /wallet/ledger/trend?days=$days');

      final response = await _apiClient.get('/wallet/ledger/trend?days=$days');

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');

      if (response.statusCode == 200) {
        final responseData = response.data as Map<String, dynamic>;
        final data = responseData['data'] as Map<String, dynamic>? ?? responseData;
        final result = LedgerTrend.fromJson(data);
        debugPrint('[WalletService] 获取成功: ${result.dailyTrend.length} 天数据');
        debugPrint('[WalletService] ================================');
        return result;
      }

      throw Exception('获取流水趋势失败: ${response.statusCode}');
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 获取流水趋势异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  // =============== 手续费配置相关 API ===============

  // =============== 法币提现相关 API ===============

  /// 发送法币提现验证短信
  ///
  /// 调用 POST /wallet/fiat-withdrawal/send-sms (wallet-service)
  Future<void> sendFiatWithdrawalSmsCode() async {
    try {
      debugPrint('[WalletService] ========== 发送法币提现验证短信 ==========');
      debugPrint('[WalletService] 请求: POST /wallet/fiat-withdrawal/send-sms');

      final response = await _apiClient.post('/wallet/fiat-withdrawal/send-sms');

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');
      debugPrint('[WalletService] 响应数据: ${response.data}');

      if (response.statusCode == 200 || response.statusCode == 201) {
        debugPrint('[WalletService] 发送成功');
        debugPrint('[WalletService] ================================');
        return;
      }

      debugPrint('[WalletService] 发送失败，状态码: ${response.statusCode}');

      String errorMessage = '发送验证码失败';
      if (response.data is Map<String, dynamic>) {
        final errorData = response.data as Map<String, dynamic>;
        errorMessage = errorData['message'] ?? errorData['error'] ?? errorMessage;
      }
      throw Exception(errorMessage);
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 发送法币提现验证短信异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  /// 法币提现申请
  ///
  /// 调用 POST /wallet/fiat-withdrawal (wallet-service)
  /// 将绿积分提现到银行卡/支付宝/微信，1:1 兑换 CNY
  Future<FiatWithdrawalResponse> withdrawFiat({
    required double amount,
    required PaymentMethod paymentMethod,
    // 银行卡
    String? bankName,
    String? bankCardNo,
    String? cardHolderName,
    // 支付宝
    String? alipayAccount,
    String? alipayRealName,
    // 微信
    String? wechatAccount,
    String? wechatRealName,
    // 验证
    required String smsCode,
    required String password,
  }) async {
    try {
      debugPrint('[WalletService] ========== 法币提现申请 ==========');
      debugPrint('[WalletService] 请求: POST /wallet/fiat-withdrawal');
      debugPrint('[WalletService] 参数: amount=$amount, paymentMethod=${paymentMethod.name}');

      final Map<String, dynamic> data = {
        'amount': amount,
        'paymentMethod': paymentMethod.name,
        'smsCode': smsCode,
        'password': password,
      };

      // 根据支付方式添加对应字段
      switch (paymentMethod) {
        case PaymentMethod.BANK_CARD:
          data['bankName'] = bankName;
          data['bankCardNo'] = bankCardNo;
          data['cardHolderName'] = cardHolderName;
          break;
        case PaymentMethod.ALIPAY:
          data['alipayAccount'] = alipayAccount;
          data['alipayRealName'] = alipayRealName;
          break;
        case PaymentMethod.WECHAT:
          data['wechatAccount'] = wechatAccount;
          data['wechatRealName'] = wechatRealName;
          break;
      }

      final response = await _apiClient.post(
        '/wallet/fiat-withdrawal',
        data: data,
      );

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');
      debugPrint('[WalletService] 响应数据: ${response.data}');

      if (response.statusCode == 200 || response.statusCode == 201) {
        final responseData = response.data as Map<String, dynamic>;
        // 处理可能的嵌套 data 结构
        final resultData = responseData['data'] as Map<String, dynamic>? ?? responseData;
        final result = FiatWithdrawalResponse.fromJson(resultData);
        debugPrint('[WalletService] 法币提现申请成功: orderNo=${result.orderNo}');
        debugPrint('[WalletService] ================================');
        return result;
      }

      debugPrint('[WalletService] 法币提现申请失败，状态码: ${response.statusCode}');

      // 尝试解析错误信息
      String errorMessage = '提现申请失败: ${response.statusCode}';
      if (response.data is Map<String, dynamic>) {
        final errorData = response.data as Map<String, dynamic>;
        errorMessage = errorData['message'] ?? errorData['error'] ?? errorMessage;
      }
      throw Exception(errorMessage);
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 法币提现申请异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  /// 获取法币提现记录列表
  ///
  /// 调用 GET /wallet/fiat-withdrawal (wallet-service)
  Future<List<FiatWithdrawalRecord>> getFiatWithdrawals() async {
    try {
      debugPrint('[WalletService] ========== 获取法币提现记录 ==========');
      debugPrint('[WalletService] 请求: GET /wallet/fiat-withdrawal');

      final response = await _apiClient.get('/wallet/fiat-withdrawal');

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');

      if (response.statusCode == 200) {
        final responseData = response.data as Map<String, dynamic>;
        final dataList = responseData['data'] as List<dynamic>? ??
                         (response.data is List ? response.data as List<dynamic> : []);

        final records = dataList
            .map((item) => FiatWithdrawalRecord.fromJson(item as Map<String, dynamic>))
            .toList();

        debugPrint('[WalletService] 获取成功: ${records.length} 条记录');
        debugPrint('[WalletService] ================================');
        return records;
      }

      debugPrint('[WalletService] 获取失败，状态码: ${response.statusCode}');
      throw Exception('获取法币提现记录失败: ${response.statusCode}');
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 获取法币提现记录异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  /// 获取提取手续费配置
  ///
  /// 调用 GET /wallet/fee-config (wallet-service)
  Future<FeeConfig> getFeeConfig() async {
    try {
      debugPrint('[WalletService] ========== 获取手续费配置 ==========');
      debugPrint('[WalletService] 请求: GET /wallet/fee-config');

      final response = await _apiClient.get('/wallet/fee-config');

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');

      if (response.statusCode == 200) {
        final responseData = response.data as Map<String, dynamic>;
        final data = responseData['data'] as Map<String, dynamic>? ?? responseData;
        final result = FeeConfig.fromJson(data);
        debugPrint('[WalletService] 获取成功: ${result.description}');
        debugPrint('[WalletService] ================================');
        return result;
      }

      // 如果请求失败，返回默认配置
      debugPrint('[WalletService] 获取失败，使用默认配置');
      return FeeConfig(
        feeType: FeeType.fixed,
        feeValue: 2,
        minFee: 0,
        maxFee: 0,
        memo: '默认配置',
      );
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 获取手续费配置异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      // 返回默认配置，不抛出异常
      return FeeConfig(
        feeType: FeeType.fixed,
        feeValue: 2,
        minFee: 0,
        maxFee: 0,
        memo: '默认配置 (请求失败)',
      );
    }
  }

  /// 执行特殊扣减
  ///
  /// 调用 POST /wallets/special-deduction/execute (wallet-service 内部 API)
  /// 此方法由待办操作页面调用，用户确认后执行扣减
  Future<SpecialDeductionResult> executeSpecialDeduction({
    required String accountSequence,
    required String pendingActionId,
    required double amount,
    required String reason,
  }) async {
    try {
      debugPrint('[WalletService] ========== 执行特殊扣减 ==========');
      debugPrint('[WalletService] accountSequence: $accountSequence');
      debugPrint('[WalletService] pendingActionId: $pendingActionId');
      debugPrint('[WalletService] amount: $amount');
      debugPrint('[WalletService] reason: $reason');

      final response = await _apiClient.post(
        '/wallets/special-deduction/execute',
        data: {
          'accountSequence': accountSequence,
          'pendingActionId': pendingActionId,
          'amount': amount,
          'reason': reason,
        },
      );

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');
      debugPrint('[WalletService] 响应数据: ${response.data}');

      if (response.statusCode == 200 || response.statusCode == 201) {
        final responseData = response.data as Map<String, dynamic>;
        final data = responseData['data'] as Map<String, dynamic>? ?? responseData;
        final result = SpecialDeductionResult.fromJson(data);
        debugPrint('[WalletService] 特殊扣减成功: orderNo=${result.orderNo}, newBalance=${result.newBalance}');
        debugPrint('[WalletService] ================================');
        return result;
      }

      throw Exception('特殊扣减失败: ${response.statusCode}');
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 特殊扣减异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  /// 查询未处理的结算收益记录
  ///
  /// 调用 GET /wallets/offline-settlement/unprocessed/:accountSequence
  /// 用于全额线下结算扣减模式
  Future<UnprocessedSettlementsResult> getUnprocessedSettlements({
    required String accountSequence,
  }) async {
    try {
      debugPrint('[WalletService] ========== 查询未处理结算记录 ==========');
      debugPrint('[WalletService] accountSequence: $accountSequence');

      final response = await _apiClient.get(
        '/wallets/offline-settlement/unprocessed/$accountSequence',
      );

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');
      debugPrint('[WalletService] 响应数据: ${response.data}');

      if (response.statusCode == 200) {
        final responseData = response.data as Map<String, dynamic>;
        final data = responseData['data'] as Map<String, dynamic>? ?? responseData;
        final result = UnprocessedSettlementsResult.fromJson(data);
        debugPrint('[WalletService] 查询成功: ${result.count} 条记录, 总金额: ${result.totalAmount}');
        debugPrint('[WalletService] ================================');
        return result;
      }

      throw Exception('查询失败: ${response.statusCode}');
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 查询未处理结算记录异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }

  /// 执行全额线下结算扣减
  ///
  /// 调用 POST /wallets/offline-settlement/execute
  /// 自动扣减用户所有未处理的结算收益
  Future<OfflineSettlementDeductionResult> executeOfflineSettlementDeduction({
    required String accountSequence,
    required String pendingActionId,
    required String operatorId,
    String? customMemo,
  }) async {
    try {
      debugPrint('[WalletService] ========== 执行全额线下结算扣减 ==========');
      debugPrint('[WalletService] accountSequence: $accountSequence');
      debugPrint('[WalletService] pendingActionId: $pendingActionId');
      debugPrint('[WalletService] operatorId: $operatorId');
      debugPrint('[WalletService] customMemo: $customMemo');

      final response = await _apiClient.post(
        '/wallets/offline-settlement/execute',
        data: {
          'accountSequence': accountSequence,
          'pendingActionId': pendingActionId,
          'operatorId': operatorId,
          if (customMemo != null && customMemo.isNotEmpty) 'customMemo': customMemo,
        },
      );

      debugPrint('[WalletService] 响应状态码: ${response.statusCode}');
      debugPrint('[WalletService] 响应数据: ${response.data}');

      if (response.statusCode == 200 || response.statusCode == 201) {
        final responseData = response.data as Map<String, dynamic>;
        final data = responseData['data'] as Map<String, dynamic>? ?? responseData;
        final result = OfflineSettlementDeductionResult.fromJson(data);
        debugPrint('[WalletService] 全额扣减成功: ${result.deductionCount} 笔, 总金额: ${result.totalDeducted}');
        debugPrint('[WalletService] ================================');
        return result;
      }

      throw Exception('全额扣减失败: ${response.statusCode}');
    } catch (e, stackTrace) {
      debugPrint('[WalletService] !!!!!!!!!! 全额线下结算扣减异常 !!!!!!!!!!');
      debugPrint('[WalletService] 错误: $e');
      debugPrint('[WalletService] 堆栈: $stackTrace');
      rethrow;
    }
  }
}

/// 未处理结算记录查询结果
class UnprocessedSettlementsResult {
  final List<UnprocessedSettlementEntry> entries;
  final double totalAmount;
  final int count;

  UnprocessedSettlementsResult({
    required this.entries,
    required this.totalAmount,
    required this.count,
  });

  factory UnprocessedSettlementsResult.fromJson(Map<String, dynamic> json) {
    final entriesList = json['entries'] as List<dynamic>? ?? [];
    return UnprocessedSettlementsResult(
      entries: entriesList
          .map((e) => UnprocessedSettlementEntry.fromJson(e as Map<String, dynamic>))
          .toList(),
      totalAmount: (json['totalAmount'] ?? 0).toDouble(),
      count: json['count'] ?? 0,
    );
  }
}

/// 未处理结算记录条目
class UnprocessedSettlementEntry {
  final String id;
  final double amount;
  final DateTime createdAt;
  final String? memo;
  final String? allocationType;

  UnprocessedSettlementEntry({
    required this.id,
    required this.amount,
    required this.createdAt,
    this.memo,
    this.allocationType,
  });

  factory UnprocessedSettlementEntry.fromJson(Map<String, dynamic> json) {
    return UnprocessedSettlementEntry(
      id: json['id']?.toString() ?? '',
      amount: (json['amount'] ?? 0).toDouble(),
      createdAt: json['createdAt'] != null
          ? DateTime.tryParse(json['createdAt']) ?? DateTime.now()
          : DateTime.now(),
      memo: json['memo'],
      allocationType: json['allocationType'],
    );
  }

  /// 获取权益类型中文名
  String get allocationTypeName {
    const nameMap = {
      'SHARE_RIGHT': '分享权益',
      'PROVINCE_AREA_RIGHT': '省区域权益',
      'PROVINCE_TEAM_RIGHT': '省团队权益',
      'CITY_AREA_RIGHT': '市区域权益',
      'CITY_TEAM_RIGHT': '市团队权益',
      'COMMUNITY_RIGHT': '社区权益',
    };
    return nameMap[allocationType] ?? allocationType ?? '收益结算';
  }
}

/// 全额线下结算扣减结果
class OfflineSettlementDeductionResult {
  final bool success;
  final double totalDeducted;
  final int deductionCount;
  final List<String> orderNos;
  final double newBalance;

  OfflineSettlementDeductionResult({
    required this.success,
    required this.totalDeducted,
    required this.deductionCount,
    required this.orderNos,
    required this.newBalance,
  });

  factory OfflineSettlementDeductionResult.fromJson(Map<String, dynamic> json) {
    final orderNosList = json['orderNos'] as List<dynamic>? ?? [];
    return OfflineSettlementDeductionResult(
      success: json['success'] as bool? ?? false,
      totalDeducted: (json['totalDeducted'] ?? 0).toDouble(),
      deductionCount: json['deductionCount'] ?? 0,
      orderNos: orderNosList.map((e) => e.toString()).toList(),
      newBalance: (json['newBalance'] ?? 0).toDouble(),
    );
  }
}

/// 特殊扣减结果
class SpecialDeductionResult {
  final bool success;
  final String orderNo;
  final double newBalance;

  SpecialDeductionResult({
    required this.success,
    required this.orderNo,
    required this.newBalance,
  });

  factory SpecialDeductionResult.fromJson(Map<String, dynamic> json) {
    return SpecialDeductionResult(
      success: json['success'] as bool? ?? false,
      orderNo: json['orderNo'] as String? ?? '',
      newBalance: (json['newBalance'] ?? 0).toDouble(),
    );
  }
}

/// 提取响应
class WithdrawResponse {
  final String orderNo;
  final String status;
  final double amount;
  final double fee;
  final double netAmount;
  final String toAddress;
  final String chainType;
  final DateTime createdAt;

  WithdrawResponse({
    required this.orderNo,
    required this.status,
    required this.amount,
    required this.fee,
    required this.netAmount,
    required this.toAddress,
    required this.chainType,
    required this.createdAt,
  });

  factory WithdrawResponse.fromJson(Map<String, dynamic> json) {
    return WithdrawResponse(
      orderNo: json['orderNo'] ?? json['id'] ?? '',
      status: json['status'] ?? 'PENDING',
      amount: (json['amount'] ?? 0).toDouble(),
      fee: (json['fee'] ?? 0).toDouble(),
      netAmount: (json['netAmount'] ?? json['amount'] ?? 0).toDouble(),
      toAddress: json['toAddress'] ?? '',
      chainType: json['chainType'] ?? 'KAVA',
      createdAt: json['createdAt'] != null
          ? DateTime.tryParse(json['createdAt']) ?? DateTime.now()
          : DateTime.now(),
    );
  }
}

/// 提取记录
class WithdrawRecord {
  final String orderNo;
  final String status;
  final double amount;
  final double fee;
  final double netAmount;
  final String toAddress;
  final String chainType;
  final String? txHash;
  final DateTime createdAt;
  final DateTime? completedAt;

  WithdrawRecord({
    required this.orderNo,
    required this.status,
    required this.amount,
    required this.fee,
    required this.netAmount,
    required this.toAddress,
    required this.chainType,
    this.txHash,
    required this.createdAt,
    this.completedAt,
  });

  factory WithdrawRecord.fromJson(Map<String, dynamic> json) {
    return WithdrawRecord(
      orderNo: json['orderNo'] ?? json['id'] ?? '',
      status: json['status'] ?? 'PENDING',
      amount: (json['amount'] ?? 0).toDouble(),
      fee: (json['fee'] ?? 0).toDouble(),
      netAmount: (json['netAmount'] ?? json['amount'] ?? 0).toDouble(),
      toAddress: json['toAddress'] ?? '',
      chainType: json['chainType'] ?? 'KAVA',
      txHash: json['txHash'],
      createdAt: json['createdAt'] != null
          ? DateTime.tryParse(json['createdAt']) ?? DateTime.now()
          : DateTime.now(),
      completedAt: json['completedAt'] != null
          ? DateTime.tryParse(json['completedAt'])
          : null,
    );
  }
}

// =============== 账本流水相关模型 ===============

/// 账本流水条目
class LedgerEntry {
  final String id;
  final String entryType;
  final double amount;
  final String assetType;
  final double? balanceAfter;
  final String? refOrderId;
  final String? refTxHash;
  final String? memo;
  final String? allocationType;
  final Map<String, dynamic>? payloadJson;
  final DateTime createdAt;

  LedgerEntry({
    required this.id,
    required this.entryType,
    required this.amount,
    required this.assetType,
    this.balanceAfter,
    this.refOrderId,
    this.refTxHash,
    this.memo,
    this.allocationType,
    this.payloadJson,
    required this.createdAt,
  });

  factory LedgerEntry.fromJson(Map<String, dynamic> json) {
    return LedgerEntry(
      id: json['id']?.toString() ?? '',
      entryType: json['entryType'] ?? '',
      amount: (json['amount'] ?? 0).toDouble(),
      assetType: json['assetType'] ?? 'USDT',
      balanceAfter: json['balanceAfter']?.toDouble(),
      refOrderId: json['refOrderId'],
      refTxHash: json['refTxHash'],
      memo: json['memo'],
      allocationType: json['allocationType'],
      payloadJson: json['payloadJson'] as Map<String, dynamic>?,
      createdAt: json['createdAt'] != null
          ? DateTime.tryParse(json['createdAt']) ?? DateTime.now()
          : DateTime.now(),
    );
  }

  // === 转账相关辅助方法 ===

  /// 获取转账对方的账户序列号
  String? get counterpartyAccountSequence {
    if (payloadJson == null) return null;
    if (entryType == 'TRANSFER_IN') {
      return payloadJson!['fromAccountSequence'] as String?;
    } else if (entryType == 'TRANSFER_OUT') {
      return payloadJson!['toAccountSequence'] as String?;
    }
    return null;
  }

  /// 获取转账对方的用户ID
  String? get counterpartyUserId {
    if (payloadJson == null) return null;
    if (entryType == 'TRANSFER_IN') {
      return payloadJson!['fromUserId']?.toString();
    } else if (entryType == 'TRANSFER_OUT') {
      return payloadJson!['toUserId']?.toString();
    }
    return null;
  }

  /// 获取转账手续费（仅转出时有）
  double? get transferFee {
    if (payloadJson == null || entryType != 'TRANSFER_OUT') return null;
    final fee = payloadJson!['fee'];
    if (fee == null) return null;
    if (fee is num) return fee.toDouble();
    if (fee is String) return double.tryParse(fee);
    return null;
  }

  /// 获取流水类型中文名
  String get entryTypeName {
    const nameMap = {
      'DEPOSIT_KAVA': '充值',
      'DEPOSIT_BSC': '充值',
      'PLANT_PAYMENT': '认种支付',
      'PLANT_FREEZE': '认种冻结',
      'PLANT_UNFREEZE': '认种解冻',
      'REWARD_PENDING': '待领取奖励',
      'REWARD_TO_SETTLEABLE': '分享收益',
      'REWARD_PENDING_CONVERTED': '待领取转可结算',
      'REWARD_EXPIRED': '奖励过期',
      'REWARD_SETTLED': '奖励结算',
      'TRANSFER_TO_POOL': '转入矿池',
      'SWAP_EXECUTED': '兑换执行',
      'WITHDRAWAL': '提现',
      'TRANSFER_IN': '转入',
      'TRANSFER_OUT': '转出',
      'FREEZE': '冻结',
      'UNFREEZE': '解冻',
      'SYSTEM_ALLOCATION': '系统分配',
      'SPECIAL_DEDUCTION': '面对面结算',
    };
    return nameMap[entryType] ?? entryType;
  }

  /// 获取权益分配类型中文名
  String? get allocationTypeName {
    if (allocationType == null) return null;
    const nameMap = {
      'SHARE_RIGHT': '分享权益',
      'PROVINCE_AREA_RIGHT': '省区域权益',
      'PROVINCE_TEAM_RIGHT': '省团队权益',
      'CITY_AREA_RIGHT': '市区域权益',
      'CITY_TEAM_RIGHT': '市团队权益',
      'COMMUNITY_RIGHT': '社区权益',
    };
    return nameMap[allocationType] ?? allocationType;
  }

  /// 获取显示名称（优先显示权益类型，否则显示流水类型）
  String get displayName {
    return allocationTypeName ?? entryTypeName;
  }

  /// [2026-03-01] 获取带状态标注的显示名称
  /// 当用户已无待领取奖励时，REWARD_PENDING 流水追加"(已转可结算)"标注
  String displayNameWithStatus({bool userHasNoPending = false}) {
    final baseName = allocationTypeName ?? entryTypeName;

    if (entryType == 'REWARD_PENDING' && userHasNoPending) {
      return '$baseName (已转可结算)';
    }

    return baseName;
  }

  /// 从 memo 中提取来源用户ID（格式如："来源: D26022600016"）
  String? get sourceAccountFromMemo {
    if (memo == null) return null;
    final match = RegExp(r'来源:\s*(D\d+)').firstMatch(memo!);
    return match?.group(1);
  }

  /// 是否为收入
  bool get isIncome => amount > 0;
}

/// 分页的账本流水响应
class PaginatedLedger {
  final List<LedgerEntry> data;
  final int total;
  final int page;
  final int pageSize;
  final int totalPages;

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

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

/// 按类型汇总的统计项
class EntryTypeSummary {
  final String entryType;
  final String entryTypeName;
  final double totalAmount;
  final int count;

  EntryTypeSummary({
    required this.entryType,
    required this.entryTypeName,
    required this.totalAmount,
    required this.count,
  });

  factory EntryTypeSummary.fromJson(Map<String, dynamic> json) {
    return EntryTypeSummary(
      entryType: json['entryType'] ?? '',
      entryTypeName: json['entryTypeName'] ?? '',
      totalAmount: (json['totalAmount'] ?? 0).toDouble(),
      count: json['count'] ?? 0,
    );
  }
}

/// 流水统计
class LedgerStatistics {
  final double totalIncome;
  final double totalExpense;
  final double netAmount;
  final int totalCount;
  final List<EntryTypeSummary> byEntryType;
  final DateTime startDate;
  final DateTime endDate;

  LedgerStatistics({
    required this.totalIncome,
    required this.totalExpense,
    required this.netAmount,
    required this.totalCount,
    required this.byEntryType,
    required this.startDate,
    required this.endDate,
  });

  factory LedgerStatistics.fromJson(Map<String, dynamic> json) {
    final byTypeList = json['byEntryType'] as List<dynamic>? ?? [];
    return LedgerStatistics(
      totalIncome: (json['totalIncome'] ?? 0).toDouble(),
      totalExpense: (json['totalExpense'] ?? 0).toDouble(),
      netAmount: (json['netAmount'] ?? 0).toDouble(),
      totalCount: json['totalCount'] ?? 0,
      byEntryType: byTypeList.map((e) => EntryTypeSummary.fromJson(e as Map<String, dynamic>)).toList(),
      startDate: DateTime.tryParse(json['startDate'] ?? '') ?? DateTime.now(),
      endDate: DateTime.tryParse(json['endDate'] ?? '') ?? DateTime.now(),
    );
  }
}

/// 每日趋势项
class DailyTrendItem {
  final String date;
  final double income;
  final double expense;
  final double net;
  final int count;

  DailyTrendItem({
    required this.date,
    required this.income,
    required this.expense,
    required this.net,
    required this.count,
  });

  factory DailyTrendItem.fromJson(Map<String, dynamic> json) {
    return DailyTrendItem(
      date: json['date'] ?? '',
      income: (json['income'] ?? 0).toDouble(),
      expense: (json['expense'] ?? 0).toDouble(),
      net: (json['net'] ?? 0).toDouble(),
      count: json['count'] ?? 0,
    );
  }
}

/// 流水趋势
class LedgerTrend {
  final List<DailyTrendItem> dailyTrend;
  final int days;
  final double periodIncome;
  final double periodExpense;
  final double periodNet;

  LedgerTrend({
    required this.dailyTrend,
    required this.days,
    required this.periodIncome,
    required this.periodExpense,
    required this.periodNet,
  });

  factory LedgerTrend.fromJson(Map<String, dynamic> json) {
    final trendList = json['dailyTrend'] as List<dynamic>? ?? [];
    return LedgerTrend(
      dailyTrend: trendList.map((e) => DailyTrendItem.fromJson(e as Map<String, dynamic>)).toList(),
      days: json['days'] ?? 30,
      periodIncome: (json['periodIncome'] ?? 0).toDouble(),
      periodExpense: (json['periodExpense'] ?? 0).toDouble(),
      periodNet: (json['periodNet'] ?? 0).toDouble(),
    );
  }
}

// =============== 法币提现相关模型 ===============

/// 支付方式枚举
enum PaymentMethod {
  BANK_CARD,
  ALIPAY,
  WECHAT,
}

/// 法币提现状态枚举
enum FiatWithdrawalStatus {
  PENDING,
  FROZEN,
  REVIEWING,
  APPROVED,
  PAYING,
  COMPLETED,
  REJECTED,
  FAILED,
  CANCELLED,
}

/// 法币提现响应
class FiatWithdrawalResponse {
  final String orderNo;
  final String status;
  final double amount;
  final double fee;
  final String paymentMethod;
  final DateTime createdAt;

  FiatWithdrawalResponse({
    required this.orderNo,
    required this.status,
    required this.amount,
    required this.fee,
    required this.paymentMethod,
    required this.createdAt,
  });

  factory FiatWithdrawalResponse.fromJson(Map<String, dynamic> json) {
    return FiatWithdrawalResponse(
      orderNo: json['orderNo'] ?? json['id'] ?? '',
      status: json['status'] ?? 'PENDING',
      amount: (json['amount'] ?? 0).toDouble(),
      fee: (json['fee'] ?? 0).toDouble(),
      paymentMethod: json['paymentMethod'] ?? 'BANK_CARD',
      createdAt: json['createdAt'] != null
          ? DateTime.tryParse(json['createdAt']) ?? DateTime.now()
          : DateTime.now(),
    );
  }
}

/// 法币提现记录
class FiatWithdrawalRecord {
  final String orderNo;
  final String status;
  final double amount;
  final double fee;
  final String paymentMethod;
  // 银行卡信息
  final String? bankName;
  final String? bankCardNo;
  final String? cardHolderName;
  // 支付宝信息
  final String? alipayAccount;
  final String? alipayRealName;
  // 微信信息
  final String? wechatAccount;
  final String? wechatRealName;
  // 审核信息
  final String? reviewedBy;
  final DateTime? reviewedAt;
  final String? reviewRemark;
  // 打款信息
  final String? paidBy;
  final DateTime? paidAt;
  final String? paymentProof;
  final String? paymentRemark;
  // 时间戳
  final DateTime createdAt;
  final DateTime? completedAt;

  FiatWithdrawalRecord({
    required this.orderNo,
    required this.status,
    required this.amount,
    required this.fee,
    required this.paymentMethod,
    this.bankName,
    this.bankCardNo,
    this.cardHolderName,
    this.alipayAccount,
    this.alipayRealName,
    this.wechatAccount,
    this.wechatRealName,
    this.reviewedBy,
    this.reviewedAt,
    this.reviewRemark,
    this.paidBy,
    this.paidAt,
    this.paymentProof,
    this.paymentRemark,
    required this.createdAt,
    this.completedAt,
  });

  factory FiatWithdrawalRecord.fromJson(Map<String, dynamic> json) {
    return FiatWithdrawalRecord(
      orderNo: json['orderNo'] ?? json['id'] ?? '',
      status: json['status'] ?? 'PENDING',
      amount: (json['amount'] ?? 0).toDouble(),
      fee: (json['fee'] ?? 0).toDouble(),
      paymentMethod: json['paymentMethod'] ?? 'BANK_CARD',
      bankName: json['bankName'],
      bankCardNo: json['bankCardNo'],
      cardHolderName: json['cardHolderName'],
      alipayAccount: json['alipayAccount'],
      alipayRealName: json['alipayRealName'],
      wechatAccount: json['wechatAccount'],
      wechatRealName: json['wechatRealName'],
      reviewedBy: json['reviewedBy'],
      reviewedAt: json['reviewedAt'] != null
          ? DateTime.tryParse(json['reviewedAt'])
          : null,
      reviewRemark: json['reviewRemark'],
      paidBy: json['paidBy'],
      paidAt: json['paidAt'] != null
          ? DateTime.tryParse(json['paidAt'])
          : null,
      paymentProof: json['paymentProof'],
      paymentRemark: json['paymentRemark'],
      createdAt: json['createdAt'] != null
          ? DateTime.tryParse(json['createdAt']) ?? DateTime.now()
          : DateTime.now(),
      completedAt: json['completedAt'] != null
          ? DateTime.tryParse(json['completedAt'])
          : null,
    );
  }

  /// 获取状态中文名
  String get statusName {
    const nameMap = {
      'PENDING': '待处理',
      'FROZEN': '已冻结',
      'REVIEWING': '审核中',
      'APPROVED': '已审核',
      'PAYING': '打款中',
      'COMPLETED': '已完成',
      'REJECTED': '已拒绝',
      'FAILED': '失败',
      'CANCELLED': '已取消',
    };
    return nameMap[status] ?? status;
  }

  /// 获取支付方式中文名
  String get paymentMethodName {
    const nameMap = {
      'BANK_CARD': '银行卡',
      'ALIPAY': '支付宝',
      'WECHAT': '微信',
    };
    return nameMap[paymentMethod] ?? paymentMethod;
  }
}
