analysis_controller.dart 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import 'dart:math';
  2. import 'package:classify_photo/classify_photo.dart';
  3. import 'package:clean/base/base_controller.dart';
  4. import 'package:clean/dialog/photo_uploading_dialog.dart';
  5. import 'package:clean/module/analysis/analysis_state.dart';
  6. import 'package:clean/utils/expand.dart';
  7. import 'package:flutter/Material.dart';
  8. import 'package:flutter/cupertino.dart';
  9. import 'package:flutter_screenutil/flutter_screenutil.dart';
  10. import 'package:get/get.dart';
  11. import 'package:get/get_core/src/get_main.dart';
  12. import 'package:get/get_rx/src/rx_types/rx_types.dart';
  13. import 'package:permission_handler/permission_handler.dart';
  14. import 'package:wechat_camera_picker/wechat_camera_picker.dart';
  15. import '../../model/asset_info.dart';
  16. import '../../utils/file_utils.dart';
  17. import '../../utils/image_util.dart';
  18. import '../../utils/toast_util.dart';
  19. import '../image_picker/image_picker_assets.dart';
  20. class AnalysisController extends BaseController {
  21. // 是否为编辑状态
  22. RxBool isEdit = false.obs;
  23. // 使用共享状态
  24. RxList<AssetInfo> imageList = AnalysisState.imageList;
  25. RxMap<String, List<AssetInfo>> assetsByMonth = AnalysisState.assetsByMonth;
  26. // 获取月份数量
  27. int get monthCount => assetsByMonth.length;
  28. // 获取总图片数量
  29. int get totalAssetCount =>
  30. assetsByMonth.values.fold(0, (sum, list) => sum + list.length);
  31. // 存储选中的图片ID
  32. final RxSet<String> selectedAssets = <String>{}.obs;
  33. // 是否全选
  34. RxBool isAllSelected = false.obs;
  35. // 选中图片的总容量(字节)
  36. final RxInt selectedTotalSize = 0.obs;
  37. @override
  38. void onInit() {
  39. // TODO: implement onInit
  40. super.onInit();
  41. loadAssets();
  42. }
  43. // 加载并分组图片
  44. Future<void> loadAssets() async {
  45. var newImageList = <AssetInfo>[];
  46. newImageList = await FileUtils.getAllAssets(FileType.analysis);
  47. AnalysisState.imageList.value = newImageList;
  48. AnalysisState.updateMonthlyAssets();
  49. if (newImageList.isEmpty) {
  50. isEdit.value = false;
  51. return;
  52. }
  53. // 清空现有数据
  54. assetsByMonth.clear();
  55. // 按月份分组
  56. for (var asset in newImageList) {
  57. final monthKey = ImageUtil.getMonthKey(asset.createDateTime);
  58. if (!assetsByMonth.containsKey(monthKey)) {
  59. assetsByMonth[monthKey] = [];
  60. }
  61. assetsByMonth[monthKey]!.add(asset);
  62. asset.dateTitle = ImageUtil.formatMonthKey(monthKey);
  63. }
  64. newImageList.sort((a, b) => b.createDateTime.compareTo(a.createDateTime));
  65. AnalysisState.imageList.value = newImageList;
  66. AnalysisState.updateMonthlyAssets();
  67. // 对每个月份内的图片按时间排序(新的在前)
  68. assetsByMonth.forEach((key, list) {
  69. list.sort((a, b) => b.createDateTime.compareTo(a.createDateTime));
  70. });
  71. // 打印分组结果
  72. assetsByMonth.forEach((key, assets) {
  73. print('${ImageUtil.formatMonthKey(key)}: ${assets.length} photos');
  74. });
  75. }
  76. // 上传按钮点击
  77. void uploadBtnClick() {
  78. openGallery();
  79. // showCupertinoModalPopup(
  80. // context: Get.context!,
  81. // builder: (context) {
  82. // return CupertinoActionSheet(
  83. // actions: <Widget>[
  84. // //操作按钮集合
  85. // CupertinoActionSheetAction(
  86. // onPressed: () {
  87. // Navigator.pop(context);
  88. // openGallery();
  89. // },
  90. // child: Text(
  91. // 'Upload from Gallery',
  92. // style: TextStyle(
  93. // color: "#007AFF".color,
  94. // fontWeight: FontWeight.w500,
  95. // fontSize: 16.sp,
  96. // ),
  97. // ),
  98. // ),
  99. // CupertinoActionSheetAction(
  100. // onPressed: () {
  101. // Navigator.pop(context);
  102. // openCamera();
  103. // },
  104. // child: Text(
  105. // 'Take and Upload',
  106. // style: TextStyle(
  107. // color: "#007AFF".color,
  108. // fontWeight: FontWeight.w500,
  109. // fontSize: 16.sp,
  110. // ),
  111. // ),
  112. // ),
  113. // ],
  114. // cancelButton: CupertinoActionSheetAction(
  115. // //取消按钮
  116. // onPressed: () {
  117. // Navigator.pop(context);
  118. // },
  119. // child: Text(
  120. // 'Cancel',
  121. // style: TextStyle(
  122. // color: "#007AFF".color,
  123. // fontWeight: FontWeight.w500,
  124. // fontSize: 16.sp,
  125. // ),
  126. // ),
  127. // ),
  128. // );
  129. // },
  130. // );
  131. }
  132. // 保存并刷新图片列表
  133. Future<void> saveAndRefreshAssets(List<AssetEntity> assets) async {
  134. for (var asset in assets) {
  135. await FileUtils.saveAsset(FileType.analysis, asset);
  136. }
  137. showDialog(
  138. context: Get.context!,
  139. barrierDismissible: false, // 防止点击外部关闭
  140. builder: (context) => UploadingDialog(
  141. duration: const Duration(seconds: 3),
  142. onComplete: () {
  143. loadAssets();
  144. ToastUtil.show("Successful");
  145. // 这里可以添加完成后的操作
  146. },
  147. ),
  148. );
  149. // 重新加载图片列表
  150. }
  151. // 选择/取消选择图片
  152. void toggleSelectAsset(String assetId) {
  153. final asset = imageList.firstWhere((asset) => asset.id == assetId);
  154. if (selectedAssets.contains(assetId)) {
  155. selectedAssets.remove(assetId);
  156. if (asset.size != null) {
  157. selectedTotalSize.value -= asset.size!;
  158. }
  159. } else {
  160. selectedAssets.add(assetId);
  161. if (asset.size != null) {
  162. selectedTotalSize.value += asset.size!;
  163. }
  164. }
  165. // 更新全选状态
  166. isAllSelected.value = selectedAssets.length == imageList.length;
  167. }
  168. // 全选/取消全选
  169. void toggleSelectAll() {
  170. if (isAllSelected.value) {
  171. selectedAssets.clear();
  172. selectedTotalSize.value = 0;
  173. } else {
  174. selectedAssets.addAll(imageList.map((asset) => asset.id));
  175. selectedTotalSize.value = imageList.fold(
  176. 0, (sum, asset) => sum + (asset.size != null ? asset.size! : 0));
  177. }
  178. isAllSelected.value = !isAllSelected.value;
  179. }
  180. // 退出编辑模式时清空选择
  181. void exitEditMode() {
  182. isEdit.value = false;
  183. selectedAssets.clear();
  184. isAllSelected.value = false;
  185. selectedTotalSize.value = 0;
  186. }
  187. // 删除文件
  188. void deleteBtnClick() {
  189. // 获取要删除的资产
  190. final assetsToDelete =
  191. imageList.where((asset) => selectedAssets.contains(asset.id)).toList();
  192. for (var asset in assetsToDelete) {
  193. FileUtils.deleteAsset(FileType.analysis, asset.id.substring(0, 36));
  194. }
  195. selectedTotalSize.value = 0;
  196. loadAssets();
  197. }
  198. // 格式化文件大小显示
  199. String formatFileSize(int bytes) {
  200. if (bytes <= 0) return "Delete";
  201. final units = ['B', 'KB', 'MB', 'GB'];
  202. int digitGroups = (log(bytes) / log(1024)).floor();
  203. if (bytes == 0) {
  204. return "Delete";
  205. } else {
  206. return "Delete(${(bytes / pow(1024, digitGroups)).toStringAsFixed(1)} ${units[digitGroups]})";
  207. }
  208. }
  209. // 开启图库
  210. Future<void> openGallery() async {
  211. var status = await Permission.photos.status;
  212. if (status == PermissionStatus.granted) {
  213. List<AssetEntity> assets = <AssetEntity>[];
  214. for (var asset in imageList) {
  215. var newAsset = await asset.toAssetEntity();
  216. if (newAsset != null) {
  217. assets.add(newAsset);
  218. }
  219. }
  220. List<AssetEntity>? pickList = await ImagePickAssets.pick();
  221. if (pickList != null && pickList.isNotEmpty) {
  222. await saveAndRefreshAssets(pickList);
  223. final asset = pickList.first;
  224. final file = await asset.originFile;
  225. // final exifInfo = await ClassifyPhoto().getPhotoExif(file!.path);
  226. // print(exifInfo);
  227. }
  228. } else {
  229. ToastUtil.show("请先开启权限");
  230. }
  231. }
  232. // 开启相机
  233. Future<void> openCamera() async {
  234. final entity = await CameraPicker.pickFromCamera(
  235. Get.context!,
  236. pickerConfig: const CameraPickerConfig(),
  237. );
  238. if (entity != null) {
  239. await saveAndRefreshAssets([entity]);
  240. }
  241. }
  242. }