You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

388 lines
16KB

  1. import 'package:dio/dio.dart';
  2. import 'package:farm_tpf/custom_model/NotificationObjectDTO.dart';
  3. import 'package:farm_tpf/data/repository/repository.dart';
  4. import 'package:farm_tpf/data/repository/user_repository.dart';
  5. import 'package:farm_tpf/presentation/custom_widgets/widget_utils.dart';
  6. import 'package:farm_tpf/presentation/screens/account/sc_account.dart';
  7. import 'package:farm_tpf/presentation/screens/codes/code_detail_page.dart';
  8. import 'package:farm_tpf/presentation/screens/codes/code_page.dart';
  9. import 'package:farm_tpf/presentation/screens/control_device/sc_control_device.dart';
  10. import 'package:farm_tpf/presentation/screens/notification/sc_notification.dart';
  11. import 'package:farm_tpf/presentation/screens/notification/update_count_noti_bloc.dart';
  12. import 'package:farm_tpf/presentation/screens/plot/sc_plot.dart';
  13. import 'package:farm_tpf/presentation/screens/plot_detail/sc_plot_detail.dart';
  14. import 'package:farm_tpf/utils/NotificationsBloc.dart';
  15. import 'package:farm_tpf/utils/const_color.dart';
  16. import 'package:farm_tpf/utils/const_common.dart';
  17. import 'package:farm_tpf/utils/const_icons.dart';
  18. import 'package:farm_tpf/utils/local_storage.dart';
  19. import 'package:farm_tpf/utils/pref.dart';
  20. import 'package:flutter/material.dart';
  21. import 'package:flutter_svg/flutter_svg.dart';
  22. import 'package:get/get.dart';
  23. import '../qr_scan/qr_scan_page.dart';
  24. class TabbarScreen extends StatefulWidget {
  25. static Route route() {
  26. return MaterialPageRoute<void>(builder: (_) => TabbarScreen());
  27. }
  28. @override
  29. _TabbarScreenState createState() => _TabbarScreenState();
  30. }
  31. class _TabbarScreenState extends State<TabbarScreen> {
  32. Stream<LocalNotification>? _notificationsStream;
  33. UserRepository _userRepository = UserRepository();
  34. // final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  35. var pref = LocalPref();
  36. String pushkey = "";
  37. String currentFullName = "";
  38. var token;
  39. var client;
  40. final changeTabbar = Get.put(TabbarSelected());
  41. List<TabbarItem> itemsTabbar = [
  42. TabbarItem(icon: AppIcons.icPlot, title: 'Lô trồng', index: TabBarIndex.plot),
  43. // TabbarItem(icon: AppIcons.icDevice, title: 'Thiết bị', index: TabBarIndex.device),
  44. TabbarItem(icon: AppIcons.icQrManage, title: 'Quản lý QR', index: TabBarIndex.qrManage),
  45. TabbarItem(icon: AppIcons.icQr, title: 'Quét QR', index: TabBarIndex.qr),
  46. TabbarItem(icon: AppIcons.icNotification, title: 'Thông báo', index: TabBarIndex.notification),
  47. TabbarItem(icon: AppIcons.icPerson, title: 'Cá nhân', index: TabBarIndex.account)
  48. ];
  49. Future<Null> getSharedPrefs() async {
  50. token = await pref.getString(DATA_CONST.TOKEN_KEY);
  51. // currentFullName = await pref.getString(DATA_CONST.CURRENT_FULL_NAME);
  52. currentFullName = LocalStorage.getString(LocalStorageKey.full_name);
  53. var options = BaseOptions(baseUrl: ConstCommon.baseUrl);
  54. options.headers["Authorization"] = "Bearer $token";
  55. client = Dio(options);
  56. // if (Platform.isIOS) {
  57. // _firebaseMessaging.requestNotificationPermissions(IosNotificationSettings());
  58. // }
  59. // _firebaseMessaging.configure(
  60. // onMessage: (Map<String, dynamic> message) async {
  61. // print("onMessage--tabbar-: $message");
  62. // try {
  63. // final String type = message['tbCropType'];
  64. // final String contents = message['contents'];
  65. // final String tbCropId = message['tbCropId'];
  66. // updateCountNotiBloc.getNotifications((data) {}, (err) {});
  67. // final notification = LocalNotification(type, contents, tbCropId);
  68. // NotificationsBloc.instance.newNotification(notification);
  69. // if (contents == "ENV_UPDATE") {
  70. // if (Get.isSnackbarOpen) Get.back();
  71. // Get.snackbar(null, 'Thông số môi trường được cập nhật');
  72. // } else if (contents == "PIC_UPDATE") {
  73. // if (Get.isSnackbarOpen) Get.back();
  74. // Get.snackbar(null, 'Người phụ trách được cập nhật');
  75. // } else {
  76. // //Go home
  77. // }
  78. // } catch (e) {
  79. // print('error');
  80. // print(e);
  81. // }
  82. // },
  83. // onBackgroundMessage: Platform.isIOS ? null : myBackgroundMessageHandler,
  84. // onLaunch: (Map<String, dynamic> message) async {
  85. // print("onLaunch: $message");
  86. // Future.delayed(Duration(milliseconds: 500), () {
  87. // updateCountNotiBloc.getNotifications((data) {}, (err) {});
  88. // _notificationNavigateOnFCM(message);
  89. // });
  90. // },
  91. // onResume: (Map<String, dynamic> message) async {
  92. // print("onResume: $message");
  93. // updateCountNotiBloc.getNotifications((data) {}, (err) {});
  94. // _notificationNavigateOnFCM(message);
  95. // },
  96. // );
  97. // _firebaseMessaging.requestNotificationPermissions(const IosNotificationSettings(sound: true, badge: true, alert: true, provisional: true));
  98. // _firebaseMessaging.onIosSettingsRegistered.listen((IosNotificationSettings settings) {
  99. // print("Settings registered: $settings");
  100. // });
  101. // if (pushkey?.isEmpty ?? true) {
  102. // _firebaseMessaging.getToken().then((String token) {
  103. // assert(token != null);
  104. // print("Push Messaging token: $token");
  105. // _userRepository.updateFcmToken(token).then((value) {
  106. // print("send push key successful");
  107. // pref.saveString(DATA_CONST.PUSH_KEY, token);
  108. // });
  109. // // client.put("");
  110. // });
  111. // } else {
  112. // print("Don't need get push key");
  113. // }
  114. var pushKey = await pref.getString(PrefKey.push_key);
  115. _userRepository.updateFcmToken(pushKey).then((value) {
  116. print("send push key successful");
  117. });
  118. if (currentFullName?.isEmpty ?? true) {
  119. try {
  120. var currentUser = await _userRepository.getUser();
  121. pref.saveString(DATA_CONST.CURRENT_FULL_NAME, currentUser.fullName ?? '');
  122. LocalStorage.save(LocalStorageKey.full_name, currentUser.fullName ?? '');
  123. print("fullname: ${currentUser.fullName}");
  124. } catch (e) {
  125. print("error: ${e.toString()}");
  126. }
  127. }
  128. }
  129. @override
  130. void initState() {
  131. super.initState();
  132. getSharedPrefs();
  133. changeTabbar.initValue();
  134. updateCountNotiBloc.getNotifications((data) {}, (err) {});
  135. _notificationsStream = NotificationsBloc.instance.notificationsStream;
  136. _notificationsStream?.listen((notification) {
  137. updateCountNotiBloc.getNotifications((data) {}, (err) {});
  138. print('Notification: $notification');
  139. });
  140. }
  141. _notificationNavigateOnFCM(Map<String, dynamic> message) {
  142. try {
  143. final String type = message['tbCropType'];
  144. final String contents = message['contents'];
  145. final String tbCropId = message['tbCropId'];
  146. if (contents == "ENV_UPDATE") {
  147. Get.to(PlotDetailScreen(
  148. cropType: int.parse(type),
  149. cropId: int.parse(tbCropId),
  150. initialIndex: 0,
  151. ));
  152. } else if (contents == "PIC_UPDATE") {
  153. Get.to(PlotDetailScreen(
  154. cropType: int.parse(type),
  155. cropId: int.parse(tbCropId),
  156. initialIndex: 1,
  157. ));
  158. } else {
  159. //Go home
  160. }
  161. } catch (e) {
  162. //Go home
  163. }
  164. Get.to(PlotDetailScreen(
  165. cropType: 0,
  166. cropId: 1,
  167. initialIndex: 0,
  168. ));
  169. }
  170. Widget textCountNoti() {
  171. return StreamBuilder(
  172. stream: updateCountNotiBloc.actions,
  173. builder: (context, AsyncSnapshot<dynamic> snapshot) {
  174. if (snapshot.hasData) {
  175. var noti = snapshot.data as NotificationObjectDTO;
  176. var unreadNoti = (noti.numberUnreadTotal ?? 0) > 99 ? '99+' : '${noti.numberUnreadTotal}';
  177. return Text(
  178. '$unreadNoti',
  179. softWrap: true,
  180. style: TextStyle(color: Colors.white, fontSize: 10),
  181. );
  182. } else {
  183. return Text(
  184. 'O',
  185. softWrap: true,
  186. style: TextStyle(color: Colors.white, fontSize: 10),
  187. );
  188. }
  189. },
  190. );
  191. }
  192. @override
  193. Widget build(BuildContext context) {
  194. return Container(
  195. color: Colors.white,
  196. child: SafeArea(
  197. top: false,
  198. bottom: true,
  199. child: Scaffold(
  200. body: GetBuilder<TabbarSelected>(
  201. init: changeTabbar,
  202. builder: (tabbarSelected) {
  203. switch (tabbarSelected.index) {
  204. case TabBarIndex.plot:
  205. return PlotListScreen();
  206. break;
  207. // case TabBarIndex.device:
  208. // return ControlDeviceScreen();
  209. // break;
  210. case TabBarIndex.qrManage:
  211. return CodePage();
  212. break;
  213. case TabBarIndex.qr:
  214. return Container();
  215. break;
  216. case TabBarIndex.notification:
  217. return NotificationScreen();
  218. break;
  219. case TabBarIndex.account:
  220. return AccountScreen();
  221. break;
  222. default:
  223. return PlotListScreen();
  224. }
  225. }),
  226. bottomNavigationBar: Container(
  227. padding: EdgeInsets.all(4),
  228. height: 70,
  229. decoration: BoxDecoration(color: Colors.white, border: Border(top: BorderSide(color: Colors.grey, width: 0.35))),
  230. child: GetBuilder<TabbarSelected>(
  231. init: changeTabbar,
  232. builder: (tabbarSelected) {
  233. return Center(
  234. child: ListView.builder(
  235. scrollDirection: Axis.horizontal,
  236. shrinkWrap: true,
  237. physics: NeverScrollableScrollPhysics(),
  238. itemCount: itemsTabbar.length,
  239. itemBuilder: (context, index) {
  240. return GestureDetector(
  241. child: Container(
  242. width: (Get.width - 20) / 5,
  243. margin: EdgeInsets.all(1),
  244. padding: EdgeInsets.all(10),
  245. child: Column(
  246. mainAxisAlignment: MainAxisAlignment.center,
  247. children: [
  248. index == 3
  249. ? Badge(
  250. // badgeContent: textCountNoti(),
  251. // shape: BadgeShape.circle,
  252. // badgeColor: Colors.red,
  253. // position: BadgePosition(top: -15, start: 10),
  254. child: SvgPicture.asset(
  255. itemsTabbar[index].icon,
  256. width: 24,
  257. height: 24,
  258. color: (tabbarSelected.index == itemsTabbar[index].index) ? AppColors.YELLOW : AppColors.GRAY1,
  259. ),
  260. )
  261. : SvgPicture.asset(
  262. itemsTabbar[index].icon,
  263. width: 24,
  264. height: 24,
  265. color: (tabbarSelected.index == itemsTabbar[index].index) ? AppColors.YELLOW : AppColors.GRAY1,
  266. ),
  267. Flexible(
  268. child: Text(
  269. itemsTabbar[index].title,
  270. style: TextStyle(
  271. color: (tabbarSelected.index == itemsTabbar[index].index) ? AppColors.DEFAULT : Colors.grey,
  272. fontSize: 9),
  273. ),
  274. )
  275. ],
  276. )),
  277. onTap: () {
  278. //Open scan qr code when tap icon in tabbar
  279. if (index == 2) {
  280. changeTabbar.changeIndex(changeTabbar.index ?? TabBarIndex.plot);
  281. // scan(context);
  282. Get.to(
  283. QrCodeScannerScreen(),
  284. )?.then((value) {
  285. if (value != null) {
  286. _showAlertCheckCropCode(value);
  287. }
  288. });
  289. } else {
  290. changeTabbar.changeIndex(itemsTabbar[index].index);
  291. }
  292. // changeTabbar.changeIndex(itemsTabbar[index].index);
  293. },
  294. );
  295. }),
  296. );
  297. })),
  298. )));
  299. }
  300. _showAlertCheckCropCode(String qrCodeValue) async {
  301. var repository = Repository();
  302. Get.defaultDialog(title: "Kiểm tra thông tin lô ....", middleText: "", content: CircularProgressIndicator());
  303. try {
  304. Uri uri = Uri.parse(qrCodeValue);
  305. String code = uri.pathSegments.isNotEmpty ? uri.pathSegments.last : '';
  306. if (code.startsWith('LO')) {
  307. await repository.getPlotDetailByCode(code).then((value) {
  308. print("ok");
  309. if (Get.isDialogOpen ?? false) Get.back();
  310. Get.to(
  311. PlotDetailScreen(
  312. cropId: value.tbCropDTO?.id ?? -1,
  313. cropType: value.tbCropDTO?.tbCropTypeId ?? -1,
  314. initialIndex: 0,
  315. ),
  316. );
  317. }).catchError((onError) {
  318. Utils.showDialog(
  319. title: "Không tìm thấy lô",
  320. message: "Thử lại với mã tem khác?",
  321. textConfirm: "Thử lại",
  322. textCancel: "Huỷ",
  323. onConfirm: () {
  324. Get.back();
  325. // scan(context);
  326. });
  327. });
  328. } else if (code.startsWith('AC')) {
  329. var stamp = await repository.getStampDetailByCode(code: code);
  330. Get.to(() => CodeDetailPage(stampId: stamp.id ?? 0, stampCode: stamp.code ?? ''));
  331. }
  332. } catch (e) {
  333. Utils.showDialog(
  334. title: "Không tìm thấy lô",
  335. message: "Thử lại với mã tem khác?",
  336. textConfirm: "Thử lại",
  337. textCancel: "Huỷ",
  338. onConfirm: () {
  339. Get.back();
  340. // scan(context);
  341. },
  342. );
  343. }
  344. }
  345. }
  346. class TabbarSelected extends GetxController {
  347. TabBarIndex? index = TabBarIndex.plot;
  348. void initValue() {
  349. index = TabBarIndex.plot;
  350. update();
  351. }
  352. void changeIndex(TabBarIndex changedIndex) {
  353. index = changedIndex;
  354. update();
  355. }
  356. }
  357. enum TabBarIndex {
  358. plot,
  359. // device,
  360. qrManage,
  361. qr,
  362. notification,
  363. account,
  364. }
  365. class TabbarItem {
  366. TabBarIndex index;
  367. String icon;
  368. String title;
  369. TabbarItem({required this.icon, required this.title, required this.index});
  370. }