import 'dart:io';
import 'dart:math';

import 'package:clean/model/asset_group.dart';
import 'package:get/get.dart';
import 'package:photo_manager/photo_manager.dart';

class ImagePickerUtil {
  ImagePickerUtil._();

  static const RequestType permissionType = RequestType.image;

  // 全局存储不同类型的照片
  // 截图图片
  static final RxList<AssetEntity> screenshotPhotos = <AssetEntity>[].obs;

  // 相似图片
  static final RxList<List<AssetEntity>> similarPhotos =
      <List<AssetEntity>>[].obs;

  // 地点图片
  static final RxMap<String, List<AssetEntity>> locationPhotos =
      <String, List<AssetEntity>>{}.obs;

  // 人物图片
  static final RxList<AssetEntity> peoplePhotos = <AssetEntity>[].obs;

  // 添加大小信息的变量
  static final Rx<int> screenshotsSize = 0.obs;
  static final Rx<int> locationsSize = 0.obs;
  static final Rx<int> peopleSize = 0.obs;
  static final Rx<int> similarPhotosSize = 0.obs;

  // 清除所有照片数据
  static void clearAllPhotos() {
    screenshotPhotos.clear();
    similarPhotos.clear();
    locationPhotos.clear();
    peoplePhotos.clear();
  }

  // 更新照片数据
  static Future<void> updatePhotos(
      List<Map<String, dynamic>> photoGroups) async {
    clearAllPhotos();

    for (var group in photoGroups) {
      String type = group['type'] as String;
      Map<dynamic, dynamic> groupData = group['group'] as Map<dynamic, dynamic>;
      List<dynamic> photos = groupData['photos'] as List<dynamic>;
      int totalSize = groupData['totalSize'] as int;
      int count = groupData['count'] as int;

      switch (type) {
        case 'screenshots':
          screenshotPhotos.value = await _convertToAssetEntities(photos);
          screenshotsSize.value = totalSize;
          break;
        case 'similar':
          similarPhotos.add(await _convertToAssetEntities(photos));
          similarPhotosSize.value = totalSize;
          break;
        case 'location':
          String location = group['name'] as String;
          locationPhotos[location] = await _convertToAssetEntities(photos);
          locationsSize.value = totalSize;
          break;
        case 'people':
          peoplePhotos.value = await _convertToAssetEntities(photos);
          peopleSize.value = totalSize;
          break;
      }
    }
  }

  // 将原始照片数据转换为 AssetEntity 列表
  static Future<List<AssetEntity>> _convertToAssetEntities(
      List<dynamic> photos) async {
    List<AssetEntity> entities = [];
    for (var photo in photos) {
      final entity = await AssetEntity.fromId(photo['id'] as String);
      if (entity != null) {
        entities.add(entity);
      }
    }
    return entities;
  }

  //申请权限
  static Future<bool> requestPermissionExtend() async {
    final PermissionState ps = await PhotoManager.requestPermissionExtend(
        requestOption: const PermissionRequestOption(
            androidPermission: AndroidPermission(
      type: permissionType,
      mediaLocation: false,
    )));
    return ps.hasAccess;
  }

  //判断是否有权限
  static Future<bool> hasPermission() async {
    final PermissionState ps = await PhotoManager.getPermissionState(
        requestOption: const PermissionRequestOption(
            androidPermission: AndroidPermission(
      type: permissionType,
      mediaLocation: false,
    )));
    return ps.hasAccess;
  }

  static String formatFileSize(int bytes, {int decimals = 2}) {
    if (bytes <= 0) return '0 B';

    const suffixes = ['B', 'KB', 'MB', 'GB', 'TB'];
    var i = (log(bytes) / log(1024)).floor();

    // 确保不超过数组范围
    i = i < suffixes.length ? i : suffixes.length - 1;

    // 计算实际大小
    final size = bytes / pow(1024, i);

    // 格式化数字，处理小数点位数
    String sizeStr;
    if (size >= 100) {
      // 大于100的只保留整数
      sizeStr = size.round().toString();
    } else {
      // 小于100的保留指定小数位
      sizeStr = size.toStringAsFixed(decimals);
    }

    // 移除末尾的0和不必要的小数点
    sizeStr = sizeStr.replaceAll(RegExp(r'\.?0+$'), '');

    return '$sizeStr ${suffixes[i]}';
  }

  /// 直接转换为 GB 单位
  static String formatToGB(int bytes, {int decimals = 2}) {
    if (bytes <= 0) return '0 GB';

    final gb = bytes / pow(1024, 3); // 直接转换为 GB

    // 格式化数字，处理小数点位数
    String sizeStr;
    if (gb >= 100) {
      // 大于100的只保留整数
      sizeStr = gb.round().toString();
    } else {
      // 小于100的保留指定小数位
      sizeStr = gb.toStringAsFixed(decimals);
    }

    // 移除末尾的0和不必要的小数点
    sizeStr = sizeStr.replaceAll(RegExp(r'\.?0+$'), '');

    return '$sizeStr GB';
  }
}
