calendar_preview_controller.dart 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import 'dart:async';
  2. import 'package:clean/base/base_controller.dart';
  3. import 'package:clean/module/calendar/selected_preview/calendar_selected_preview_view.dart';
  4. import 'package:flutter/Material.dart';
  5. import 'package:flutter_card_swiper/flutter_card_swiper.dart';
  6. import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
  7. import 'package:get/get.dart';
  8. import 'package:wechat_assets_picker/wechat_assets_picker.dart';
  9. import '../../../data/repositories/user_repository.dart';
  10. import '../../../dialog/photo_delete_finish_dialog.dart';
  11. import '../../../dialog/photo_deleting_dialog.dart';
  12. import '../../../utils/toast_util.dart';
  13. import '../../image_picker/image_picker_util.dart';
  14. import '../../people_photo/photo_group.dart';
  15. import '../../store/store_view.dart';
  16. class CalendarPreviewController extends BaseController
  17. with GetSingleTickerProviderStateMixin {
  18. final Rx<PhotoGroup> photoGroup =
  19. PhotoGroup(isSelected: false, images: []).obs;
  20. late String? currentImageId;
  21. final CardSwiperController cardSwiperController = CardSwiperController();
  22. final RxBool isSwiperEnd = false.obs;
  23. RxInt groupIndex = 0.obs;
  24. late AnimationController animationController;
  25. RxBool animationIsComplete = false.obs;
  26. @override
  27. void onInit() {
  28. super.onInit();
  29. _getArgs(); // 获取传递的参数
  30. animationController = AnimationController(
  31. vsync: this,
  32. duration: const Duration(seconds: 3),
  33. );
  34. WidgetsBinding.instance.addPostFrameCallback((_) {
  35. if (currentImageId != null) {
  36. for (int i = 0; i < photoGroup.value.images.length; i++) {
  37. if (photoGroup.value.images[i].id == currentImageId) {
  38. debugPrint('photoGroups[i].id ${photoGroup.value.images[i].id},i $i');
  39. groupIndex.value = i;
  40. cardSwiperController.moveTo(i);
  41. break;
  42. }
  43. }
  44. }
  45. });
  46. animationController.addStatusListener((status) {
  47. if (status == AnimationStatus.forward) {
  48. // 延迟一秒
  49. Future.delayed(Duration(seconds: 1), () {
  50. animationIsComplete.value = true;
  51. });
  52. }
  53. if (status == AnimationStatus.completed) {
  54. Future.delayed(Duration(seconds: 1), () {
  55. CalendarSelectedPreviewPage.start(photoGroup.value);
  56. });
  57. }
  58. });
  59. }
  60. // 获取参数
  61. void _getArgs() {
  62. photoGroup.value = parameters?['photoGroup'];
  63. currentImageId = parameters?['currentImageId'];
  64. }
  65. void clickUnselect() {
  66. debugPrint("clickUnselect");
  67. cardSwiperController.swipe(CardSwiperDirection.right);
  68. }
  69. FutureOr<bool> onSwipe(
  70. int previousIndex,
  71. int? currentIndex,
  72. CardSwiperDirection direction,
  73. ) {
  74. debugPrint(
  75. 'The card $previousIndex was swiped to the ${direction.name}. Now the card $currentIndex is on top',
  76. );
  77. if (currentIndex != null) {
  78. groupIndex.value = currentIndex;
  79. }
  80. // 预加载
  81. // precacheImage(AssetEntityImageProvider(entity), context);
  82. // 如果direction是left,
  83. if (direction == CardSwiperDirection.left) {
  84. // 先看看图片id是不是在selectedPhotosIds里面,如果在,不处理,如果不在,添加到selectedPhotosIds里面
  85. if (!photoGroup.value.selectedPhotosIds
  86. .contains(photoGroup.value.images[previousIndex].id)) {
  87. debugPrint(
  88. 'add photoGroups[groupIndex.value].id ${photoGroup.value.images[previousIndex].id}');
  89. photoGroup.value.selectedPhotosIds
  90. .add(photoGroup.value.images[previousIndex].id);
  91. }
  92. } else if (direction == CardSwiperDirection.right) {
  93. // 先看看图片id是不是在selectedPhotosIds里面,如果在,在selectedPhotosIds移除,不处理,如果不在,不处理
  94. if (photoGroup.value.selectedPhotosIds
  95. .contains(photoGroup.value.images[previousIndex].id)) {
  96. debugPrint(
  97. 'remove photoGroups[groupIndex.value].id ${photoGroup.value.images[previousIndex].id}');
  98. photoGroup.value.selectedPhotosIds
  99. .remove(photoGroup.value.images[previousIndex].id);
  100. }
  101. }
  102. updateSelectedFilesSize();
  103. return true;
  104. }
  105. bool onSwiperUndo(
  106. int? previousIndex,
  107. int currentIndex,
  108. CardSwiperDirection direction,
  109. ) {
  110. debugPrint(
  111. 'The card $currentIndex was swiped back to the ${direction.name}. Now the card $previousIndex is on top');
  112. groupIndex.value = currentIndex;
  113. // 撤销之前左滑的操作
  114. if (direction == CardSwiperDirection.left) {
  115. debugPrint(
  116. 'photoGroups[groupIndex.value].id ${photoGroup.value.images[groupIndex.value].id}');
  117. if (photoGroup.value.selectedPhotosIds
  118. .contains(photoGroup.value.images[groupIndex.value].id)) {
  119. photoGroup.value.selectedPhotosIds
  120. .remove(photoGroup.value.images[groupIndex.value].id);
  121. }
  122. }
  123. updateSelectedFilesSize();
  124. return true;
  125. }
  126. onSwiperEnd() {
  127. isSwiperEnd.value = true;
  128. debugPrint('onSwiperEnd');
  129. // 延迟500ms
  130. Future.delayed(Duration(milliseconds: 200), () {
  131. animationController.forward(from: 0);
  132. });
  133. PhotoManager.clearFileCache();
  134. // PhotoSelectedPreviewPage.start(photosType, selectedPhotosIds);
  135. }
  136. void recoverSelectPhoto() {
  137. debugPrint('PhotoPreviewController recoverSelectPhoto');
  138. cardSwiperController.undo();
  139. }
  140. void clickSelect() {
  141. cardSwiperController.swipe(CardSwiperDirection.left);
  142. }
  143. void clickBack() {
  144. Get.back();
  145. }
  146. clickDelete() async {
  147. debugPrint('CalendarPreviewController clickDelete');
  148. if (userRepository.isVip()) {
  149. if (photoGroup.value.selectedPhotosIds.isNotEmpty) {
  150. photoDeletingDialog();
  151. // 获取要删除的资产
  152. final assetsToDelete = photoGroup.value.images
  153. .where(
  154. (asset) => photoGroup.value.selectedPhotosIds.contains(asset.id),
  155. )
  156. .toList();
  157. // 调用方法会返回被删除的资源,如果全部失败会返回空列表。
  158. final List<String> result = await PhotoManager.editor.deleteWithIds(
  159. assetsToDelete.map((e) => e.id).toList(),
  160. );
  161. // 比较result和selectedPhotosIds,如果result和selectedPhotosIds相等,说明删除成功,走下面的逻辑
  162. // 如果不相等,说明有删除失败的,走else逻辑
  163. if (result.length == photoGroup.value.selectedPhotosIds.length) {
  164. ImagePickerUtil.updatePhotoData(
  165. photoGroup.value.selectedPhotosIds);
  166. cleanSelections();
  167. ToastUtil.show('Delete success');
  168. Future.delayed(Duration(seconds: 2), () {
  169. SmartDialog.dismiss(tag: 'photoDeletingDialog');
  170. photoDeleteFinishDialog();
  171. });
  172. } else {
  173. SmartDialog.dismiss(tag: 'photoDeletingDialog');
  174. // 删除失败
  175. ToastUtil.show("Delete failed");
  176. }
  177. }
  178. } else {
  179. StorePage.start();
  180. }
  181. }
  182. //删除成功清除选中的图片
  183. void cleanSelections() async {
  184. photoGroup.value.images
  185. .removeWhere((element) => photoGroup.value.selectedPhotosIds.contains(element.id));
  186. photoGroup.value.selectedPhotosIds.clear();
  187. photoGroup.refresh();
  188. if (photoGroup.value.images.isEmpty) {
  189. return;
  190. }
  191. isSwiperEnd.value = false;
  192. if (photoGroup.value.images.isNotEmpty) {
  193. WidgetsBinding.instance.addPostFrameCallback((_) {
  194. groupIndex.value = 0;
  195. cardSwiperController.moveTo(0);
  196. });
  197. }
  198. updateSelectedFilesSize();
  199. }
  200. // 将selectedFilesSize转成String类型,然后单位转换,如果超过1MB,则转成MB,超过1GB,则转成GB,否则KB
  201. String get selectedFilesSizeString {
  202. final double sizeInKB = photoGroup.value.selectedTotalSize.value;
  203. if (sizeInKB >= 1024 * 1024) { // 先检查最大单位(GB)
  204. return "${(sizeInKB / (1024 * 1024)).toStringAsFixed(2)}GB";
  205. } else if (sizeInKB >= 1024) { // 然后检查MB
  206. return "${(sizeInKB / 1024).toStringAsFixed(2)}MB";
  207. } else { // 最后是KB
  208. return "${sizeInKB.toStringAsFixed(2)}KB";
  209. }
  210. }
  211. Future<void> updateSelectedFilesSize() async {
  212. // 如果没有选中的文件,直接返回
  213. if (photoGroup.value.selectedCount == 0) {
  214. photoGroup.value.selectedTotalSize.value = 0;
  215. return;
  216. }
  217. double totalSize = 0;
  218. final selectedImages = photoGroup.value.images;
  219. // 获取选中图片的大小(异步并行执行)
  220. final futures = photoGroup.value.selectedPhotosIds.map((assetId) async {
  221. if (ImagePickerUtil.fileSizeCache.containsKey(assetId)) {
  222. totalSize += ImagePickerUtil.fileSizeCache[assetId]!;
  223. } else {
  224. final image = selectedImages.firstWhere((image) => image.id == assetId);
  225. final file = await image.file;
  226. if (file != null) {
  227. final size = (await file.length()) / 1024; // 转换为KB
  228. totalSize += size;
  229. ImagePickerUtil.fileSizeCache[assetId] = size;
  230. }
  231. }
  232. }).toList();
  233. // 等待所有异步操作完成
  234. await Future.wait(futures);
  235. // 更新选中文件的总大小
  236. photoGroup.value.selectedTotalSize.value = totalSize;
  237. // 打印调试信息
  238. print("selectedFilesSize: ${photoGroup.value.selectedTotalSize.value}");
  239. }
  240. void restoreSelections() {
  241. if(photoGroup.value.images.isEmpty){
  242. clickBack();
  243. return;
  244. }
  245. isSwiperEnd.value = false;
  246. if (photoGroup.value.images.isNotEmpty) {
  247. WidgetsBinding.instance.addPostFrameCallback((_) {
  248. groupIndex.value = 0;
  249. cardSwiperController.moveTo(0);
  250. });
  251. }
  252. updateSelectedFilesSize();
  253. }
  254. @override
  255. void onClose() {
  256. debugPrint('CalendarPreviewController onClose');
  257. animationController.dispose();
  258. super.onClose();
  259. isSwiperEnd.value = false;
  260. // 清理操作,释放资源
  261. cardSwiperController.dispose();
  262. // 清理缓存
  263. PhotoManager.clearFileCache();
  264. }
  265. }