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_controller.dart';
import 'package:clean/module/store/store_view.dart';
import 'package:clean/router/app_pages.dart';
import 'package:clean/utils/toast_util.dart';
import 'package:flutter/Material.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 PhotoSelectedPreviewController extends BasePhotoController {
  late PhotosType photosType;


  final RxBool isKeepAll = false.obs;
  final RxList<AssetEntity> selectedPhotos = <AssetEntity>[].obs;
  PhotoPreviewController photoPreviewController =
      Get.find<PhotoPreviewController>();

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

  // 从参数中获取照片类型和选中的照片ID集合
  _getArgs() {
    final parameters = Get.arguments;
    photosType = parameters?['photosType'];
    selectedPhotosIds.assignAll(parameters?['selectedIds'] ?? []);
  }

  // 加载选中的照片预览
  @override
  void loadPhotos() {
    photoGroups.clear();
    for (var assetsEntity in photoPreviewController.listAssetEntity) {
      if (selectedPhotosIds.contains(assetsEntity.id)) {
        selectedPhotos.add(assetsEntity);
      }
    }

    if (selectedPhotos.isNotEmpty) {
      photoGroups.add(PhotoGroup(
        isSelected: true,
        images: selectedPhotos,
      ));
    }
  }

  void clickBack() {
    print('PhotoSelectedPreviewController clickBack');
    photoPreviewController.updateSelections(selectedPhotosIds);

    Get.back();
  }

  @override
  clickImage(List<AssetEntity> images, int imageIndex, PhotosType type) {
    print("PhotoSelectedPreviewController clickImage");
  }

  @override
  void clickDelete() async {
    if (userRepository.isVip()) {
      if (selectedPhotosIds.isNotEmpty) {
        photoDeletingDialog();
        print(
            "PhotoSelectedPreviewController clickDelete selectedPhotosIds $selectedPhotosIds");
        final assetsToDelete = photoGroups
            .expand((group) => group.images
                .where((asset) => selectedPhotosIds.contains(asset.id)))
            .toList();

        final List<String> result = await PhotoManager.editor.deleteWithIds(
          assetsToDelete.map((e) => e.id).toList(),
        );

        if (result.length == selectedPhotosIds.length) {
          for (var group in photoGroups) {
            group.images.removeWhere(
                (element) => selectedPhotosIds.contains(element.id));

            // 更新 group 中的 selectedImages 状态
            group.selectedImages.value = group.images.map((image) {
              return selectedPhotosIds.contains(image.id);
            }).toList();

            // 更新 group.isSelected
            group.isSelected.value =
                group.selectedImages.every((selected) => selected);
          }

          photoPreviewController.selectedPhotosIds.assignAll(selectedPhotosIds);
          photoPreviewController.cleanSelections();

          ImagePickerUtil.updatePhotoGroupDate(
              getPhotosType(), selectedPhotosIds);
          selectedPhotosIds.clear();
          ToastUtil.show("Delete success");

          Future.delayed(Duration(seconds: 2), () {
            SmartDialog.dismiss(tag: 'photoDeletingDialog');
            photoDeleteFinishDialog(onDismiss: () {
              Get.until((route) => Get.currentRoute == RoutePath.mainTab);
            });
          });
        } else {
          SmartDialog.dismiss(tag: 'photoDeletingDialog');
          ToastUtil.show("Delete failed");
        }
      } else {
        isKeepAll.value = true;

        Future.delayed(Duration(seconds: 3), () {
          Get.until((route) => Get. currentRoute ==RoutePath.mainTab);
        });
      }
    } else {
      StorePage.start();
    }
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    isKeepAll.value = false;
  }

  @override
  PhotosType getPhotosType() => photosType;
}
