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

/// 资产服务
class AssetService {
  final DioClient _client;

  AssetService(this._client);

  /// 获取资产总览
  Future<ApiResponse<AssetOverview>> getOverview() async {
    final response = await _client.get<Map<String, dynamic>>(
      ApiEndpoints.assetOverview,
    );

    if (response.success && response.data != null) {
      return ApiResponse.success(
        AssetOverview.fromJson(response.data!),
        response.message,
      );
    }
    return ApiResponse.fail(response.message ?? '获取资产总览失败');
  }

  /// 获取资金账户
  Future<ApiResponse<AccountFund>> getFundAccount() async {
    final response = await _client.get<Map<String, dynamic>>(
      ApiEndpoints.fundAccount,
    );

    if (response.success && response.data != null) {
      return ApiResponse.success(
        AccountFund.fromJson(response.data!),
        response.message,
      );
    }
    return ApiResponse.fail(response.message ?? '获取资金账户失败');
  }

  /// 获取交易账户
  Future<ApiResponse<List<AccountTrade>>> getTradeAccount() async {
    final response = await _client.get<Map<String, dynamic>>(
      ApiEndpoints.tradeAccount,
    );

    if (response.success && response.data != null) {
      final list = response.data!['list'] as List?;
      final accounts = list?.map((e) => AccountTrade.fromJson(e as Map<String, dynamic>)).toList() ?? [];
      return ApiResponse.success(accounts, response.message);
    }
    return ApiResponse.fail(response.message ?? '获取交易账户失败');
  }

  /// 资金划转
  Future<ApiResponse<void>> transfer({
    required int direction,
    required String amount,
  }) async {
    return _client.post<void>(
      ApiEndpoints.transfer,
      data: {
        'direction': direction,
        'amount': amount,
      },
    );
  }

  /// 获取资金流水
  Future<ApiResponse<Map<String, dynamic>>> getFlow({
    int? flowType,
    int pageNum = 1,
    int pageSize = 20,
  }) async {
    final params = <String, dynamic>{
      'pageNum': pageNum,
      'pageSize': pageSize,
    };
    if (flowType != null) params['flowType'] = flowType;

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