import 'dart:io';

import 'package:clean/base/base_controller.dart';
import 'package:clean/base/base_photo_controller.dart';
import 'package:clean/data/bean/photos_type.dart';
import 'package:clean/data/repositories/user_repository.dart';
import 'package:clean/dialog/photo_delete_finish_dialog.dart';
import 'package:clean/dialog/photo_deleting_dialog.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/module/store/store_view.dart';
import 'package:clean/utils/toast_util.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class SimilarPhotoController extends BasePhotoController {
  @override
  void loadPhotos() {
    photoGroups.clear();
    photoGroups.addAll(
      ImagePickerUtil.similarPhotos.where((group) => group.isNotEmpty).map(
        (group) {
          return PhotoGroup(
            isSelected: true,
            images: group,
          );
        },
      ),
    );
    for (var group in photoGroups) {
      for (int i = 0; i < group.images.length; i++) {
        group.selectedImages[i] = i == 0 ? false : true;
        updateSelectedPhotosIds(group.images[i].id, i != 0);
      }
    }
    ImagePickerUtil.selectedSimilarPhotosIds.assignAll(selectedPhotosIds);
  }

  // 点击删除单组选中的图片
  void clickSingleGroupDelete(List<AssetEntity> images) async {
    if (userRepository.isVip()) {
      // 获取指定组
      final group = getGroupByImages(images);

      // 获取该组中所有选中的图片
      final selectedImages = group.images
          .where((image) => group.selectedImages[group.images.indexOf(image)])
          .toList();

      if (selectedImages.isEmpty) {
        ToastUtil.show('Please select the photo to delete');
        return;
      }

      photoDeletingDialog();
      try {
        // 执行删除操作
        final List<String> result = await PhotoManager.editor.deleteWithIds(
          selectedImages.map((e) => e.id).toList(),
        );

        // 检查删除成功的图片数量
        if (result.length == selectedImages.length) {
          // 先删除该组的图片，再更新selectedImages和selectedPhotosIds
          List<AssetEntity> imagesToRemove = [];
          List<int> indexesToRemove = [];

          for (var image in selectedImages) {
            // 找到图片在该组中的索引
            int index = group.images.indexOf(image);
            imagesToRemove.add(image);
            indexesToRemove.add(index);
          }

          // 从后往前删除，避免删除后索引错位
          for (int i = indexesToRemove.length - 1; i >= 0; i--) {
            int index = indexesToRemove[i];
            group.images.removeAt(index);
            group.selectedImages.removeAt(index);
          }

          // 如果当前组为空，则删除该组
          if (group.images.isEmpty) {
            photoGroups.remove(group);
          }

          // 更新选中的图片ID
          for (var image in imagesToRemove) {
            updateSelectedPhotosIds(image.id, false);
          }
          selectedFileCount.value = selectedPhotosIds.length;
          updateSelectedFilesSize();

          Future.delayed(Duration(seconds: 2), () {
            SmartDialog.dismiss(tag: 'photoDeletingDialog');
            photoDeleteFinishDialog();
          });

          ToastUtil.show("Delete success");
        } else {
          SmartDialog.dismiss(tag: 'photoDeletingDialog');
          ToastUtil.show("Delete failed");
        }
      } catch (e) {
        // 异常处理
        SmartDialog.dismiss(tag: 'photoDeletingDialog');
        ToastUtil.show("Error occurred during deletion: $e");
      }
    } else {
      StorePage.start();
    }
  }

  @override
  PhotosType getPhotosType() => PhotosType.similarPhotos;
}
