import 'package:flutter/foundation.dart';
import 'package:dio/dio.dart';
import '../network/api_client.dart';
import '../services/cache_service.dart';
import '../models/api_response.dart';
import '../storage/storage_service.dart';

/// 增强版API服务，集成缓存功能
class EnhancedApiService {
  final ApiClient _apiClient = ApiClient.instance;
  
  /// GET请求，支持缓存
  Future<ApiResponse<T>> get<T>(
    String endpoint, {
    Map<String, dynamic>? queryParameters,
    bool useCache = true,
    Duration? cacheDuration,
    T Function(Map<String, dynamic>)? fromJson,
  }) async {
    try {
      // 生成缓存键
      final cacheKey = _generateCacheKey('GET', endpoint, queryParameters);
      
      // 尝试从缓存获取数据
      if (useCache) {
        final cachedData = await CacheService.getCache<T>(
          cacheKey,
          duration: cacheDuration,
          fromJson: fromJson,
        );
        
        if (cachedData != null) {
          if (kDebugMode) {
            print('Cache hit for: $endpoint');
          }
          return ApiResponse.success(
            data: cachedData,
            message: 'Data from cache',
          );
        }
      }
      
      // 发起网络请求
      final response = await _apiClient.get(
        endpoint,
        queryParameters: queryParameters,
      );
      
      if (response.statusCode == 200 && response.data != null) {
        // 缓存成功响应的数据
        if (useCache) {
          await CacheService.setCache(
            cacheKey,
            response.data,
            duration: cacheDuration,
          );
        }
        
        return ApiResponse.success(
          data: fromJson != null ? fromJson(response.data) : response.data,
          message: 'Success',
        );
      }
      
      return ApiResponse.error(
        message: 'Request failed with status: ${response.statusCode}',
        code: response.statusCode,
      );
    } catch (e) {
      if (kDebugMode) {
        print('Error in enhanced GET request: $e');
      }
      return ApiResponse.error(
        message: e.toString(),
      );
    }
  }
  
  /// POST请求
  Future<ApiResponse<T>> post<T>(
    String endpoint, {
    Map<String, dynamic>? data,
    bool invalidateCache = true,
    List<String>? cacheKeysToInvalidate,
    T Function(Map<String, dynamic>)? fromJson,
  }) async {
    try {
      final response = await _apiClient.post(
        endpoint,
        data: data,
      );
      
      if (response.statusCode == 200 || response.statusCode == 201) {
        // POST请求成功后，清除相关缓存
        if (invalidateCache) {
          await _invalidateRelatedCache(endpoint, cacheKeysToInvalidate);
        }
        
        return ApiResponse.success(
          data: fromJson != null && response.data != null ? fromJson(response.data) : response.data,
          message: 'Success',
        );
      }
      
      return ApiResponse.error(
        message: 'Request failed with status: ${response.statusCode}',
        code: response.statusCode,
      );
    } catch (e) {
      if (kDebugMode) {
        print('Error in enhanced POST request: $e');
      }
      return ApiResponse.error(
        message: e.toString(),
      );
    }
  }
  
  /// PUT请求
  Future<ApiResponse<T>> put<T>(
    String endpoint, {
    Map<String, dynamic>? data,
    bool invalidateCache = true,
    List<String>? cacheKeysToInvalidate,
    T Function(Map<String, dynamic>)? fromJson,
  }) async {
    try {
      final response = await _apiClient.put(
        endpoint,
        data: data,
      );
      
      if (response.statusCode == 200) {
        // PUT请求成功后，清除相关缓存
        if (invalidateCache) {
          await _invalidateRelatedCache(endpoint, cacheKeysToInvalidate);
        }
        
        return ApiResponse.success(
          data: fromJson != null && response.data != null ? fromJson(response.data) : response.data,
          message: 'Success',
        );
      }
      
      return ApiResponse.error(
        message: 'Request failed with status: ${response.statusCode}',
        code: response.statusCode,
      );
    } catch (e) {
      if (kDebugMode) {
        print('Error in enhanced PUT request: $e');
      }
      return ApiResponse.error(
        message: e.toString(),
      );
    }
  }
  
  /// DELETE请求
  Future<ApiResponse<T>> delete<T>(
    String endpoint, {
    bool invalidateCache = true,
    List<String>? cacheKeysToInvalidate,
  }) async {
    try {
      final response = await _apiClient.delete(
        endpoint,
      );
      
      if (response.statusCode == 200 || response.statusCode == 204) {
        // DELETE请求成功后，清除相关缓存
        if (invalidateCache) {
          await _invalidateRelatedCache(endpoint, cacheKeysToInvalidate);
        }
        
        return ApiResponse.success(
          data: null,
          message: 'Success',
        );
      }
      
      return ApiResponse.error(
        message: 'Request failed with status: ${response.statusCode}',
        code: response.statusCode,
      );
    } catch (e) {
      if (kDebugMode) {
        print('Error in enhanced DELETE request: $e');
      }
      return ApiResponse.error(
        message: e.toString(),
      );
    }
  }
  
  /// 生成缓存键
  String _generateCacheKey(
    String method,
    String endpoint,
    Map<String, dynamic>? queryParameters,
  ) {
    final buffer = StringBuffer();
    buffer.write(method);
    buffer.write('_');
    buffer.write(endpoint.replaceAll('/', '_'));
    
    if (queryParameters != null && queryParameters.isNotEmpty) {
      final sortedKeys = queryParameters.keys.toList()..sort();
      for (final key in sortedKeys) {
        buffer.write('_${key}_${queryParameters[key]}');
      }
    }
    
    return buffer.toString();
  }
  
  /// 清除相关缓存
  Future<void> _invalidateRelatedCache(
    String endpoint,
    List<String>? specificKeys,
  ) async {
    try {
      // 清除指定的缓存键
      if (specificKeys != null) {
        for (final key in specificKeys) {
          await CacheService.removeCache(key);
        }
      }
      
      // 清除与当前端点相关的缓存
      final endpointKey = endpoint.replaceAll('/', '_');
      final keys = StorageService.getKeys();
      final relatedKeys = keys.where((key) => key.contains(endpointKey));
      
      for (final key in relatedKeys) {
        final cacheKey = key.replaceFirst('api_cache_', '');
        await CacheService.removeCache(cacheKey);
      }
      
      if (kDebugMode) {
        print('Cache invalidated for endpoint: $endpoint');
      }
    } catch (e) {
      if (kDebugMode) {
        print('Error invalidating cache: $e');
      }
    }
  }
  
  /// 预加载数据到缓存
  Future<void> preloadCache(
    String endpoint, {
    Map<String, dynamic>? queryParameters,
    Duration? cacheDuration,
  }) async {
    try {
      await get(
        endpoint,
        queryParameters: queryParameters,
        useCache: true,
        cacheDuration: cacheDuration,
      );
      
      if (kDebugMode) {
        print('Cache preloaded for: $endpoint');
      }
    } catch (e) {
      if (kDebugMode) {
        print('Error preloading cache: $e');
      }
    }
  }
  
  /// 获取缓存信息
  Future<Map<String, int>> getCacheInfo() async {
    return await CacheService.getCacheInfo();
  }
  
  /// 清理过期缓存
  Future<void> cleanExpiredCache() async {
    await CacheService.cleanExpiredCache();
  }
  
  /// 清空所有缓存
  Future<void> clearAllCache() async {
    await CacheService.clearAllCache();
  }
}