photo_preview_controller.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. import 'dart:async';
  2. import 'package:clean/base/base_controller.dart';
  3. import 'package:clean/base/base_photo_controller.dart';
  4. import 'package:clean/data/bean/photos_type.dart';
  5. import 'package:clean/data/consts/constants.dart';
  6. import 'package:clean/data/repositories/user_repository.dart';
  7. import 'package:clean/dialog/photo_delete_finish_dialog.dart';
  8. import 'package:clean/dialog/photo_deleting_dialog.dart';
  9. import 'package:clean/dialog/photo_preview_tip_dialog.dart';
  10. import 'package:clean/module/image_picker/image_picker_util.dart';
  11. import 'package:clean/module/locations_photo/locations_single_photo_controller.dart';
  12. import 'package:clean/module/people_photo/people_photo_controller.dart';
  13. import 'package:clean/module/people_photo/photo_group.dart';
  14. import 'package:clean/module/photo_preview/phtoto_selected_preview_view.dart';
  15. import 'package:clean/module/screenshots_blurry/screenshots_controller.dart';
  16. import 'package:clean/module/similar_photo/similar_photo_controller.dart';
  17. import 'package:clean/module/store/store_view.dart';
  18. import 'package:clean/utils/file_utils.dart';
  19. import 'package:clean/utils/toast_util.dart';
  20. import 'package:flutter/Material.dart';
  21. import 'package:flutter_card_swiper/flutter_card_swiper.dart';
  22. import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
  23. import 'package:get/get.dart';
  24. import 'package:lottie/lottie.dart';
  25. import 'package:wechat_assets_picker/wechat_assets_picker.dart';
  26. import '../../utils/file_size_calculator_util.dart';
  27. class PhotoPreviewController extends BaseController
  28. with GetSingleTickerProviderStateMixin {
  29. Rx<CardSwiperController> cardSwiperController = CardSwiperController().obs;
  30. final RxList<AssetEntity> listAssetEntity = <AssetEntity>[].obs;
  31. final RxSet<String> selectedPhotosIds = <String>{}.obs;
  32. final RxBool isSwiperEnd = false.obs;
  33. RxInt groupIndex = 0.obs;
  34. late PhotosType photosType;
  35. late String? currentImageId;
  36. RxDouble selectedFilesSize = 0.0.obs;
  37. RxInt selectedFileCount = 0.obs;
  38. late AnimationController animationController;
  39. RxBool animationIsComplete = false.obs;
  40. @override
  41. void onInit() {
  42. super.onInit();
  43. animationController = AnimationController(
  44. vsync: this,
  45. duration: const Duration(seconds: 3),
  46. );
  47. print('PhotoPreviewController onInit');
  48. _getArgs(); // 获取传递的参数
  49. _initData(); // 初始化数据
  50. WidgetsBinding.instance.addPostFrameCallback((_) {
  51. if (currentImageId != null) {
  52. for (int i = 0; i < listAssetEntity.length; i++) {
  53. if (listAssetEntity[i].id == currentImageId) {
  54. print('photoGroups[i].id ${listAssetEntity[i].id},i $i');
  55. groupIndex.value = i;
  56. cardSwiperController.value.moveTo(i);
  57. break;
  58. }
  59. }
  60. }
  61. });
  62. animationController.addStatusListener((status) {
  63. if (status == AnimationStatus.forward) {
  64. // 延迟一秒
  65. Future.delayed(Duration(seconds: 1), () {
  66. animationIsComplete.value = true;
  67. });
  68. }
  69. if (status == AnimationStatus.completed) {
  70. Future.delayed(Duration(seconds: 1), () {
  71. PhotoSelectedPreviewPage.start(photosType, selectedPhotosIds);
  72. });
  73. }
  74. });
  75. }
  76. @override
  77. void onReady() {
  78. // TODO: implement onReady
  79. super.onReady();
  80. print('PhotoPreviewController onReady');
  81. if (isFirstOpenPhotoPreview()) {
  82. photoPreviewTipDialog(clickCallback: () {
  83. setFirstOpenPhotoPreview(false);
  84. });
  85. }
  86. }
  87. // 获取参数
  88. void _getArgs() {
  89. photosType = parameters?['photosType'];
  90. currentImageId = parameters?['currentImageId'];
  91. }
  92. void _assignPhotosAndSelections(BasePhotoController controller) {
  93. listAssetEntity.assignAll(controller.getAllPhotos());
  94. selectedPhotosIds.assignAll(controller.selectedPhotosIds);
  95. selectedFileCount.value = selectedPhotosIds.length;
  96. }
  97. void _initData() {
  98. listAssetEntity.clear();
  99. selectedPhotosIds.clear();
  100. switch (photosType) {
  101. case PhotosType.peoplePhotos:
  102. final PeoplePhotoController controller =
  103. Get.find<PeoplePhotoController>();
  104. _assignPhotosAndSelections(controller);
  105. break;
  106. case PhotosType.screenshots:
  107. final ScreenShotsController controller =
  108. Get.find<ScreenShotsController>();
  109. _assignPhotosAndSelections(controller);
  110. break;
  111. case PhotosType.similarPhotos:
  112. final SimilarPhotoController controller =
  113. Get.find<SimilarPhotoController>();
  114. _assignPhotosAndSelections(controller);
  115. break;
  116. case PhotosType.locationPhotos:
  117. final LocationsSinglePhotoController controller =
  118. Get.find<LocationsSinglePhotoController>();
  119. _assignPhotosAndSelections(controller);
  120. break;
  121. case PhotosType.blurryPhotos:
  122. final ScreenShotsController controller =
  123. Get.find<ScreenShotsController>();
  124. _assignPhotosAndSelections(controller);
  125. break;
  126. }
  127. updateSelectedFilesSize();
  128. }
  129. //删除成功清除选中的图片
  130. void cleanSelections() async {
  131. debugPrint('PhotoPreviewController cleanSelections');
  132. listAssetEntity
  133. .removeWhere((element) => selectedPhotosIds.contains(element.id));
  134. selectedPhotosIds.clear();
  135. if (listAssetEntity.isEmpty) {
  136. return;
  137. }
  138. isSwiperEnd.value = false;
  139. if (listAssetEntity.isNotEmpty) {
  140. WidgetsBinding.instance.addPostFrameCallback((_) {
  141. groupIndex.value = 0;
  142. cardSwiperController.value.moveTo(0);
  143. });
  144. }
  145. updateSelectedFilesSize();
  146. selectedFileCount.value = selectedPhotosIds.length;
  147. }
  148. // 恢复状态
  149. void restoreSelections() {
  150. if (listAssetEntity.isEmpty) {
  151. clickBack();
  152. return;
  153. }
  154. isSwiperEnd.value = false;
  155. if (listAssetEntity.isNotEmpty) {
  156. WidgetsBinding.instance.addPostFrameCallback((_) {
  157. groupIndex.value = 0;
  158. cardSwiperController.value.moveTo(0);
  159. });
  160. }
  161. updateSelectedFilesSize();
  162. selectedFileCount.value = selectedPhotosIds.length;
  163. }
  164. Future<void> updateSelectedFilesSize() async {
  165. if (selectedPhotosIds.isEmpty) {
  166. selectedFilesSize.value = 0;
  167. return;
  168. }
  169. double totalSize = 0;
  170. final uncasedIds = selectedPhotosIds.where((id) => !FileSizeCalculatorUtil.fileSizeCache.containsKey(id)).toSet();
  171. // **1️⃣ 先处理缓存中的文件**
  172. totalSize = selectedPhotosIds.fold(0, (prev, id) => prev + (FileSizeCalculatorUtil.fileSizeCache[id] ?? 0));
  173. // **2️⃣ 分批处理未缓存的文件**
  174. const batchSize = 50;
  175. for (int i = 0; i < uncasedIds.length; i += batchSize) {
  176. if (selectedPhotosIds.isEmpty) {
  177. selectedFilesSize.value = 0;
  178. return;
  179. }
  180. final batch = uncasedIds.skip(i).take(batchSize);
  181. final sizes = await Future.wait(batch.map(FileSizeCalculatorUtil.getFileSize));
  182. totalSize += sizes.fold(0, (sum, size) => sum + size);
  183. // **再检查一次是否被清空,避免无意义计算**
  184. if (selectedPhotosIds.isEmpty) {
  185. selectedFilesSize.value = 0;
  186. return;
  187. }
  188. // **减少 UI 更新频率**
  189. if (i % (batchSize * 2) == 0 || i + batchSize >= uncasedIds.length) {
  190. selectedFilesSize.value = totalSize;
  191. }
  192. await Future.delayed(Duration.zero);
  193. }
  194. selectedFilesSize.value = totalSize; // 确保最终更新总大小
  195. PhotoManager.clearFileCache();
  196. }
  197. void updateSelections(Set<String> selectedIds) {
  198. print(
  199. 'PhotoPreviewController updateSelections photosType $photosType selectedIds $selectedIds');
  200. selectedPhotosIds.assignAll(selectedIds);
  201. restoreSelections();
  202. }
  203. void recoverSelectPhoto() {
  204. print('PhotoPreviewController recoverSelectPhoto');
  205. cardSwiperController.value.undo();
  206. }
  207. void clickSelect() {
  208. cardSwiperController.value.swipe(CardSwiperDirection.left);
  209. }
  210. @override
  211. void onClose() {
  212. print('PhotoPreviewController onClose');
  213. animationController.dispose();
  214. super.onClose();
  215. isSwiperEnd.value = false;
  216. // 清理操作,释放资源
  217. cardSwiperController.value.dispose();
  218. // 清理缓存
  219. PhotoManager.clearFileCache();
  220. }
  221. void clickBack() {
  222. _saveSelectedPhotos(photosType);
  223. Get.back();
  224. }
  225. // // 保存选择的图片ID列表
  226. void _saveSelectedPhotos(PhotosType type) {
  227. switch (type) {
  228. case PhotosType.peoplePhotos:
  229. PeoplePhotoController controller = Get.find<PeoplePhotoController>();
  230. controller.updateSelections(selectedPhotosIds);
  231. controller.restoreSelections();
  232. break;
  233. case PhotosType.screenshots:
  234. ScreenShotsController controller = Get.find<ScreenShotsController>();
  235. controller.updateSelections(selectedPhotosIds);
  236. controller.restoreSelections();
  237. break;
  238. case PhotosType.similarPhotos:
  239. SimilarPhotoController controller = Get.find<SimilarPhotoController>();
  240. controller.updateSelections(selectedPhotosIds);
  241. controller.restoreSelections();
  242. break;
  243. case PhotosType.locationPhotos:
  244. LocationsSinglePhotoController controller =
  245. Get.find<LocationsSinglePhotoController>();
  246. controller.updateSelections(selectedPhotosIds);
  247. controller.restoreSelections();
  248. break;
  249. case PhotosType.blurryPhotos:
  250. ScreenShotsController controller = Get.find<ScreenShotsController>();
  251. controller.updateSelections(selectedPhotosIds);
  252. controller.restoreSelections();
  253. break;
  254. }
  255. }
  256. void clickUnselect() {
  257. print("clickUnselect");
  258. cardSwiperController.value.swipe(CardSwiperDirection.right);
  259. }
  260. FutureOr<bool> onSwipe(
  261. int previousIndex,
  262. int? currentIndex,
  263. CardSwiperDirection direction,
  264. ) {
  265. print(
  266. 'The card $previousIndex was swiped to the ${direction.name}. Now the card $currentIndex is on top',
  267. );
  268. if (currentIndex != null) {
  269. groupIndex.value = currentIndex;
  270. }
  271. // 如果direction是left,
  272. if (direction == CardSwiperDirection.left) {
  273. // 先看看图片id是不是在selectedPhotosIds里面,如果在,不处理,如果不在,添加到selectedPhotosIds里面
  274. if (!selectedPhotosIds.contains(listAssetEntity[previousIndex].id)) {
  275. print(
  276. 'add photoGroups[groupIndex.value].id ${listAssetEntity[previousIndex].id}');
  277. selectedPhotosIds.add(listAssetEntity[previousIndex].id);
  278. }
  279. } else if (direction == CardSwiperDirection.right) {
  280. // 先看看图片id是不是在selectedPhotosIds里面,如果在,在selectedPhotosIds移除,不处理,如果不在,不处理
  281. if (selectedPhotosIds.contains(listAssetEntity[previousIndex].id)) {
  282. print(
  283. 'remove photoGroups[groupIndex.value].id ${listAssetEntity[previousIndex].id}');
  284. selectedPhotosIds.remove(listAssetEntity[previousIndex].id);
  285. }
  286. }
  287. selectedFileCount.value = selectedPhotosIds.length;
  288. updateSelectedFilesSize();
  289. return true;
  290. }
  291. bool onSwiperUndo(
  292. int? previousIndex,
  293. int currentIndex,
  294. CardSwiperDirection direction,
  295. ) {
  296. print(
  297. 'The card $currentIndex was swiped back to the ${direction.name}. Now the card $previousIndex is on top');
  298. groupIndex.value = currentIndex;
  299. // 撤销之前左滑的操作
  300. if (direction == CardSwiperDirection.left) {
  301. print(
  302. 'photoGroups[groupIndex.value].id ${listAssetEntity[groupIndex.value].id}');
  303. if (selectedPhotosIds.contains(listAssetEntity[groupIndex.value].id)) {
  304. selectedPhotosIds.remove(listAssetEntity[groupIndex.value].id);
  305. }
  306. }
  307. selectedFileCount.value = selectedPhotosIds.length;
  308. updateSelectedFilesSize();
  309. PhotoManager.clearFileCache();
  310. return true;
  311. }
  312. onSwiperEnd() {
  313. isSwiperEnd.value = true;
  314. print('onSwiperEnd');
  315. // 延迟500ms
  316. Future.delayed(Duration(milliseconds: 200), () {
  317. animationController.forward(from: 0);
  318. });
  319. PhotoManager.clearFileCache();
  320. // PhotoSelectedPreviewPage.start(photosType, selectedPhotosIds);
  321. }
  322. clickDelete() async {
  323. print('clickDelete');
  324. if (userRepository.isVip()) {
  325. switch (photosType) {
  326. case PhotosType.peoplePhotos:
  327. ImagePickerUtil.selectedPeoplePhotosIds.assignAll(selectedPhotosIds);
  328. break;
  329. case PhotosType.screenshots:
  330. ImagePickerUtil.selectedScreenshotPhotosIds
  331. .assignAll(selectedPhotosIds);
  332. break;
  333. case PhotosType.similarPhotos:
  334. ImagePickerUtil.selectedSimilarPhotosIds.assignAll(selectedPhotosIds);
  335. break;
  336. case PhotosType.locationPhotos:
  337. ImagePickerUtil.selectedLocationPhotosIds
  338. .assignAll(selectedPhotosIds);
  339. break;
  340. case PhotosType.blurryPhotos:
  341. ImagePickerUtil.selectedBlurryPhotosIds.assignAll(selectedPhotosIds);
  342. break;
  343. }
  344. if (selectedPhotosIds.isNotEmpty) {
  345. photoDeletingDialog();
  346. // 获取要删除的资产
  347. final assetsToDelete = listAssetEntity
  348. .where(
  349. (asset) => selectedPhotosIds.contains(asset.id),
  350. )
  351. .toList();
  352. // 调用方法会返回被删除的资源,如果全部失败会返回空列表。
  353. final List<String> result = await PhotoManager.editor.deleteWithIds(
  354. assetsToDelete.map((e) => e.id).toList(),
  355. );
  356. print('PhotoPreviewController result $result');
  357. // 比较result和selectedPhotosIds,如果result和selectedPhotosIds相等,说明删除成功,走下面的逻辑
  358. // 如果不相等,说明有删除失败的,走else逻辑
  359. if (result.length == selectedPhotosIds.length) {
  360. switch (photosType) {
  361. case PhotosType.peoplePhotos:
  362. ImagePickerUtil.updatePhotoGroupDate(
  363. photosType, ImagePickerUtil.selectedPeoplePhotosIds);
  364. break;
  365. case PhotosType.screenshots:
  366. ImagePickerUtil.updatePhotoGroupDate(
  367. photosType, ImagePickerUtil.selectedScreenshotPhotosIds);
  368. break;
  369. case PhotosType.similarPhotos:
  370. ImagePickerUtil.updatePhotoGroupDate(
  371. photosType, ImagePickerUtil.selectedSimilarPhotosIds);
  372. break;
  373. case PhotosType.locationPhotos:
  374. ImagePickerUtil.updatePhotoGroupDate(
  375. photosType, ImagePickerUtil.selectedLocationPhotosIds);
  376. break;
  377. case PhotosType.blurryPhotos:
  378. ImagePickerUtil.updatePhotoGroupDate(
  379. photosType, ImagePickerUtil.selectedBlurryPhotosIds);
  380. break;
  381. }
  382. cleanSelections();
  383. ToastUtil.show('Delete success');
  384. Future.delayed(Duration(seconds: 2), () {
  385. SmartDialog.dismiss(tag: 'photoDeletingDialog');
  386. photoDeleteFinishDialog();
  387. });
  388. } else {
  389. SmartDialog.dismiss(tag: 'photoDeletingDialog');
  390. // 删除失败
  391. ToastUtil.show("Delete failed");
  392. }
  393. }
  394. } else {
  395. StorePage.start();
  396. }
  397. // 清理缓存
  398. PhotoManager.clearFileCache();
  399. }
  400. // 将selectedFilesSize转成String类型,然后单位转换,如果超过1MB,则转成MB,超过1GB,则转成GB,否则KB
  401. String get selectedFilesSizeString {
  402. final double sizeInKB = selectedFilesSize.value;
  403. if (sizeInKB >= 1024 * 1024) { // 先检查最大单位(GB)
  404. return "${(sizeInKB / (1024 * 1024)).toStringAsFixed(2)}GB";
  405. } else if (sizeInKB >= 1024) { // 然后检查MB
  406. return "${(sizeInKB / 1024).toStringAsFixed(2)}MB";
  407. } else { // 最后是KB
  408. return "${sizeInKB.toStringAsFixed(2)}KB";
  409. }
  410. }
  411. }