import 'package:flutter/foundation.dart';
import '../network/api_client.dart';

/// 发行商财务服务
class IssuerFinanceService {
  final ApiClient _apiClient;

  IssuerFinanceService({ApiClient? apiClient})
      : _apiClient = apiClient ?? ApiClient.instance;

  /// 获取可提现余额
  Future<FinanceBalance> getBalance() async {
    try {
      final response = await _apiClient.get('/api/v1/issuers/me/finance/balance');
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return FinanceBalance.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[IssuerFinanceService] getBalance 失败: $e');
      rethrow;
    }
  }

  /// 获取财务概览
  Future<FinanceStats> getStats() async {
    try {
      final response = await _apiClient.get('/api/v1/issuers/me/finance/stats');
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return FinanceStats.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[IssuerFinanceService] getStats 失败: $e');
      rethrow;
    }
  }

  /// 获取交易流水
  Future<({List<TransactionModel> items, int total})> getTransactions({
    int page = 1,
    int limit = 20,
    String? type,
  }) async {
    try {
      final params = <String, dynamic>{'page': page, 'limit': limit};
      if (type != null) params['type'] = type;

      final response = await _apiClient.get(
        '/api/v1/issuers/me/finance/transactions',
        queryParameters: params,
      );
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      final items = (inner['items'] as List?)
              ?.map((e) => TransactionModel.fromJson(e as Map<String, dynamic>))
              .toList() ??
          [];
      return (items: items, total: (inner['total'] as int?) ?? items.length);
    } catch (e) {
      debugPrint('[IssuerFinanceService] getTransactions 失败: $e');
      rethrow;
    }
  }

  /// 发起提现
  Future<void> withdraw(double amount) async {
    try {
      await _apiClient.post('/api/v1/issuers/me/finance/withdraw', data: {
        'amount': amount,
      });
    } catch (e) {
      debugPrint('[IssuerFinanceService] withdraw 失败: $e');
      rethrow;
    }
  }

  /// 获取对账数据
  Future<Map<String, dynamic>> getReconciliation({String period = 'month'}) async {
    try {
      final response = await _apiClient.get(
        '/api/v1/issuers/me/finance/reconciliation',
        queryParameters: {'period': period},
      );
      final data = response.data is Map<String, dynamic> ? response.data : {};
      return (data['data'] ?? data) as Map<String, dynamic>;
    } catch (e) {
      debugPrint('[IssuerFinanceService] getReconciliation 失败: $e');
      rethrow;
    }
  }
}

class FinanceBalance {
  final double withdrawable;
  final double pending;
  final double total;

  const FinanceBalance({
    required this.withdrawable,
    required this.pending,
    required this.total,
  });

  factory FinanceBalance.fromJson(Map<String, dynamic> json) {
    return FinanceBalance(
      withdrawable: _toDouble(json['withdrawable']),
      pending: _toDouble(json['pending']),
      total: _toDouble(json['total']),
    );
  }

  static double _toDouble(dynamic v) {
    if (v == null) return 0;
    if (v is num) return v.toDouble();
    return double.tryParse(v.toString()) ?? 0;
  }
}

class FinanceStats {
  final double salesAmount;
  final double breakageIncome;
  final double platformFee;
  final double pendingSettlement;
  final double withdrawnAmount;
  final double totalRevenue;

  const FinanceStats({
    required this.salesAmount,
    required this.breakageIncome,
    required this.platformFee,
    required this.pendingSettlement,
    required this.withdrawnAmount,
    required this.totalRevenue,
  });

  factory FinanceStats.fromJson(Map<String, dynamic> json) {
    return FinanceStats(
      salesAmount: _toDouble(json['salesAmount']),
      breakageIncome: _toDouble(json['breakageIncome']),
      platformFee: _toDouble(json['platformFee']),
      pendingSettlement: _toDouble(json['pendingSettlement']),
      withdrawnAmount: _toDouble(json['withdrawnAmount']),
      totalRevenue: _toDouble(json['totalRevenue']),
    );
  }

  static double _toDouble(dynamic v) {
    if (v == null) return 0;
    if (v is num) return v.toDouble();
    return double.tryParse(v.toString()) ?? 0;
  }
}

class TransactionModel {
  final String id;
  final String type;
  final double amount;
  final String description;
  final String status;
  final DateTime createdAt;

  const TransactionModel({
    required this.id,
    required this.type,
    required this.amount,
    required this.description,
    required this.status,
    required this.createdAt,
  });

  factory TransactionModel.fromJson(Map<String, dynamic> json) {
    return TransactionModel(
      id: json['id'] ?? '',
      type: json['type'] ?? '',
      amount: _toDouble(json['amount']),
      description: json['description'] ?? '',
      status: json['status'] ?? '',
      createdAt: DateTime.tryParse(json['createdAt']?.toString() ?? '') ?? DateTime.now(),
    );
  }

  static double _toDouble(dynamic v) {
    if (v == null) return 0;
    if (v is num) return v.toDouble();
    return double.tryParse(v.toString()) ?? 0;
  }
}
