base_photo_controller.dart 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import 'package:clean/base/base_controller.dart';
  2. import 'package:clean/data/repositories/user_repository.dart';
  3. import 'package:clean/dialog/photo_delete_finish_dialog.dart';
  4. import 'package:clean/dialog/photo_deleting_dialog.dart';
  5. import 'package:clean/module/store/store_view.dart';
  6. import 'package:flutter/cupertino.dart';
  7. import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
  8. import 'package:get/get.dart';
  9. import 'package:wechat_assets_picker/wechat_assets_picker.dart';
  10. import 'package:clean/module/image_picker/image_picker_util.dart';
  11. import 'package:clean/module/people_photo/photo_group.dart';
  12. import 'package:clean/utils/toast_util.dart';
  13. import 'package:clean/data/bean/photos_type.dart';
  14. import 'package:clean/module/photo_preview/photo_preview_view.dart';
  15. import '../utils/file_size_calculator_util.dart';
  16. abstract class BasePhotoController extends BaseController {
  17. final RxList<PhotoGroup> photoGroups = <PhotoGroup>[].obs;
  18. final RxDouble selectedFilesSize = 0.0.obs;
  19. RxInt selectedFileCount = 0.obs;
  20. final RxSet<String> selectedPhotosIds = <String>{}.obs;
  21. // 将selectedFilesSize转成String类型,然后单位转换,如果超过1MB,则转成MB,超过1GB,则转成GB,否则KB
  22. String get selectedFilesSizeString {
  23. debugPrint(
  24. "BasePhotoController selectedFilesSize.value ${selectedFilesSize.value}");
  25. final double sizeInKB = selectedFilesSize.value;
  26. if (sizeInKB >= 1024 * 1024) {
  27. // 先检查最大单位(GB)
  28. return "${(sizeInKB / (1024 * 1024)).toStringAsFixed(2)}GB";
  29. } else if (sizeInKB >= 1024) {
  30. // 然后检查MB
  31. return "${(sizeInKB / 1024).toStringAsFixed(2)}MB";
  32. } else {
  33. // 最后是KB
  34. return "${sizeInKB.toStringAsFixed(2)}KB";
  35. }
  36. }
  37. Future<void> updateSelectedFilesSize() async {
  38. if (selectedPhotosIds.isEmpty) {
  39. selectedFilesSize.value = 0;
  40. return;
  41. }
  42. FileSizeCalculatorUtil.calculateTotalSize(assetIds: selectedPhotosIds, updateValue: (double totalSize) {
  43. selectedFilesSize.value = totalSize; // 监听并更新 UI
  44. });
  45. // double totalSize = 0;
  46. // final uncasedIds = selectedPhotosIds.where((id) => !FileSizeCalculatorUtil.fileSizeCache.containsKey(id)).toSet();
  47. //
  48. // // **1️⃣ 先处理缓存中的文件**
  49. //
  50. // totalSize = selectedPhotosIds.fold(0, (prev, id) => prev + (FileSizeCalculatorUtil.fileSizeCache[id] ?? 0));
  51. //
  52. //
  53. // // **2️⃣ 分批处理未缓存的文件**
  54. // const batchSize = 50;
  55. // for (int i = 0; i < uncasedIds.length; i += batchSize) {
  56. // if (selectedPhotosIds.isEmpty) {
  57. // selectedFilesSize.value = 0;
  58. // return;
  59. // }
  60. //
  61. // final batch = uncasedIds.skip(i).take(batchSize);
  62. // final sizes = await Future.wait(batch.map(FileSizeCalculatorUtil.getFileSize));
  63. //
  64. // totalSize += sizes.fold(0, (sum, size) => sum + size);
  65. //
  66. // // **再检查一次是否被清空,避免无意义计算**
  67. // if (selectedPhotosIds.isEmpty) {
  68. // selectedFilesSize.value = 0;
  69. // return;
  70. // }
  71. //
  72. // // **减少 UI 更新频率**
  73. // if (i % (batchSize * 2) == 0 || i + batchSize >= uncasedIds.length) {
  74. // selectedFilesSize.value = totalSize;
  75. // }
  76. //
  77. // await Future.delayed(Duration.zero);
  78. // }
  79. //
  80. // selectedFilesSize.value = totalSize; // 确保最终更新总大小
  81. // PhotoManager.clearFileCache();
  82. }
  83. // 切换图片选中状态
  84. Future<void> toggleImageSelection(
  85. List<AssetEntity> groupTitle, int imageIndex) async {
  86. print("BasePhotoController toggleImageSelection");
  87. final group = getGroupByImages(groupTitle);
  88. final image = group.images[imageIndex];
  89. final selected = !group.selectedImages[imageIndex];
  90. group.selectedImages[imageIndex] = selected;
  91. updateSelectedPhotosIds(image.id, selected);
  92. group.isSelected.value = group.selectedImages.every((selected) => selected);
  93. selectedFileCount.value = selectedPhotosIds.length;
  94. // 更新文件大小
  95. if (selected) {
  96. // 如果选中,增加文件大小
  97. if (FileSizeCalculatorUtil.fileSizeCache.containsKey(image.id)) {
  98. selectedFilesSize.value += FileSizeCalculatorUtil.fileSizeCache[image.id]!;
  99. } else {
  100. final file = await image.file;
  101. if (file != null) {
  102. selectedFilesSize.value += (await file.length()) / 1024; // 转换为KB
  103. }
  104. }
  105. } else {
  106. // 如果取消选中,减少文件大小
  107. if (FileSizeCalculatorUtil.fileSizeCache.containsKey(image.id)) {
  108. selectedFilesSize.value -= FileSizeCalculatorUtil.fileSizeCache[image.id]!;
  109. } else {
  110. final file = await image.file;
  111. if (file != null) {
  112. selectedFilesSize.value -= (await file.length()) / 1024; // 转换为KB
  113. }
  114. }
  115. }
  116. PhotoManager.clearFileCache();
  117. }
  118. void clickImage(List<AssetEntity> images, int imageIndex, PhotosType type) {
  119. print("BasePhotoController clickImage");
  120. final group = getGroupByImages(images);
  121. final image = group.images[imageIndex];
  122. PhotoPreviewPage.start(type, image.id);
  123. }
  124. // 切换图片组选中状态
  125. void toggleGroupSelection(List<AssetEntity> imagesList) {
  126. final group = getGroupByImages(imagesList);
  127. final newValue = !group.isSelected.value;
  128. group.toggleSelectAll(newValue);
  129. for (var image in group.images) {
  130. updateSelectedPhotosIds(image.id, newValue);
  131. }
  132. selectedFileCount.value = selectedPhotosIds.length;
  133. updateSelectedFilesSize();
  134. }
  135. PhotoGroup getGroupByImages(List<AssetEntity> images) {
  136. final imageIds = images.map((img) => img.id).toSet();
  137. return photoGroups.firstWhere(
  138. (group) => group.images.every((image) => imageIds.contains(image.id)));
  139. }
  140. void updateSelectedPhotosIds(String photoId, bool isSelected) {
  141. if (isSelected) {
  142. selectedPhotosIds.add(photoId);
  143. } else {
  144. selectedPhotosIds.remove(photoId);
  145. }
  146. }
  147. // 恢复选中状态
  148. void restoreSelections() async {
  149. final selectedIds = selectedPhotosIds.toSet();
  150. for (var group in photoGroups) {
  151. for (int i = 0; i < group.images.length; i++) {
  152. group.selectedImages[i] = selectedIds.contains(group.images[i].id);
  153. }
  154. group.isSelected.value =
  155. group.selectedImages.every((selected) => selected);
  156. }
  157. selectedFileCount.value = selectedIds.length;
  158. if (selectedIds.isEmpty) {
  159. selectedFilesSize.value = 0;
  160. return;
  161. }
  162. updateSelectedFilesSize();
  163. }
  164. @override
  165. void onInit() {
  166. print("BasePhotoController onInit");
  167. super.onInit();
  168. loadPhotos();
  169. restoreSelections();
  170. }
  171. void loadPhotos();
  172. // 点击删除
  173. void clickDelete() async {
  174. if (userRepository.isVip()) {
  175. if (selectedPhotosIds.isNotEmpty) {
  176. photoDeletingDialog();
  177. final assetsToDelete = photoGroups
  178. .expand((group) => group.images
  179. .where((asset) => selectedPhotosIds.contains(asset.id)))
  180. .toList();
  181. final List<String> result = await PhotoManager.editor.deleteWithIds(
  182. assetsToDelete.map((e) => e.id).toList(),
  183. );
  184. if (result.length == selectedPhotosIds.length) {
  185. for (var group in photoGroups) {
  186. group.images.removeWhere(
  187. (element) => selectedPhotosIds.contains(element.id));
  188. }
  189. ImagePickerUtil.updatePhotoGroupDate(
  190. getPhotosType(), selectedPhotosIds);
  191. selectedPhotosIds.clear();
  192. selectedFileCount.value = selectedPhotosIds.length;
  193. print(
  194. "BasePhotoController clickDelete selectedPhotosIds $selectedPhotosIds");
  195. updateSelectedFilesSize();
  196. ToastUtil.show("Delete success");
  197. Future.delayed(Duration(seconds: 2), () {
  198. SmartDialog.dismiss(tag: 'photoDeletingDialog');
  199. photoDeleteFinishDialog();
  200. });
  201. } else {
  202. SmartDialog.dismiss(tag: 'photoDeletingDialog');
  203. ToastUtil.show("Delete failed");
  204. }
  205. }
  206. } else {
  207. StorePage.start();
  208. }
  209. }
  210. void updateSelections(Set<String> selectedIds) {
  211. print(
  212. "BasePhotoController updateSelections selectedIds $selectedIds, selectedPhotosIds $selectedPhotosIds getPhotosType() ${getPhotosType()}");
  213. // selectedId如果是selectedPhotosIds对象,那么selectedPhotosIds.assignAll(selectedIds)会清空
  214. // selectedPhotosIds.assignAll(selectedIds);
  215. selectedPhotosIds.assignAll(Set.from(selectedIds));
  216. print(
  217. "BasePhotoController updateSelections selectedIds $selectedIds, selectedPhotosIds $selectedPhotosIds getPhotosType() ${getPhotosType()}");
  218. switch (getPhotosType()) {
  219. case PhotosType.peoplePhotos:
  220. ImagePickerUtil.selectedPeoplePhotosIds.assignAll(selectedPhotosIds);
  221. break;
  222. case PhotosType.screenshots:
  223. ImagePickerUtil.selectedScreenshotPhotosIds
  224. .assignAll(selectedPhotosIds);
  225. break;
  226. case PhotosType.similarPhotos:
  227. ImagePickerUtil.selectedSimilarPhotosIds.assignAll(selectedPhotosIds);
  228. break;
  229. case PhotosType.locationPhotos:
  230. ImagePickerUtil.selectedLocationPhotosIds.assignAll(selectedPhotosIds);
  231. break;
  232. case PhotosType.blurryPhotos:
  233. ImagePickerUtil.selectedBlurryPhotosIds.assignAll(selectedPhotosIds);
  234. break;
  235. }
  236. }
  237. PhotosType getPhotosType();
  238. // 将photoGroups中所有的图片返回
  239. List<AssetEntity> getAllPhotos() {
  240. return photoGroups.expand((group) => group.images).toList();
  241. }
  242. @override
  243. void onClose() {
  244. super.onClose();
  245. PhotoManager.clearFileCache();
  246. }
  247. }