import '../../core/constants/api_endpoints.dart';
import '../../core/network/api_response.dart';
import '../../core/network/dio_client.dart';
import '../models/order_models.dart';

/// 充提服务
class FundService {
  final DioClient _client;

  FundService(this._client);

  /// 获取默认钱包地址
  Future<ApiResponse<ColdWallet>> getDefaultWallet() async {
    final response = await _client.get<Map<String, dynamic>>(
      ApiEndpoints.defaultWallet,
    );

    if (response.success && response.data != null) {
      return ApiResponse.success(
        ColdWallet.fromJson(response.data!),
        response.message,
      );
    }
    return ApiResponse.fail(response.message ?? '获取钱包地址失败');
  }

  /// 申请充值
  /// 返回包含 orderNo, amount, status, walletAddress, walletNetwork 的信息
  Future<ApiResponse<Map<String, dynamic>>> deposit({
    required String amount,
    String? remark,
  }) async {
    return _client.post<Map<String, dynamic>>(
      ApiEndpoints.deposit,
      data: {
        'amount': amount,
        if (remark != null) 'remark': remark,
      },
    );
  }

  /// 用户确认已打款
  Future<ApiResponse<void>> confirmPay(String orderNo) async {
    return _client.post<void>(
      ApiEndpoints.confirmPay,
      data: {'orderNo': orderNo},
    );
  }

  /// 申请提现
  Future<ApiResponse<Map<String, dynamic>>> withdraw({
    required String amount,
    required String withdrawAddress,
    String? withdrawContact,
    String? remark,
  }) async {
    return _client.post<Map<String, dynamic>>(
      ApiEndpoints.withdraw,
      data: {
        'amount': amount,
        'withdrawAddress': withdrawAddress,
        if (withdrawContact != null) 'withdrawContact': withdrawContact,
        if (remark != null) 'remark': remark,
      },
    );
  }

  /// 取消订单
  Future<ApiResponse<void>> cancelOrder(String orderNo) async {
    return _client.post<void>(
      ApiEndpoints.cancelOrder,
      data: {'orderNo': orderNo},
    );
  }

  /// 获取充提记录
  Future<ApiResponse<Map<String, dynamic>>> getOrders({
    int? type,
    int pageNum = 1,
    int pageSize = 20,
  }) async {
    final params = <String, dynamic>{
      'pageNum': pageNum,
      'pageSize': pageSize,
    };
    if (type != null) params['type'] = type;

    return _client.get<Map<String, dynamic>>(
      ApiEndpoints.fundOrders,
      queryParameters: params,
    );
  }

  /// 解析充提记录列表
  List<OrderFund> parseOrderList(List<dynamic>? list) {
    if (list == null) return [];
    return list.map((e) => OrderFund.fromJson(e as Map<String, dynamic>)).toList();
  }
}
