import 'package:clean/base/base_controller.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../image_picker/image_picker_util.dart';
import '../people_photo/photo_group.dart';

class CalendarMonthController extends BaseController {
  late final Rx<PhotoGroup> photoGroup =
      PhotoGroup(isSelected: false, images: []).obs;
  final RxDouble selectedFilesSize = 0.0.obs;
  RxInt selectedFileCount = 0.obs;
  final RxSet<String> selectedPhotosIds = <String>{}.obs;

  // 是否是选择模式
  RxBool isSelectMode = false.obs;

  @override
  void onInit() {
    _getArgs();
    super.onInit();
  }

  void _getArgs() {
    final parameters = Get.arguments;
    photoGroup.value = parameters?['PhotoGroup'] as PhotoGroup;
  }

  clickBack() {
    print('CalendarMonthController clickBack');
    Get.back();
  }

  // 切换图片组选中状态
  void toggleGroupSelection(List<AssetEntity> imagesList) {
    final newValue = !photoGroup.value.isSelected.value;
    photoGroup.value.toggleSelectAll(newValue);

    for (var image in photoGroup.value.images) {
      updateSelectedPhotosIds(image.id, newValue);
    }
    selectedFileCount.value = selectedPhotosIds.length;
    updateSelectedFilesSize();
  }

  Future<void> updateSelectedFilesSize() async {
    // 如果没有选中的文件，直接返回
    if (selectedFileCount.value == 0) {
      selectedFilesSize.value = 0;
      return;
    }
    double totalSize = 0;

    for (int i = 0; i < photoGroup.value.images.length; i++) {
      if (photoGroup.value.selectedImages[i]) {
        // 检查缓存
        final assetId = photoGroup.value.images[i].id;
        if (ImagePickerUtil.fileSizeCache.containsKey(assetId)) {
          totalSize += ImagePickerUtil.fileSizeCache[assetId]!;
        } else {
          final file = await photoGroup.value.images[i].file;
          if (file != null) {
            final size = (await file.length()) / 1024; // 转换为KB
            totalSize += size;
            ImagePickerUtil.fileSizeCache[assetId] = size;
          }
        }
      }
    }

    selectedFilesSize.value = totalSize;
    print("selectedFilesSize: $selectedFilesSize");
    PhotoManager.clearFileCache();
  }

  void updateSelectedPhotosIds(String photoId, bool isSelected) {
    if (isSelected) {
      selectedPhotosIds.add(photoId);
    } else {
      selectedPhotosIds.remove(photoId);
    }
  }

  clickImage(List<AssetEntity> images, int imageIndex) {
    print("CalendarMonthController clickImage");
  }

  Future<void> toggleImageSelection(
      List<AssetEntity> groupTitle, int imageIndex) async {
    print("BasePhotoController toggleImageSelection");

    final image = photoGroup.value.images[imageIndex];
    final selected = !photoGroup.value.selectedImages[imageIndex];

    photoGroup.value.selectedImages[imageIndex] = selected;
    updateSelectedPhotosIds(image.id, selected);

    photoGroup.value.isSelected.value =
        photoGroup.value.selectedImages.every((selected) => selected);

    selectedFileCount.value = selectedPhotosIds.length;

    // 更新文件大小
    if (selected) {
      // 如果选中，增加文件大小
      if (ImagePickerUtil.fileSizeCache.containsKey(image.id)) {
        selectedFilesSize.value += ImagePickerUtil.fileSizeCache[image.id]!;
      } else {
        final file = await image.file;
        if (file != null) {
          selectedFilesSize.value += (await file.length()) / 1024; // 转换为KB
        }
      }
    } else {
      // 如果取消选中，减少文件大小
      if (ImagePickerUtil.fileSizeCache.containsKey(image.id)) {
        selectedFilesSize.value -= ImagePickerUtil.fileSizeCache[image.id]!;
      } else {
        final file = await image.file;
        if (file != null) {
          selectedFilesSize.value -= (await file.length()) / 1024; // 转换为KB
        }
      }
    }

    PhotoManager.clearFileCache();
  }

  // 将selectedFilesSize转成String类型,然后单位转换,如果超过1MB,则转成MB,超过1GB,则转成GB,否则KB
  String get selectedFilesSizeString {
    if (selectedFilesSize.value > 1024) {
      return "${(selectedFilesSize.value / 1024).toStringAsFixed(2)}MB";
    } else if (selectedFilesSize.value > 1024 * 1024) {
      return "${(selectedFilesSize.value / 1024 / 1024).toStringAsFixed(2)}GB";
    } else {
      return "${(selectedFilesSize.value).toStringAsFixed(2)}KB";
    }
  }
}
