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

/// 核销服务
class RedemptionService {
  final ApiClient _apiClient;

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

  /// 扫码核销
  Future<RedemptionResult> scan(String qrCode) async {
    try {
      final response = await _apiClient.post('/api/v1/redemptions/scan', data: {
        'qrCode': qrCode,
      });
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return RedemptionResult.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[RedemptionService] scan 失败: $e');
      rethrow;
    }
  }

  /// 手动输入核销
  Future<RedemptionResult> manual(String couponCode) async {
    try {
      final response = await _apiClient.post('/api/v1/redemptions/manual', data: {
        'couponCode': couponCode,
      });
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return RedemptionResult.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[RedemptionService] manual 失败: $e');
      rethrow;
    }
  }

  /// 批量核销
  Future<BatchRedemptionResult> batch(List<String> couponCodes) async {
    try {
      final response = await _apiClient.post('/api/v1/redemptions/batch', data: {
        'couponCodes': couponCodes,
      });
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return BatchRedemptionResult.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[RedemptionService] batch 失败: $e');
      rethrow;
    }
  }

  /// 获取核销历史
  Future<({List<RedemptionRecord> items, int total})> getHistory({
    int page = 1,
    int limit = 20,
    String? startDate,
    String? endDate,
  }) async {
    try {
      final params = <String, dynamic>{'page': page, 'limit': limit};
      if (startDate != null) params['startDate'] = startDate;
      if (endDate != null) params['endDate'] = endDate;

      final response = await _apiClient.get(
        '/api/v1/redemptions',
        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) => RedemptionRecord.fromJson(e as Map<String, dynamic>))
              .toList() ??
          [];
      return (items: items, total: (inner['total'] as int?) ?? items.length);
    } catch (e) {
      debugPrint('[RedemptionService] getHistory 失败: $e');
      rethrow;
    }
  }

  /// 获取今日统计
  Future<TodayRedemptionStats> getTodayStats() async {
    try {
      final response = await _apiClient.get('/api/v1/redemptions/today-stats');
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return TodayRedemptionStats.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[RedemptionService] getTodayStats 失败: $e');
      rethrow;
    }
  }
}

class RedemptionResult {
  final String id;
  final String couponName;
  final double amount;
  final String status;

  const RedemptionResult({
    required this.id,
    required this.couponName,
    required this.amount,
    required this.status,
  });

  factory RedemptionResult.fromJson(Map<String, dynamic> json) {
    return RedemptionResult(
      id: json['id'] ?? '',
      couponName: json['couponName'] ?? '',
      amount: _toDouble(json['amount']),
      status: json['status'] ?? 'completed',
    );
  }

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

class BatchRedemptionResult {
  final int successCount;
  final int failCount;
  final List<String> failedCodes;

  const BatchRedemptionResult({
    required this.successCount,
    required this.failCount,
    required this.failedCodes,
  });

  factory BatchRedemptionResult.fromJson(Map<String, dynamic> json) {
    return BatchRedemptionResult(
      successCount: json['successCount'] ?? 0,
      failCount: json['failCount'] ?? 0,
      failedCodes: (json['failedCodes'] as List?)?.map((e) => e.toString()).toList() ?? [],
    );
  }
}

class RedemptionRecord {
  final String id;
  final String couponName;
  final double amount;
  final String method;
  final String status;
  final DateTime createdAt;

  const RedemptionRecord({
    required this.id,
    required this.couponName,
    required this.amount,
    required this.method,
    required this.status,
    required this.createdAt,
  });

  factory RedemptionRecord.fromJson(Map<String, dynamic> json) {
    return RedemptionRecord(
      id: json['id'] ?? '',
      couponName: json['couponName'] ?? '',
      amount: _toDouble(json['amount']),
      method: json['method'] ?? 'scan',
      status: json['status'] ?? 'completed',
      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;
  }
}

class TodayRedemptionStats {
  final int count;
  final double totalAmount;

  const TodayRedemptionStats({
    required this.count,
    required this.totalAmount,
  });

  factory TodayRedemptionStats.fromJson(Map<String, dynamic> json) {
    return TodayRedemptionStats(
      count: json['count'] ?? 0,
      totalAmount: _toDouble(json['totalAmount']),
    );
  }

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