import 'package:clean/base/base_controller.dart';
import 'package:clean/module/calendar/preview/calendar_preview_controller.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';

import '../../../data/repositories/user_repository.dart';
import '../../../dialog/photo_delete_finish_dialog.dart';
import '../../../dialog/photo_deleting_dialog.dart';
import '../../../router/app_pages.dart';
import '../../../utils/file_size_calculator_util.dart';
import '../../../utils/toast_util.dart';
import '../../image_picker/image_picker_util.dart';
import '../../people_photo/photo_group.dart';
import '../../store/store_view.dart';

class CalendarSelectedPreviewController extends BaseController {
  final Rx<PhotoGroup> photoGroup =
      PhotoGroup(isSelected: false, images: []).obs;

  final CalendarPreviewController calendarPreviewController =
      Get.find<CalendarPreviewController>();

  final RxBool isKeepAll = false.obs;

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

  void _initData() {
    // 筛选出已选中的图片
    final selectedImages = calendarPreviewController.photoGroup.value.images
        .where((image) => calendarPreviewController
            .photoGroup.value.selectedPhotosIds
            .contains(image.id))
        .toList();

    // 生成新的 PhotoGroup 仅包含选中的图片
    photoGroup.value = PhotoGroup(
      isSelected: selectedImages.length ==
          calendarPreviewController.photoGroup.value.images.length,
      images: selectedImages,
    );

    // 更新已选中的 ID 列表
    photoGroup.value.selectedPhotosIds.addAll(
      selectedImages.map((image) => image.id),
    );
    updateSelectedFilesSize();
  }

  void clickBack() {
    calendarPreviewController.restoreSelections();
    Get.back();
  }

  void toggleGroupSelection(List<AssetEntity> imagesList) {
    final newValue = !photoGroup.value.isSelected.value;
    photoGroup.value.toggleSelectAll(newValue);

    // 更新选中状态
    for (var image in imagesList) {
      updateSelectedPhotosIds(image.id, newValue);
    }
    updateSelectedFilesSize();
  }

  clickDelete() async {
    debugPrint('CalendarSelectedPreviewController clickDelete');
    if (userRepository.isVip()) {
      if (photoGroup.value.selectedPhotosIds.isNotEmpty) {
        photoDeletingDialog();
        // 获取要删除的资产
        final assetsToDelete = photoGroup.value.images
            .where(
              (asset) => photoGroup.value.selectedPhotosIds.contains(asset.id),
            )
            .toList();

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

        //   比较result和selectedPhotosIds，如果result和selectedPhotosIds相等，说明删除成功，走下面的逻辑
        // 如果不相等，说明有删除失败的，走else逻辑
        if (result.length == photoGroup.value.selectedPhotosIds.length) {
          debugPrint(
              "CalendarSelectedPreviewController delete ${photoGroup.value.selectedPhotosIds}");

          ImagePickerUtil.updatePhotoData(photoGroup.value.selectedPhotosIds);
          cleanSelections();
          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();
    }
  }

  //删除成功清除选中的图片
  void cleanSelections() async {
    photoGroup.value.images.removeWhere(
        (element) => photoGroup.value.selectedPhotosIds.contains(element.id));
    calendarPreviewController.photoGroup.value.images.removeWhere(
        (element) => photoGroup.value.selectedPhotosIds.contains(element.id));
    calendarPreviewController.photoGroup.value.selectedPhotosIds.clear();
    photoGroup.value.selectedPhotosIds.clear();
    if (photoGroup.value.images.isEmpty) {
      return;
    }
    updateSelectedFilesSize();
  }

  Future<void> updateSelectedFilesSize() async {
    // 如果没有选中的文件，直接返回
    if (photoGroup.value.selectedCount == 0) {
      photoGroup.value.selectedTotalSize.value = 0;
      return;
    }

    FileSizeCalculatorUtil.calculateTotalSizeByIOS(
      assetIds: photoGroup.value.selectedPhotosIds,
      updateValue: (double totalSize) {
        photoGroup.value.selectedTotalSize.value = totalSize;
      },
    );
  }

  void updateSelectedPhotosIds(String photoId, bool isSelected) {
    if (isSelected) {
      if (!photoGroup.value.selectedPhotosIds.contains(photoId)) {
        photoGroup.value.selectedPhotosIds.add(photoId);
      }
    } else {
      photoGroup.value.selectedPhotosIds.remove(photoId);
    }
    photoGroup.value.isSelected.value =
        photoGroup.value.selectedPhotosIds.length ==
            photoGroup.value.images.length;
  }

  clickImage(int imageIndex) {
    debugPrint("CalendarSelectedPreviewController clickImage");
  }

  Future<void> toggleImageSelection(int imageIndex) async {
    debugPrint("CalendarSelectedPreviewController toggleImageSelection");
    final image = photoGroup.value.images[imageIndex];
    final photoId = image.id;

    // 反转选择状态
    final isNowSelected = !photoGroup.value.selectedPhotosIds.contains(photoId);
    updateSelectedPhotosIds(photoId, isNowSelected);

    updateSelectedFilesSize();
  }

  // 将selectedFilesSize转成String类型,然后单位转换,如果超过1MB,则转成MB,超过1GB,则转成GB,否则KB
  String get selectedFilesSizeString {
    final double sizeInKB = photoGroup.value.selectedTotalSize.value;

    if (sizeInKB >= 1024 * 1024) {
      // 先检查最大单位（GB）
      return "${(sizeInKB / (1024 * 1024)).toStringAsFixed(2)}GB";
    } else if (sizeInKB >= 1024) {
      // 然后检查MB
      return "${(sizeInKB / 1024).toStringAsFixed(2)}MB";
    } else {
      // 最后是KB
      return "${sizeInKB.toStringAsFixed(2)}KB";
    }
  }
}
