import 'package:dio/dio.dart';

import '../models/asset/asset_statement.dart';
import '../models/asset/deposit_wallet.dart';
import '../models/asset/today_pnl.dart';
import '../models/asset/recharge_record.dart';
import '../models/asset/transfer_record.dart';
import '../models/asset/wallet_overview.dart';

/// 资产 API 服务（无状态）
class AssetService {
  const AssetService(this._dio);

  final Dio _dio;

  /// 获取钱包地址列表（充值页面核心接口）
  Future<List<DepositWallet>> getWalletAddresses() async {
    // 钱包地址必须始终从服务器获取，不能使用缓存，确保用户收到最新的充值地址
    final response = await _dio.post<Map<String, dynamic>>(
      'uc/asset/wallet/address',
      options: Options(extra: {'noCache': true}),
    );
    final data = response.data?['data'];
    if (data is List) {
      return data
          .whereType<Map<String, dynamic>>()
          .map((e) => DepositWallet.fromJson(e))
          .toList();
    }
    return [];
  }

  /// 获取充值记录列表
  Future<List<RechargeRecord>> getRechargeList({
    int pageNo = 1,
    int pageSize = 10,
  }) async {
    final response = await _dio.get<Map<String, dynamic>>(
      'uc/asset/recharge-list',
      queryParameters: {'pageNo': pageNo, 'pageSize': pageSize},
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      final content = data['content'];
      if (content is List) {
        return content
            .whereType<Map<String, dynamic>>()
            .map((e) => RechargeRecord.fromJson(e))
            .toList();
      }
    }
    return [];
  }

  /// 执行划转
  Future<void> transfer({
    required String amount,
    required String from,
    required String to,
  }) async {
    await _dio.post(
      'uc/asset/transfer',
      data: {'amount': amount, 'from': from, 'to': to},
      options: Options(contentType: Headers.formUrlEncodedContentType),
    );
  }

  /// 获取划转记录列表
  Future<List<TransferRecord>> getTransferList({
    int pageNo = 1,
    int pageSize = 10,
  }) async {
    final response = await _dio.post<Map<String, dynamic>>(
      'uc/asset/transfer/list',
      data: {'pageNo': pageNo, 'pageSize': pageSize},
      options: Options(contentType: Headers.formUrlEncodedContentType),
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      final content = data['content'];
      if (content is List) {
        return content
            .whereType<Map<String, dynamic>>()
            .map((e) => TransferRecord.fromJson(e))
            .toList();
      }
    }
    return [];
  }

  /// 获取流水币种列表（筛选用）
  Future<List<StatementCoin>> getStatementCoins() async {
    final response = await _dio.get<Map<String, dynamic>>(
      'uc/asset/transaction/coin',
    );
    final data = response.data?['data'];
    if (data is List) {
      final list = data
          .whereType<Map<String, dynamic>>()
          .map((e) => StatementCoin.fromJson(e))
          .toList();
      list.sort((a, b) => a.sort.compareTo(b.sort));
      return list;
    }
    return [];
  }

  /// 获取流水类型列表（筛选用）
  Future<List<StatementType>> getStatementTypes() async {
    final response = await _dio.get<Map<String, dynamic>>(
      'uc/asset/transaction/type',
    );
    final data = response.data?['data'];
    if (data is List) {
      return data
          .whereType<Map<String, dynamic>>()
          .map((e) => StatementType.fromJson(e))
          .toList();
    }
    return [];
  }

  /// 查询流水记录
  Future<List<AssetStatement>> getStatementList({
    String type = '',
    String symbol = '',
    String startTime = '',
    String endTime = '',
    int pageNo = 1,
    int pageSize = 10,
  }) async {
    final response = await _dio.post<Map<String, dynamic>>(
      'uc/asset/transaction/all',
      data: {
        'type': type,
        'symbol': symbol,
        'startTime': startTime,
        'endTime': endTime,
        'pageNo': pageNo,
        'pageSize': pageSize,
      },
      options: Options(contentType: Headers.formUrlEncodedContentType),
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      final content = data['content'];
      if (content is List) {
        return content
            .whereType<Map<String, dynamic>>()
            .map((e) => AssetStatement.fromJson(e))
            .toList();
      }
    }
    return [];
  }

  /// 获取今日盈亏（从合约资产接口提取）
  Future<TodayPnl> getTodayPnl() async {
    // 资产数据必须始终从服务器获取，不能使用缓存
    final response = await _dio.get<Map<String, dynamic>>(
      'swap/wallet-new/get'
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      return TodayPnl.fromJson(data);
    }
    return TodayPnl();
  }

  /// 获取可提现账户资产列表（对齐 Web: /swap/wallet-new/account/asset/list?hideZero=）
  Future<Map<String, dynamic>> getFundAssets({bool? hideZero}) async {
    final query = <String, dynamic>{};
    if (hideZero != null) {
      query['hideZero'] = hideZero;
    }
    final response = await _dio.get<Map<String, dynamic>>(
      'swap/wallet-new/account/asset/list',
      queryParameters: query.isEmpty ? null : query,
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      return data;
    }
    return {};
  }

  /// 获取账户总览（各钱包余额汇总）
  Future<List<WalletOverview>> getWalletOverview() async {
    // 账户余额必须始终从服务器获取，不能使用缓存
    final response = await _dio.get<Map<String, dynamic>>(
      'uc/asset/wallets',
      options: Options(extra: {'noCache': true}),
    );
    final data = response.data?['data'];
    if (data is List) {
      return data
          .whereType<Map<String, dynamic>>()
          .map((e) => WalletOverview.fromJson(e))
          .toList();
    }
    return [];
  }
}
