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

/// 发行商券管理服务
class IssuerCouponService {
  final ApiClient _apiClient;

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

  /// 获取发行商的券列表
  Future<({List<IssuerCouponModel> items, int total})> list({
    int page = 1,
    int limit = 20,
    String? status,
    String? search,
  }) async {
    try {
      final params = <String, dynamic>{'page': page, 'limit': limit};
      if (status != null) params['status'] = status;
      if (search != null) params['search'] = search;

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

  /// 创建券
  Future<IssuerCouponModel> create(Map<String, dynamic> body) async {
    try {
      final response = await _apiClient.post('/api/v1/coupons', data: body);
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return IssuerCouponModel.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[IssuerCouponService] create 失败: $e');
      rethrow;
    }
  }

  /// 获取券详情
  Future<IssuerCouponModel> getDetail(String id) async {
    try {
      final response = await _apiClient.get('/api/v1/coupons/$id');
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return IssuerCouponModel.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[IssuerCouponService] getDetail 失败: $e');
      rethrow;
    }
  }

  /// 更新券状态
  Future<void> updateStatus(String id, String status) async {
    try {
      await _apiClient.put('/api/v1/coupons/$id/status', data: {
        'status': status,
      });
    } catch (e) {
      debugPrint('[IssuerCouponService] updateStatus 失败: $e');
      rethrow;
    }
  }

  /// 批量发行
  Future<void> batchIssue({
    required String templateId,
    required int quantity,
    required String expiryDate,
  }) async {
    try {
      await _apiClient.post('/api/v1/coupons/batch/issue', data: {
        'templateId': templateId,
        'quantity': quantity,
        'expiryDate': expiryDate,
      });
    } catch (e) {
      debugPrint('[IssuerCouponService] batchIssue 失败: $e');
      rethrow;
    }
  }

  /// 批量召回
  Future<void> batchRecall({
    required List<String> couponIds,
    required String reason,
  }) async {
    try {
      await _apiClient.post('/api/v1/coupons/batch/recall', data: {
        'couponIds': couponIds,
        'reason': reason,
      });
    } catch (e) {
      debugPrint('[IssuerCouponService] batchRecall 失败: $e');
      rethrow;
    }
  }

  /// 批量调价
  Future<void> batchPriceAdjust({
    required List<String> couponIds,
    required double adjustPercent,
  }) async {
    try {
      await _apiClient.post('/api/v1/coupons/batch/price-adjust', data: {
        'couponIds': couponIds,
        'adjustPercent': adjustPercent,
      });
    } catch (e) {
      debugPrint('[IssuerCouponService] batchPriceAdjust 失败: $e');
      rethrow;
    }
  }
}

class IssuerCouponModel {
  final String id;
  final String name;
  final String? description;
  final String? imageUrl;
  final double faceValue;
  final double currentPrice;
  final int totalSupply;
  final int remainingSupply;
  final String category;
  final String status;
  final String couponType;
  final DateTime expiryDate;
  final bool isTransferable;
  final String? brandName;

  const IssuerCouponModel({
    required this.id,
    required this.name,
    this.description,
    this.imageUrl,
    required this.faceValue,
    required this.currentPrice,
    required this.totalSupply,
    required this.remainingSupply,
    required this.category,
    required this.status,
    required this.couponType,
    required this.expiryDate,
    required this.isTransferable,
    this.brandName,
  });

  factory IssuerCouponModel.fromJson(Map<String, dynamic> json) {
    return IssuerCouponModel(
      id: json['id'] ?? '',
      name: json['name'] ?? '',
      description: json['description'],
      imageUrl: json['imageUrl'],
      faceValue: _toDouble(json['faceValue']),
      currentPrice: _toDouble(json['currentPrice']),
      totalSupply: json['totalSupply'] ?? 0,
      remainingSupply: json['remainingSupply'] ?? 0,
      category: json['category'] ?? '',
      status: json['status'] ?? '',
      couponType: json['couponType'] ?? 'utility',
      expiryDate: DateTime.tryParse(json['expiryDate']?.toString() ?? '') ?? DateTime.now(),
      isTransferable: json['isTransferable'] ?? true,
      brandName: json['issuer']?['companyName'] ?? json['brandName'],
    );
  }

  int get soldCount => totalSupply - remainingSupply;

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