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.

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