import 'dart:io';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:path_provider/path_provider.dart';

class SCAppUtils {


  // 递归计算文件夹大小
  static Future<double> _gs(Directory folder) async {
    try {
      if (!await folder.exists()) return 0;

      double size = 0;
      final files = folder.listSync(recursive: true);

      for (var file in files) {
        if (file is File) {
          try {
            final stat = await file.stat();
            size += stat.size;
          } catch (e) {
            // 忽略无法访问的文件
          }
        }
      }

      return size;
    } catch (e) {
      print('计算文件夹大小出错: ${folder.path} - $e');
      return 0;
    }
  }


  // 删除文件夹
  static Future<void> _dd(Directory folder) async {
    try {
      if (await folder.exists()) {
        await folder.delete(recursive: true);
      }
    } catch (e) {
      print('删除文件夹失败: ${folder.path} - $e');
    }
  }

  // 清理 Dio 缓存
  static Future<void> _cd() async {
    try {
      final dioCacheDir = Directory(
        '${(await getTemporaryDirectory()).path}/dio_cache',
      );
      if (await dioCacheDir.exists()) {
        await dioCacheDir.delete(recursive: true);
      }
    } catch (e) {
      print('清理Dio缓存出错: $e');
    }
  }

  // 清理图片缓存
  static Future<void> _ci() async {
    try {
      // 清理 cached_network_image 缓存
      final imageCache = PaintingBinding.instance?.imageCache;
      if (imageCache != null) {
        imageCache.clear();
        imageCache.clearLiveImages();
      }
      await clearDiskCachedImages();
    } catch (e) {
      print('清理图片缓存出错: $e');
    }
  }

  // 格式化缓存大小显示
  static String _fs(double size) {
    if (size <= 0) return "0 B";

    const units = ["B", "KB", "MB", "GB"];
    int unitIndex = 0;

    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024;
      unitIndex++;
    }

    return "${size.toStringAsFixed(2)} ${units[unitIndex]}";
  }
}
