import 'package:clean/base/base_controller.dart';
import 'package:clean/data/bean/photos_type.dart';
import 'package:clean/module/image_picker/image_picker_util.dart';
import 'package:clean/module/people_photo/photo_group.dart';
import 'package:clean/module/photo_preview/photo_preview_view.dart';
import 'package:clean/utils/toast_util.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class PeoplePhotoController extends BaseController {
  final RxList<PhotoGroup> photoGroups = <PhotoGroup>[].obs;
  final RxDouble selectedFilesSize = 0.0.obs;
  final RxInt selectedFileCount = 0.obs;

  @override
  void onInit() {
    super.onInit();
    loadPeoplePhoto();
    restoreSelections();
  }

  @override
  void onReady() {
    super.onReady();
  }

  Future<void> updateSelectedFilesSize() async {
    double totalSize = 0;
    // 通过selectedPhotosIds获取选中的图片，然后计算大小
    for (var id in ImagePickerUtil.selectedPeoplePhotosIds) {
      final entity = await AssetEntity.fromId(id);
      if (entity != null) {
        final file = await entity.file;
        if (file != null) {
          totalSize += await file.length();
        }
      }
    }

    selectedFilesSize.value = totalSize / 1024; // Convert to KB
  }

  void toggleImageSelection(
      List<AssetEntity> groupTitle, int imageIndex) async {
    final group = getGroupByImages(groupTitle);
    final image = group.images[imageIndex];
    final selected = !group.selectedImages[imageIndex];

    group.selectedImages[imageIndex] = selected;
    _updateSelectedPeoplePhotosIds(image.id, selected);

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

    selectedFileCount.value = ImagePickerUtil.selectedPeoplePhotosIds.length;
    await updateSelectedFilesSize();
  }

  void clickImage(List<AssetEntity> images, int imageIndex) {
    final group = getGroupByImages(images);
    final image = group.images[imageIndex];

    PhotoPreviewPage.start(PhotosType.peoplePhotos, image.id);
  }

  void toggleGroupSelection(List<AssetEntity> images) async {
    final group = getGroupByImages(images);
    final newValue = !group.isSelected.value;
    group.toggleSelectAll(newValue);

    for (var image in group.images) {
      _updateSelectedPeoplePhotosIds(image.id, newValue);
    }
    selectedFileCount.value = ImagePickerUtil.selectedPeoplePhotosIds.length;
    updateSelectedFilesSize();
  }

  PhotoGroup getGroupByImages(List<AssetEntity> images) {
    final imageIds = images.map((img) => img.id).toSet();
    return photoGroups.firstWhere(
        (group) => group.images.every((image) => imageIds.contains(image.id)));
  }

  void _updateSelectedPeoplePhotosIds(String photoId, bool isSelected) {
    if (isSelected) {
      // 检查这个id有没有在这个list里面
      if (!ImagePickerUtil.selectedPeoplePhotosIds.contains(photoId)) {
        ImagePickerUtil.selectedPeoplePhotosIds.add(photoId);
      }
    } else {
      ImagePickerUtil.selectedPeoplePhotosIds.remove(photoId);
    }
  }

  void restoreSelections() async {
    print("PeoplePhotoController  restoreSelections");

    for (var group in photoGroups) {
      for (int i = 0; i < group.images.length; i++) {
        if (ImagePickerUtil.selectedPeoplePhotosIds
            .contains(group.images[i].id)) {
          group.selectedImages[i] = true;
        } else {
          group.selectedImages[i] = false;
        }
      }
      group.isSelected.value =
          group.selectedImages.every((selected) => selected);
    }
    updateSelectedFilesSize();
    selectedFileCount.value = ImagePickerUtil.selectedPeoplePhotosIds.length;
  }

  void loadPeoplePhoto() {
    print("loadPeoplePhoto");
    photoGroups.clear();

    final photoGroup = ImagePickerUtil.peoplePhotos;
    if (photoGroup.isNotEmpty) {
      photoGroups.add(PhotoGroup(
        isSelected: false,
        images: photoGroup,
      ));
    }
  }

  clickDelete() async {
    print('clickDelete');

    if (ImagePickerUtil.selectedPeoplePhotosIds.isNotEmpty) {
      // 获取要删除的资产
      final assetsToDelete = ImagePickerUtil.peoplePhotos
          .where(
            (asset) =>
                ImagePickerUtil.selectedPeoplePhotosIds.contains(asset.id),
          )
          .toList();

      // 调用方法会返回被删除的资源，如果全部失败会返回空列表。
      final List<String> result = await PhotoManager.editor.deleteWithIds(
        assetsToDelete.map((e) => e.id).toList(),
      );
      print('PhotoPreviewController result $result');

      if (result.length == ImagePickerUtil.selectedPeoplePhotosIds.length) {
        // 删除成功
        ToastUtil.show("Delete success");
        ImagePickerUtil.updatePhotoGroupDate(PhotosType.peoplePhotos,ImagePickerUtil.selectedPeoplePhotosIds);
      } else {
        // 删除失败
        ToastUtil.show("Delete failed");
      }
    }
  }
}
