import 'dart:async';

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_single_photo_controller.dart';
import 'package:clean/module/people_photo/people_photo_controller.dart';
import 'package:clean/module/people_photo/photo_group.dart';
import 'package:clean/module/photo_preview/phtoto_selected_preview_view.dart';
import 'package:clean/module/screenshots_blurry/screenshots_controller.dart';
import 'package:clean/module/similar_photo/similar_photo_controller.dart';
import 'package:clean/utils/file_utils.dart';
import 'package:clean/utils/toast_util.dart';
import 'package:flutter/Material.dart';
import 'package:flutter_card_swiper/flutter_card_swiper.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class PhotoPreviewController extends BaseController {
  Rx<CardSwiperController> cardSwiperController = CardSwiperController().obs;
  final RxList<AssetEntity> photoGroups = <AssetEntity>[].obs;
  final RxSet<String> selectedPhotosIds = <String>{}.obs;
  final RxBool isSwiperEnd = false.obs;
  RxInt groupIndex = 0.obs;

  late PhotosType photosType;
  late String? currentImageId;
  RxDouble selectedFilesSize = 0.0.obs;
  RxInt selectedFileCount = 0.obs;

  @override
  void onInit() {
    super.onInit();
    isSwiperEnd.value = false;
    print('PhotoPreviewController onInit');
    _getArgs(); // 获取传递的参数
    _initData(); // 初始化数据

    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (currentImageId != null) {
        for (int i = 0; i < photoGroups.length; i++) {
          if (photoGroups[i].id == currentImageId) {
            print('photoGroups[i].id ${photoGroups[i].id},i $i');
            groupIndex.value = i;
            cardSwiperController.value.moveTo(i);
            break;
          }
        }
      }
    });
  }

  // 获取参数
  void _getArgs() {
    photosType = parameters?['photosType'];
    currentImageId = parameters?['currentImageId'];
  }

  void _initData() {
    photoGroups.clear();
    selectedPhotosIds.clear();

    switch (photosType) {
      case PhotosType.peoplePhotos:
        photoGroups.assignAll(ImagePickerUtil.peoplePhotos);
        selectedPhotosIds.assignAll(ImagePickerUtil.selectedPeoplePhotosIds);
        selectedFileCount.value =
            ImagePickerUtil.selectedPeoplePhotosIds.length;
        break;
      case PhotosType.screenshots:
        photoGroups.assignAll(ImagePickerUtil.screenshotPhotos);
        selectedPhotosIds
            .assignAll(ImagePickerUtil.selectedScreenshotPhotosIds);
        selectedFileCount.value =
            ImagePickerUtil.selectedScreenshotPhotosIds.length;
        break;
      case PhotosType.similarPhotos:
        for (var group in ImagePickerUtil.similarPhotos) {
          photoGroups.addAll(group);
        }
        selectedPhotosIds.assignAll(ImagePickerUtil.selectedSimilarPhotosIds);
        selectedFileCount.value =
            ImagePickerUtil.selectedSimilarPhotosIds.length;
        break;
      case PhotosType.locationPhotos:
        for (var group in ImagePickerUtil.locationPhotos.values) {
          photoGroups.addAll(group);
        }
        selectedPhotosIds.assignAll(ImagePickerUtil.selectedLocationPhotosIds);
        selectedFileCount.value =
            ImagePickerUtil.selectedLocationPhotosIds.length;
        break;
      case PhotosType.blurryPhotos:
        photoGroups.assignAll(ImagePickerUtil.blurryPhotos);
        selectedPhotosIds.assignAll(ImagePickerUtil.selectedBlurryPhotosIds);
        selectedFileCount.value =
            ImagePickerUtil.selectedBlurryPhotosIds.length;
        break;
    }
    updateSelectedFilesSize();
  }

  void restoreSelections() async {

    photoGroups.removeWhere((element) => selectedPhotosIds.contains(element.id));
    selectedPhotosIds.clear();
    if (photoGroups.isNotEmpty) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        groupIndex.value = 0;
        cardSwiperController.value.moveTo(0);
      });

    }
    updateSelectedFilesSize();
    selectedFileCount.value = selectedPhotosIds.length;
  }

  Future<void> updateSelectedFilesSize() async {
    double totalSize = 0;
    // 通过selectedPhotosIds获取选中的图片，然后计算大小
    for (var id in selectedPhotosIds) {
      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 recoverSelectPhoto() {
    cardSwiperController.value.undo();
  }

  void clickSelect() {
    cardSwiperController.value.swipe(CardSwiperDirection.left);
  }

  @override
  void onClose() {
    super.onClose();

    // 清理操作，释放资源
    cardSwiperController.value.dispose();
  }

  void clickBack() {
    _saveSelectedPhotos(photosType);
    Get.back();
  }

  // // 保存选择的图片ID列表
  void _saveSelectedPhotos(PhotosType type) {
    switch (type) {
      case PhotosType.peoplePhotos:
        ImagePickerUtil.selectedPeoplePhotosIds.assignAll(selectedPhotosIds);
        PeoplePhotoController controller = Get.find<PeoplePhotoController>();
        controller.restoreSelections();
        break;
      case PhotosType.screenshots:
        ImagePickerUtil.selectedScreenshotPhotosIds
            .assignAll(selectedPhotosIds);
        ScreenShotsController controller = Get.find<ScreenShotsController>();
        controller.restoreSelections();
        break;
      case PhotosType.similarPhotos:
        ImagePickerUtil.selectedSimilarPhotosIds.assignAll(selectedPhotosIds);
        SimilarPhotoController controller = Get.find<SimilarPhotoController>();

        controller.restoreSelections();
        break;
      case PhotosType.locationPhotos:
        ImagePickerUtil.selectedLocationPhotosIds.assignAll(selectedPhotosIds);
        LocationsSinglePhotoController controller =
            Get.find<LocationsSinglePhotoController>();

        controller.restoreSelections();
        break;
      case PhotosType.blurryPhotos:
        ImagePickerUtil.selectedBlurryPhotosIds.assignAll(selectedPhotosIds);
        ScreenShotsController controller = Get.find<ScreenShotsController>();

        controller.restoreSelections();
        break;
    }
  }

  void clickUnselect() {
    print("clickUnselect");
    cardSwiperController.value.swipe(CardSwiperDirection.right);
  }

  FutureOr<bool> onSwipe(
    int previousIndex,
    int? currentIndex,
    CardSwiperDirection direction,
  ) {
    print(
      'The card $previousIndex was swiped to the ${direction.name}. Now the card $currentIndex is on top',
    );
    if (currentIndex != null) {
      groupIndex.value = currentIndex;
    }
    // 如果direction是left，
    if (direction == CardSwiperDirection.left) {
      //   先看看图片id是不是在selectedPhotosIds里面，如果在，不处理，如果不在，添加到selectedPhotosIds里面
      if (!selectedPhotosIds.contains(photoGroups[previousIndex].id)) {
        print(
            'add photoGroups[groupIndex.value].id ${photoGroups[previousIndex].id}');
        selectedPhotosIds.add(photoGroups[previousIndex].id);
      }
    } else if (direction == CardSwiperDirection.right) {
      //   先看看图片id是不是在selectedPhotosIds里面，如果在，在selectedPhotosIds移除，不处理，如果不在，不处理
      if (selectedPhotosIds.contains(photoGroups[previousIndex].id)) {
        print(
            'remove photoGroups[groupIndex.value].id ${photoGroups[previousIndex].id}');
        selectedPhotosIds.remove(photoGroups[previousIndex].id);
      }
    }
    selectedFileCount.value = selectedPhotosIds.length;
    updateSelectedFilesSize();
    return true;
  }

  bool onSwiperUndo(
    int? previousIndex,
    int currentIndex,
    CardSwiperDirection direction,
  ) {
    print(
        'The card $currentIndex was swiped back to the ${direction.name}. Now the card $previousIndex is on top');

    groupIndex.value = currentIndex;
    //   撤销之前左滑的操作
    if (direction == CardSwiperDirection.left) {
      print(
          'photoGroups[groupIndex.value].id ${photoGroups[groupIndex.value].id}');
      if (selectedPhotosIds.contains(photoGroups[groupIndex.value].id)) {
        selectedPhotosIds.remove(photoGroups[groupIndex.value].id);
      }
    }
    selectedFileCount.value = selectedPhotosIds.length;
    updateSelectedFilesSize();
    return true;
  }

  onSwiperEnd() {
    isSwiperEnd.value = true;
    print('onSwiperEnd');

    PhotoSelectedPreviewPage.start(photosType, selectedPhotosIds);
  }

  clickDelete() async {
    print('clickDelete');
    switch (photosType) {
      case PhotosType.peoplePhotos:
        ImagePickerUtil.selectedPeoplePhotosIds.assignAll(selectedPhotosIds);
        break;
      case PhotosType.screenshots:
        ImagePickerUtil.selectedScreenshotPhotosIds
            .assignAll(selectedPhotosIds);
        break;
      case PhotosType.similarPhotos:
        ImagePickerUtil.selectedSimilarPhotosIds.assignAll(selectedPhotosIds);
        break;
      case PhotosType.locationPhotos:
        ImagePickerUtil.selectedLocationPhotosIds.assignAll(selectedPhotosIds);
        break;
      case PhotosType.blurryPhotos:
        ImagePickerUtil.selectedBlurryPhotosIds.assignAll(selectedPhotosIds);
        break;
    }
    if (selectedPhotosIds.isNotEmpty) {
      // 获取要删除的资产
      final assetsToDelete = photoGroups
          .where(
            (asset) => selectedPhotosIds.contains(asset.id),
          )
          .toList();

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

      //   比较result和selectedPhotosIds，如果result和selectedPhotosIds相等，说明删除成功，走下面的逻辑
      // 如果不相等，说明有删除失败的，走else逻辑
      if (result.length == selectedPhotosIds.length) {
        switch (photosType) {
          case PhotosType.peoplePhotos:
            ImagePickerUtil.updatePhotoGroupDate(photosType,ImagePickerUtil.selectedPeoplePhotosIds);

            break;
          case PhotosType.screenshots:
            ImagePickerUtil.updatePhotoGroupDate(photosType,ImagePickerUtil.selectedScreenshotPhotosIds);

            break;
          case PhotosType.similarPhotos:
            ImagePickerUtil.updatePhotoGroupDate(photosType,ImagePickerUtil.selectedSimilarPhotosIds);

            break;
          case PhotosType.locationPhotos:
            ImagePickerUtil.updatePhotoGroupDate(photosType,ImagePickerUtil.selectedLocationPhotosIds);

            break;
          case PhotosType.blurryPhotos:
            ImagePickerUtil.updatePhotoGroupDate(photosType,ImagePickerUtil.selectedBlurryPhotosIds);

            break;
        }

        restoreSelections();
      } else {
        // 删除失败
        ToastUtil.show("Delete failed");
      }
    }
  }


}
