
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/locations_photo/locations_photo_controller.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 LocationsSinglePhotoController extends BaseController {

  late final PhotoGroup photoGroup;
  final RxInt selectedFileCount = 0.obs;


  final RxList<PhotoGroup> photoGroups = <PhotoGroup>[].obs;
  final RxDouble selectedFilesSize = 0.0.obs;
  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    _getArgs();
    loadLocationsSinglePhoto();
    restoreSelections();

  }

  void clickImage(String location, int imageIndex) {
    final group = getGroupByLocation(location);
    final image = group.images[imageIndex];

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

  void toggleImageSelection(String groupTitle, int imageIndex) {
    final group = getGroupByLocation(groupTitle);
    final image = group.images[imageIndex];
    final selected = !group.selectedImages[imageIndex];

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

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

    updateSelectedFilesSize();
    selectedFileCount.value = ImagePickerUtil.selectedLocationPhotosIds.length;
  }

  Future<void> updateSelectedFilesSize() async {
    double totalSize = 0;

    for (var id in ImagePickerUtil.selectedLocationPhotosIds) {
      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 _updateSelectedScreenshotsPhotosIds(String photoId, bool isSelected) {
    if (isSelected) {
      ImagePickerUtil.selectedLocationPhotosIds.add(photoId);
    } else {
      ImagePickerUtil.selectedLocationPhotosIds.remove(photoId);
    }
  }

  // 获取参数
  void _getArgs() {
    photoGroup = parameters?['PhotoGroup'] as PhotoGroup;

  }
  void loadLocationsSinglePhoto() {
    photoGroups.clear();
    if (ImagePickerUtil.locationPhotos.isEmpty) {
      print('locationPhotos.isEmpty');
      return;
    }
    photoGroups.add(photoGroup);
  }

  void restoreSelections() async {
    final selectedIds = ImagePickerUtil.selectedLocationPhotosIds.toSet();

    for (var group in photoGroups) {
      for (int i = 0; i < group.images.length; i++) {
        group.selectedImages[i] = selectedIds.contains(group.images[i].id);
      }
      group.isSelected.value = group.selectedImages.every((selected) => selected);
    }
    await updateSelectedFilesSize();
    selectedFileCount.value = selectedIds.length;
  }

  void toggleGroupSelection(String location) {
    final group = getGroupByLocation(location);
    final newValue = !group.isSelected.value;
    group.toggleSelectAll(newValue);

    for (var image in group.images) {
      _updateSelectedScreenshotsPhotosIds(image.id, newValue);
    }

    updateSelectedFilesSize();
    selectedFileCount.value =  ImagePickerUtil.selectedLocationPhotosIds.length;
  }


  // 通过位置获取照片组
  PhotoGroup getGroupByLocation(String? location) {
    return photoGroups.firstWhere((group) => group.location == location);
  }


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

    if (ImagePickerUtil.selectedLocationPhotosIds.isNotEmpty) {
      final assetsToDelete = photoGroups.expand((group) =>
          group.images.where((asset) => ImagePickerUtil.selectedLocationPhotosIds.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.selectedLocationPhotosIds.length) {
        if (photoGroup.images.length == ImagePickerUtil.selectedLocationPhotosIds.length) {
          ImagePickerUtil.locationPhotos.remove(photoGroup.location);
        } else {
          photoGroup.images.removeWhere((element) => ImagePickerUtil.selectedLocationPhotosIds.contains(element.id));
        }
        ImagePickerUtil.updatePhotoGroupDate(PhotosType.locationPhotos, ImagePickerUtil.selectedLocationPhotosIds);
        ToastUtil.show("Delete success");
      } else {
        // 删除失败
        ToastUtil.show("Delete failed");
      }
    }
  }


}