import 'dart:developer';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;

class NotifyImageCache {
  /// ✅ 根据 URL 生成缓存文件名（模仿你的 _getFileNameFromUrl）
  static String _fileNameFromUrl(String url) {
    try {
      Uri uri = Uri.parse(url);
      if (uri.pathSegments.isNotEmpty) {
        return uri.pathSegments.last;
      }
    } catch (_) {}
    return '${url.hashCode}.jpg';
  }

  /// ✅ 获取本地缓存路径（如果不存在则下载）
  static Future<String?> getCachedImage(String url) async {
    try {
      final dir = await getTemporaryDirectory();
      final fileName = _fileNameFromUrl(url);
      final filePath = '${dir.path}/libCachedImageData/$fileName';
      log(filePath);
      final file = File(filePath);

      // ✅ 已缓存：直接返回
      if (await file.exists()) return file.path;

      // ✅ 没缓存：下载
      final resp = await http.get(Uri.parse(url));
      if (resp.statusCode == 200) {
        await file.writeAsBytes(resp.bodyBytes);
        return file.path;
      }
    } catch (e) {
      print('缓存图片出错: $e');
    }
    return null;
  }
}
