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

/// 交易服务
class TradeService {
  final DioClient _client;

  TradeService(this._client);

  /// 买入
  Future<ApiResponse<Map<String, dynamic>>> buy({
    required String coinCode,
    required String price,
    required String quantity,
  }) async {
    return _client.post<Map<String, dynamic>>(
      ApiEndpoints.buy,
      data: {
        'coinCode': coinCode,
        'price': price,
        'quantity': quantity,
      },
    );
  }

  /// 卖出
  Future<ApiResponse<Map<String, dynamic>>> sell({
    required String coinCode,
    required String price,
    required String quantity,
  }) async {
    return _client.post<Map<String, dynamic>>(
      ApiEndpoints.sell,
      data: {
        'coinCode': coinCode,
        'price': price,
        'quantity': quantity,
      },
    );
  }

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

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

  /// 获取订单详情
  Future<ApiResponse<OrderTrade>> getOrderDetail(String orderNo) async {
    final response = await _client.get<Map<String, dynamic>>(
      ApiEndpoints.tradeOrderDetail,
      queryParameters: {'orderNo': orderNo},
    );

    if (response.success && response.data != null) {
      return ApiResponse.success(
        OrderTrade.fromJson(response.data!),
        response.message,
      );
    }
    return ApiResponse.fail(response.message ?? '获取订单详情失败');
  }
}
