import 'package:decimal/decimal.dart';
import 'package:dio/dio.dart';

import '../models/asset/account_auth.dart';
import '../models/asset/withdraw_balance.dart';
import '../models/asset/withdraw_record.dart';

/// 提币 API 服务（无状态）
class WithdrawService {
  const WithdrawService(this._dio);

  final Dio _dio;

  /// 获取可用余额
  Future<WithdrawBalance> getBalance(String coinName) async {
    // 可用余额必须始终从服务器获取，不能使用缓存
    final response = await _dio.post<Map<String, dynamic>>(
      'uc/asset/wallet/$coinName',
      options: Options(extra: {'noCache': true}),
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      return WithdrawBalance.fromJson(data);
    }
    return WithdrawBalance();
  }

  /// 获取认证信息（Google验证状态等）
  Future<AccountAuth> getSecuritySetting() async {
    final response = await _dio.post<Map<String, dynamic>>(
      'uc/approve/security/setting',
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      return AccountAuth.fromJson(data);
    }
    return const AccountAuth();
  }

  /// 发送提币邮箱验证码
  Future<void> sendWithdrawEmailCode({
    required String unit,
    required String address,
    required String amount,
  }) async {
    await _dio.post(
      'uc/withdraw/email/code',
      data: {'unit': unit, 'address': address, 'amount': amount},
      options: Options(contentType: Headers.formUrlEncodedContentType),
    );
  }

  /// 链上提币
  Future<void> withdrawApply({
    required String unit,
    required String amount,
    required String address,
    required String fee,
    required String vcode,
    required String jyPassword,
    required String vcode2,
    String remark = '',
  }) async {
    await _dio.post(
      'uc/withdraw/apply/code',
      data: {
        'unit': unit,
        'amount': amount,
        'address': address,
        'fee': fee,
        'vcode': vcode,
        'vtype': '2', // 邮箱验证
        'jyPassword': jyPassword,
        'vcode2': vcode2,
        'remark': remark,
      },
      options: Options(contentType: Headers.formUrlEncodedContentType),
    );
  }

  /// 获取内部转账最小金额（USDT 基础币种配置）
  Future<Decimal> getTransferMinAmount({String unit = 'USDT'}) async {
    try {
      final response = await _dio.post<Map<String, dynamic>>(
        'uc/withdraw/support/coin/info',
        options: Options(extra: {'noCache': true}),
      );
      final data = response.data?['data'];
      if (data is List) {
        for (final item in data) {
          if (item is Map<String, dynamic> && item['unit'] == unit) {
            return Decimal.tryParse(item['minAmount']?.toString() ?? '') ?? Decimal.zero;
          }
        }
      }
    } catch (_) {}
    return Decimal.zero;
  }

  /// 内部转账
  Future<void> internalTransfer({
    required String unit,
    required String amount,
    required String address,
    required String vcode,
    required String jyPassword,
    required String vcode2,
    String remark = '',
  }) async {
    await _dio.post(
      'uc/withdraw/transfer',
      data: {
        'unit': unit,
        'amount': amount,
        'address': address,
        'vcode': vcode,
        'vtype': '2',
        'jyPassword': jyPassword,
        'vcode2': vcode2,
        'remark': remark,
      },
      options: Options(contentType: Headers.formUrlEncodedContentType),
    );
  }

  /// 链上提现记录（page 从 0 开始）
  Future<List<WithdrawRecord>> getWithdrawRecords({
    int page = 0,
    int pageSize = 10,
  }) async {
    final response = await _dio.get<Map<String, dynamic>>(
      'uc/withdraw/record',
      queryParameters: {'page': page, 'pageSize': pageSize},
    );
    return _parseRecordList(response.data);
  }

  /// 内部转账记录（pageNo 从 0 开始）
  Future<List<WithdrawRecord>> getTransferRecords({
    int pageNo = 0,
    int pageSize = 10,
  }) async {
    final response = await _dio.get<Map<String, dynamic>>(
      'uc/withdraw/transfer/record',
      queryParameters: {'pageNo': pageNo, 'pageSize': pageSize},
    );
    return _parseRecordList(response.data);
  }

  /// 取消链上提现
  Future<void> cancelWithdraw(String id) async {
    await _dio.post('uc/withdraw/cancel', queryParameters: {'id': id});
  }

  /// 获取单条链上提现记录详情
  Future<WithdrawRecord> getWithdrawRecord(String id) async {
    final response = await _dio.get<Map<String, dynamic>>(
      'uc/withdraw/record/$id',
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      return WithdrawRecord.fromJson(data);
    }
    return WithdrawRecord(id: id);
  }

  /// 获取单条内部转账记录详情
  Future<WithdrawRecord> getTransferRecord(String id) async {
    final response = await _dio.get<Map<String, dynamic>>(
      'uc/withdraw/transfer/record/$id',
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      return WithdrawRecord.fromJson(data);
    }
    return WithdrawRecord(id: id);
  }

  /// 取消内部转账
  Future<void> cancelTransfer(String id) async {
    await _dio.post('uc/withdraw/transfer/cancel', queryParameters: {'id': id});
  }

  List<WithdrawRecord> _parseRecordList(Map<String, dynamic>? responseData) {
    final data = responseData?['data'];
    if (data is Map<String, dynamic>) {
      final content = data['content'];
      if (content is List) {
        return content
            .whereType<Map<String, dynamic>>()
            .map((e) => WithdrawRecord.fromJson(e))
            .toList();
      }
    }
    return [];
  }
}
