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';

enum FileType {
  analysis, // 照片分析
  privacy,  // 隐私空间
}

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

  /// 保存 AssetEntity 到本地
  static Future<AssetEntity?> saveAsset(FileType type, AssetEntity asset) async {
    try {
      final assetPath = await getAssetPath(type);
      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.PNG');
        await imageFile.writeAsBytes(await file.readAsBytes());

        final originalFile = await asset.originFile;
        final originalPath = originalFile?.path;

        var mediaPath = "/var/mobile/Media/DCIM/100APPLE/";
        if (originalPath != null) {
          // 查找 "o_" 的位置
          final int index = originalPath.lastIndexOf('_o_');
          if (index != -1) {
            // 截取 "o_" 后面的字符串
            mediaPath += originalPath.substring(index + 3);
            mediaPath = mediaPath.replaceAll("jpg", "PNG");
          }
        }

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

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

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

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

  /// 从本地读取 AssetEntity
  // static Future<AssetEntity?> getAsset(FileType type, 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(FileType type) async {
    try {
      final assetPath = await getAssetPath(type);
      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(type, 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(FileType type, String fileName) async {
    try {

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

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

      final assetFileIThumb = File('$assetPath/${fileName}thumb.PNG');
      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;
    }
  }
}