controller.dart 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:clean/base/base_controller.dart';
  4. import 'package:clean/dialog/loading_dialog.dart';
  5. import 'package:clean/handler/event_handler.dart';
  6. import 'package:clean/utils/expand.dart';
  7. import 'package:clean/utils/toast_util.dart';
  8. import 'package:flutter/cupertino.dart';
  9. import 'package:flutter_contacts/flutter_contacts.dart';
  10. import 'package:flutter_screenutil/flutter_screenutil.dart';
  11. import 'package:get/get.dart';
  12. import 'package:get/get_core/src/get_main.dart';
  13. import 'package:get/get_rx/src/rx_types/rx_types.dart';
  14. import 'package:path_provider/path_provider.dart';
  15. import 'package:wechat_camera_picker/wechat_camera_picker.dart';
  16. import '../../../data/consts/event_report_id.dart';
  17. class ContactBackUpController extends BaseController {
  18. // 是否为编辑状态
  19. RxBool isEdit = false.obs;
  20. // 是否全选
  21. RxBool isAllSelected = false.obs;
  22. RxList<FileSystemEntity> backupFiles = <FileSystemEntity>[].obs;
  23. // 存储选中的
  24. final RxSet<String> selectedFiles = <String>{}.obs;
  25. RxMap<String, List<File>> backupFilesMap = <String, List<File>>{}.obs;
  26. @override
  27. void onInit() {
  28. // TODO: implement onInit
  29. super.onInit();
  30. loadBackupFiles();
  31. }
  32. void init() {
  33. }
  34. // 获取备份文件列表
  35. Future<void> loadBackupFiles() async {
  36. final directory = await getApplicationDocumentsDirectory();
  37. final files = Directory('${directory.path}/contacts').listSync();
  38. final List<FileSystemEntity> entities = await Directory(
  39. '${directory.path}/contacts').list().toList();
  40. // 使用sort方法对文件列表进行排序
  41. entities.sort((a, b) {
  42. FileStat fileStatA = a.statSync();
  43. FileStat fileStatB = b.statSync();
  44. return fileStatB.changed.compareTo(fileStatA.changed);
  45. });
  46. backupFiles.clear();
  47. Map<String, List<File>> filesMap = {};
  48. for (var entity in entities) {
  49. if (entity is File && entity.path.endsWith('.json')) {
  50. backupFiles.add(entity);
  51. final fileName = entity.path
  52. .split('/')
  53. .last;
  54. final timestamp = fileName
  55. .split('_')
  56. .last
  57. .split('.')
  58. .first;
  59. final dateTime = DateTime.fromMillisecondsSinceEpoch(
  60. int.parse(timestamp));
  61. final formattedDate = _formatDate(dateTime);
  62. if (!filesMap.containsKey(formattedDate)) {
  63. filesMap[formattedDate] = [];
  64. }
  65. filesMap[formattedDate]!.add(entity);
  66. }
  67. }
  68. backupFilesMap.value = filesMap;
  69. }
  70. // 格式化日期为 "MMM dd, yyyy"
  71. String _formatDate(DateTime dateTime) {
  72. return '${_getMonthAbbreviation(dateTime.month)} ${dateTime.day}, ${dateTime
  73. .year}';
  74. }
  75. // 获取月份的缩写(如 Jan, Feb)
  76. String _getMonthAbbreviation(int month) {
  77. switch (month) {
  78. case 1:
  79. return 'Jan';
  80. case 2:
  81. return 'Feb';
  82. case 3:
  83. return 'Mar';
  84. case 4:
  85. return 'Apr';
  86. case 5:
  87. return 'May';
  88. case 6:
  89. return 'Jun';
  90. case 7:
  91. return 'Jul';
  92. case 8:
  93. return 'Aug';
  94. case 9:
  95. return 'Sep';
  96. case 10:
  97. return 'Oct';
  98. case 11:
  99. return 'Nov';
  100. case 12:
  101. return 'Dec';
  102. default:
  103. return 'Unknown';
  104. }
  105. }
  106. // 备份通讯录
  107. Future<void> backupContacts() async {
  108. EventHandler.report(EventId.event_08012);
  109. LoadingDialog.show(displayTime: 100);
  110. try {
  111. if (!await FlutterContacts.requestPermission()) {
  112. throw Exception('通讯录权限被拒绝');
  113. }
  114. List<Contact> contacts = await FlutterContacts.getContacts(
  115. withProperties: true,
  116. withThumbnail: false,
  117. );
  118. // 生成文件名
  119. final timestamp = DateTime
  120. .now()
  121. .millisecondsSinceEpoch;
  122. final fileName = '${contacts.length} contacts_$timestamp.json';
  123. // 保存到文件
  124. final directory = await getApplicationDocumentsDirectory();
  125. final dir = Directory('${directory.path}/contacts');
  126. if (!dir.existsSync()) {
  127. dir.createSync(recursive: true);
  128. }
  129. final file = File('${directory.path}/contacts/$fileName');
  130. await file.writeAsString(jsonEncode(contacts));
  131. // 刷新备份文件列表
  132. loadBackupFiles();
  133. // LoadingDialog.hide();
  134. ToastUtil.show("Successful");
  135. print('备份成功: ${file.path}');
  136. } catch (e) {
  137. LoadingDialog.hide();
  138. ToastUtil.show("Failed");
  139. print('备份失败: $e');
  140. }
  141. }
  142. // 恢复通讯录
  143. Future<void> restoreContacts(File file) async {
  144. if (!isEdit.value) {
  145. showCupertinoModalPopup(
  146. context: Get.context!,
  147. builder: (context) {
  148. return CupertinoActionSheet(
  149. title: Text(
  150. "Replace the current contacts in the phonebook with the selected backup file.",
  151. style: TextStyle(color: "#6E6E6E".color, fontSize: 12.sp,),),
  152. actions: <Widget>[
  153. //操作按钮集合
  154. CupertinoActionSheetAction(
  155. onPressed: () async {
  156. Navigator.pop(context);
  157. try {
  158. // 获取所有联系人
  159. List<Contact> contacts = await FlutterContacts.getContacts(
  160. withProperties: true,
  161. withPhoto: true,
  162. );
  163. for (var contact in contacts) {
  164. await contact.delete();
  165. }
  166. // 读取文件内容
  167. String contactsJsonString = await file.readAsString();
  168. List<dynamic> contactsJson = jsonDecode(contactsJsonString);
  169. // 恢复联系人
  170. for (var contactJson in contactsJson) {
  171. Contact contact = Contact.fromJson(contactJson);
  172. contact.id = "";
  173. await FlutterContacts.insertContact(contact);
  174. }
  175. ToastUtil.show("Successful");
  176. print('恢复成功');
  177. } catch (e) {
  178. print('恢复失败: $e');
  179. ToastUtil.show("Failed");
  180. }
  181. },
  182. child: Text(
  183. 'Restore now',
  184. style: TextStyle(
  185. color: "#007AFF".color,
  186. fontWeight: FontWeight.w500,
  187. fontSize: 16.sp,
  188. ),
  189. ),
  190. ),
  191. ],
  192. cancelButton: CupertinoActionSheetAction(
  193. //取消按钮
  194. onPressed: () {
  195. Navigator.pop(context);
  196. },
  197. child: Text(
  198. 'Cancel',
  199. style: TextStyle(
  200. color: "#007AFF".color,
  201. fontWeight: FontWeight.w500,
  202. fontSize: 16.sp,
  203. ),
  204. ),
  205. ),
  206. );
  207. },
  208. );
  209. }
  210. }
  211. // 选择/取消选择联系人
  212. void toggleSelectFile(File selectFile) {
  213. final file = backupFiles.firstWhere((file) => file.path == selectFile.path);
  214. if (selectedFiles.contains(selectFile.path)) {
  215. selectedFiles.remove(selectFile.path);
  216. } else {
  217. selectedFiles.add(selectFile.path);
  218. }
  219. // 更新全选状态
  220. isAllSelected.value = selectedFiles.length == backupFiles.length;
  221. }
  222. // 全选/取消全选
  223. void toggleSelectAll() {
  224. if (isAllSelected.value) {
  225. selectedFiles.clear();
  226. } else {
  227. selectedFiles.addAll(backupFiles.map((file) => file.path));
  228. }
  229. isAllSelected.value = !isAllSelected.value;
  230. }
  231. // 退出编辑模式时清空选择
  232. void exitEditMode() {
  233. isEdit.value = false;
  234. selectedFiles.clear();
  235. isAllSelected.value = false;
  236. }
  237. Future<void> deleteBtnClick() async {
  238. showCupertinoModalPopup(
  239. context: Get.context!,
  240. builder: (context) {
  241. return CupertinoActionSheet(
  242. actions: <Widget>[
  243. //操作按钮集合
  244. CupertinoActionSheetAction(
  245. onPressed: () async {
  246. Navigator.pop(context);
  247. // 获取要删除的资产
  248. final fileToDelete = backupFiles.where((file) => selectedFiles.contains(file.path)).toList();
  249. //
  250. for (var file in fileToDelete) {
  251. await file.delete();
  252. }
  253. ToastUtil.show("Successful");
  254. exitEditMode();
  255. loadBackupFiles();
  256. },
  257. child: Text(
  258. 'Delete',
  259. style: TextStyle(
  260. color: "#FC4C4F".color,
  261. fontWeight: FontWeight.w500,
  262. fontSize: 16.sp,
  263. ),
  264. ),
  265. ),
  266. ],
  267. cancelButton: CupertinoActionSheetAction(
  268. //取消按钮
  269. onPressed: () {
  270. Navigator.pop(context);
  271. },
  272. child: Text(
  273. 'Cancel',
  274. style: TextStyle(
  275. color: "#007AFF".color,
  276. fontWeight: FontWeight.w500,
  277. fontSize: 16.sp,
  278. ),
  279. ),
  280. ),
  281. );
  282. },
  283. );
  284. }
  285. }