import 'dart:io';

import 'package:clean/module/image_picker/image_picker_util.dart';
import 'package:clean/module/people_photo/photo_group.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class PeoplePhotoController extends GetxController {
  final RxList<PhotoGroup> photoGroups = <PhotoGroup>[].obs;

  static final Map<String, List<bool>> _savedSelections = {};
  static bool _hasInitializedSelections = false;

  int get selectedFileCount =>
      photoGroups.fold(0, (sum, group) => sum + group.selectedCount);

  Future<double> getSelectedFilesSize() async {
    double totalSize = 0;
    for (var group in photoGroups) {
      for (int i = 0; i < group.images.length; i++) {
        if (group.selectedImages[i]) {
          final file = await group.images[i].file;
          if (file != null) {
            totalSize += file.lengthSync();
          }
        }
      }
    }
    return totalSize / 1024; // Convert to KB
  }

  void toggleImageSelection(String groupTitle, int imageIndex) {
    final group = photoGroups.firstWhere((g) => g.title == groupTitle);
    group.selectedImages[imageIndex] = !group.selectedImages[imageIndex];
    group.isSelected.value = group.selectedImages.every((selected) => selected);
    _saveSelections(); // 保存选择状态
  }

  void toggleGroupSelection(String groupTitle) {
    final group = photoGroups.firstWhere((g) => g.title == groupTitle);
    final newValue = !group.isSelected.value;
    group.toggleSelectAll(newValue);
    _saveSelections(); // 保存选择状态
  }

  @override
  void onInit() {
    super.onInit();
    loadSimilarPhotos();
      if (_hasInitializedSelections) {
        _restoreSelections();
      }
    // loadPhotosFromDirectory().then((_) {
    //   // 恢复保存的选择状态
    //   if (_hasInitializedSelections) {
    //     _restoreSelections();
    //   }
    // });
  }

  void _saveSelections() {
    for (var group in photoGroups) {
      _savedSelections[group.title] = group.selectedImages.toList();
    }
    _hasInitializedSelections = true;
  }




  void _restoreSelections() {
    for (var group in photoGroups) {
      // 这里假设每次页面加载时，已选择的状态会保存在 `RxList<bool>` 中。
      group.isSelected.value = group.selectedImages.every((selected) => selected);
    }
  }
  Future<void> loadPhotosFromDirectory() async {
    try {
      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        Get.context!,
      );
      if (result != null && result.isNotEmpty) {
        photoGroups.add(PhotoGroup(
          title: 'photo: ${result.length}',
          imageCount: result.length,
          isSelected: false,
          images: result,
        ));
      }
    } catch (e) {
      print('Error loading photos: $e');
    }
  }

  void loadSimilarPhotos() {
    // 清空现有数据
    photoGroups.clear();

    // 将 ImagePickerUtil 中的相似照片转换为 PhotoGroup

      final photoGroup = ImagePickerUtil.peoplePhotos;
      if (photoGroup.isNotEmpty) {
        photoGroups.add(PhotoGroup(
          title: 'photo : ${photoGroup.length}',
          imageCount: photoGroup.length,
          isSelected: false,
          images: photoGroup,
        ));
      }

  }
}
