import 'dart:io';
import 'dart:convert';
import 'dart:typed_data';
import 'package:clean/utils/image_util.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_manager/photo_manager.dart';

import '../model/asset_info.dart';

class FileUtils {
  /// 获取 AssetEntity 保存目录
  static Future<String> getAssetPath() async {
    final directory = await getApplicationDocumentsDirectory();
    final path = '${directory.path}/assets';
    final dir = Directory(path);
    if (!dir.existsSync()) {
      dir.createSync(recursive: true);
    }
    return path;
  }

  /// 保存 AssetEntity 到本地
  static Future<AssetEntity?> saveAsset(AssetEntity asset) async {
    try {
      final assetPath = await getAssetPath();
      final title = asset.id.substring(0, 36);
      final assetFile = File('$assetPath/$title.json');

      // // 将 AssetEntity 转换为 AssetInfo 后再序列化
      // final assetInfo = AssetInfo.fromAssetEntity(asset);
      // await assetFile.writeAsString(jsonEncode(assetInfo.toJson()));

      // 保存原始图片文件
      final file = await asset.file;
      if (file != null) {
        final imageFile = File('$assetPath/$title.jpg');
        await imageFile.writeAsBytes(await file.readAsBytes());

        // 保存缩略图
        final thumbData = await asset.thumbnailDataWithSize(ThumbnailSize(200, 200));
        if (thumbData != null) {
          final thumbFile = File('$assetPath/${title}thumb.jpg');
          await thumbFile.writeAsBytes(thumbData);

          // 创建并保存 AssetInfo
          final assetInfo = AssetInfo.fromAssetEntity(asset, '$assetPath/$title.json', '$assetPath/${title}thumb.jpg');
          final assetFile = File('$assetPath/$title.json');
          await assetFile.writeAsString(jsonEncode(assetInfo.toJson()));
        }
      }

      return asset;
    } catch (e) {
      print('保存 AssetEntity 失败: $e');
      return null;
    }
  }

  /// 从本地读取图片数据
  static Future<Uint8List?> getImageData(int assetId) async {
    try {
      final assetPath = await getAssetPath();
      final imageFile = File('$assetPath/$assetId.jpg');
      if (await imageFile.exists()) {
        return await imageFile.readAsBytes();
      }
      return null;
    } catch (e) {
      print('读取图片数据失败: $e');
      return null;
    }
  }

  /// 从本地读取缩略图数据
  static Future<Uint8List?> getThumbData(String assetId) async {
    try {
      final assetPath = await getAssetPath();
      final thumbFile = File('$assetPath/${assetId}thumb.jpg');
      if (await thumbFile.exists()) {
        return await thumbFile.readAsBytes();
      }
      return null;
    } catch (e) {
      print('读取缩略图数据失败: $e');
      return null;
    }
  }

  /// 从本地读取 AssetEntity
  static Future<AssetEntity?> getAsset(String fileName) async {
    try {
      final assetPath = await getAssetPath();
      final assetFile = File('$assetPath/$fileName.json');
      if (await assetFile.exists()) {
        final jsonStr = await assetFile.readAsString();
        final json = jsonDecode(jsonStr);
        final assetInfo = AssetInfo.fromJson(json);
        return await assetInfo.toAssetEntity();
      }
      return null;
    } catch (e) {
      print('读取 AssetEntity 失败: $e');
      return null;
    }
  }

  /// 获取目录下所有 AssetEntity
  static Future<List<AssetInfo>> getAllAssets() async {
    try {
      final assetPath = await getAssetPath();
      final assetDir = Directory(assetPath);
      if (!await assetDir.exists()) {
        return [];
      }

      final List<AssetInfo> assets = [];
      final List<FileSystemEntity> entities = await assetDir.list().toList();

      for (var entity in entities) {
        if (entity is File && entity.path.endsWith('.json')) {
          final jsonStr = await entity.readAsString();
          final json = jsonDecode(jsonStr);
          final assetInfo = AssetInfo.fromJson(json);
          File? file = await ImageUtil.getImageFile(assetInfo);
          if (file != null) {
            assetInfo.size = await FileUtils.getFileSize(file);
          }
          assets.add(assetInfo);
        }
      }

      return assets;
    } catch (e) {
      print('获取所有 AssetEntity 失败: $e');
      return [];
    }
  }

  /// 删除 AssetEntity 文件
  static Future<bool> deleteAsset(String fileName) async {
    try {

      final assetPath = await getAssetPath();
      final assetFile = File('$assetPath/$fileName.json');
      if (await assetFile.exists()) {
        await assetFile.delete();
      }

      final assetFileImage = File('$assetPath/$fileName.jpg');
      if (await assetFileImage.exists()) {
        await assetFileImage.delete();
      }

      final assetFileIThumb = File('$assetPath/${fileName}thumb.jpg');
      if (await assetFileIThumb.exists()) {
        await assetFileIThumb.delete();
      }
      return true;
    } catch (e) {
      print('删除 AssetEntity 失败: $e');
      return false;
    }
  }

  // 获取文件大小
  static Future<int> getFileSize(File file) async {
    try {
      final bytes = await file.length();
      return bytes;
    } catch (e) {
      print('获取文件大小失败: $e');
      return 0;
    }
  }
}