import 'dart:convert';
import 'package:flutter/foundation.dart';
import '../storage/storage_service.dart';

/// API数据缓存服务
class CacheService {
  static const String _cachePrefix = 'api_cache_';
  static const String _timestampPrefix = 'cache_timestamp_';
  static const Duration _defaultCacheDuration = Duration(minutes: 30);

  /// 设置缓存
  static Future<void> setCache(
    String key,
    dynamic data, {
    Duration? duration,
  }) async {
    try {
      final cacheKey = _cachePrefix + key;
      final timestampKey = _timestampPrefix + key;
      
      // 存储数据
      final jsonData = jsonEncode(data);
      await StorageService.setString(cacheKey, jsonData);
      
      // 存储时间戳
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      await StorageService.setInt(timestampKey, timestamp);
      
      if (kDebugMode) {
        print('Cache set for key: $key');
      }
    } catch (e) {
      if (kDebugMode) {
        print('Error setting cache for key $key: $e');
      }
    }
  }

  /// 获取缓存
  static Future<T?> getCache<T>(
    String key, {
    Duration? duration,
    T Function(Map<String, dynamic>)? fromJson,
  }) async {
    try {
      final cacheKey = _cachePrefix + key;
      final timestampKey = _timestampPrefix + key;
      
      // 检查缓存是否存在
      final cachedData = await StorageService.getString(cacheKey);
      final timestamp = await StorageService.getInt(timestampKey);
      
      if (cachedData == null || timestamp == null) {
        return null;
      }
      
      // 检查缓存是否过期
      final cacheDuration = duration ?? _defaultCacheDuration;
      final cacheTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
      final now = DateTime.now();
      
      if (now.difference(cacheTime) > cacheDuration) {
        // 缓存过期，删除缓存
        await removeCache(key);
        return null;
      }
      
      // 解析数据
      final jsonData = jsonDecode(cachedData);
      
      if (fromJson != null && jsonData is Map<String, dynamic>) {
        return fromJson(jsonData);
      }
      
      return jsonData as T;
    } catch (e) {
      if (kDebugMode) {
        print('Error getting cache for key $key: $e');
      }
      return null;
    }
  }

  /// 获取列表缓存
  static Future<List<T>?> getListCache<T>(
    String key, {
    Duration? duration,
    required T Function(Map<String, dynamic>) fromJson,
  }) async {
    try {
      final cacheKey = _cachePrefix + key;
      final timestampKey = _timestampPrefix + key;
      
      // 检查缓存是否存在
      final cachedData = await StorageService.getString(cacheKey);
      final timestamp = await StorageService.getInt(timestampKey);
      
      if (cachedData == null || timestamp == null) {
        return null;
      }
      
      // 检查缓存是否过期
      final cacheDuration = duration ?? _defaultCacheDuration;
      final cacheTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
      final now = DateTime.now();
      
      if (now.difference(cacheTime) > cacheDuration) {
        // 缓存过期，删除缓存
        await removeCache(key);
        return null;
      }
      
      // 解析数据
      final jsonData = jsonDecode(cachedData);
      
      if (jsonData is List) {
        return jsonData
            .map((item) => fromJson(item as Map<String, dynamic>))
            .toList();
      }
      
      return null;
    } catch (e) {
      if (kDebugMode) {
        print('Error getting list cache for key $key: $e');
      }
      return null;
    }
  }

  /// 检查缓存是否有效
  static Future<bool> isCacheValid(
    String key, {
    Duration? duration,
  }) async {
    try {
      final timestampKey = _timestampPrefix + key;
      final timestamp = await StorageService.getInt(timestampKey);
      
      if (timestamp == null) {
        return false;
      }
      
      final cacheDuration = duration ?? _defaultCacheDuration;
      final cacheTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
      final now = DateTime.now();
      
      return now.difference(cacheTime) <= cacheDuration;
    } catch (e) {
      return false;
    }
  }

  /// 移除缓存
  static Future<void> removeCache(String key) async {
    try {
      final cacheKey = _cachePrefix + key;
      final timestampKey = _timestampPrefix + key;
      
      await StorageService.remove(cacheKey);
      await StorageService.remove(timestampKey);
      
      if (kDebugMode) {
        print('Cache removed for key: $key');
      }
    } catch (e) {
      if (kDebugMode) {
        print('Error removing cache for key $key: $e');
      }
    }
  }

  /// 清空所有缓存
  static Future<void> clearAllCache() async {
    try {
      final keys = StorageService.getKeys();
      final cacheKeys = keys.where((key) => 
          key.startsWith(_cachePrefix) || key.startsWith(_timestampPrefix));
      
      for (final key in cacheKeys) {
        await StorageService.remove(key);
      }
      
      if (kDebugMode) {
        print('All cache cleared');
      }
    } catch (e) {
      if (kDebugMode) {
        print('Error clearing all cache: $e');
      }
    }
  }

  /// 获取缓存大小信息
  static Future<Map<String, int>> getCacheInfo() async {
    try {
      final keys = StorageService.getKeys();
      final cacheKeys = keys.where((key) => key.startsWith(_cachePrefix));
      final timestampKeys = keys.where((key) => key.startsWith(_timestampPrefix));
      
      int totalSize = 0;
      for (final key in cacheKeys) {
        final data = await StorageService.getString(key);
        if (data != null) {
          totalSize += data.length;
        }
      }
      
      return {
        'count': cacheKeys.length,
        'size': totalSize,
        'timestamps': timestampKeys.length,
      };
    } catch (e) {
      return {
        'count': 0,
        'size': 0,
        'timestamps': 0,
      };
    }
  }

  /// 清理过期缓存
  static Future<void> cleanExpiredCache() async {
    try {
      final keys = StorageService.getKeys();
      final timestampKeys = keys.where((key) => key.startsWith(_timestampPrefix));
      
      for (final timestampKey in timestampKeys) {
        final timestamp = await StorageService.getInt(timestampKey);
        if (timestamp != null) {
          final cacheTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
          final now = DateTime.now();
          
          if (now.difference(cacheTime) > _defaultCacheDuration) {
            final cacheKey = timestampKey.replaceFirst(_timestampPrefix, _cachePrefix);
            await StorageService.remove(cacheKey);
            await StorageService.remove(timestampKey);
          }
        }
      }
      
      if (kDebugMode) {
        print('Expired cache cleaned');
      }
    } catch (e) {
      if (kDebugMode) {
        print('Error cleaning expired cache: $e');
      }
    }
  }
}