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.

350 lines
14KB

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