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.

367 lines
15KB

  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>(
  194. init: changeTabbar,
  195. builder: (tabbarSelected) {
  196. switch (tabbarSelected.index) {
  197. case TabBarIndex.plot:
  198. return PlotListScreen();
  199. break;
  200. // case TabBarIndex.device:
  201. // return ControlDeviceScreen();
  202. // break;
  203. case TabBarIndex.qrManage:
  204. return CodePage();
  205. break;
  206. case TabBarIndex.qr:
  207. return Container();
  208. break;
  209. case TabBarIndex.notification:
  210. return NotificationScreen();
  211. break;
  212. case TabBarIndex.account:
  213. return AccountScreen();
  214. break;
  215. default:
  216. return PlotListScreen();
  217. }
  218. }),
  219. bottomNavigationBar: Container(
  220. padding: EdgeInsets.all(4),
  221. height: 70,
  222. decoration: BoxDecoration(color: Colors.white, border: Border(top: BorderSide(color: Colors.grey, width: 0.35))),
  223. child: GetBuilder<TabbarSelected>(
  224. init: changeTabbar,
  225. builder: (tabbarSelected) {
  226. return Center(
  227. child: ListView.builder(
  228. scrollDirection: Axis.horizontal,
  229. shrinkWrap: true,
  230. physics: NeverScrollableScrollPhysics(),
  231. itemCount: itemsTabbar.length,
  232. itemBuilder: (context, index) {
  233. return GestureDetector(
  234. child: Container(
  235. width: (Get.width - 20) / 5,
  236. margin: EdgeInsets.all(1),
  237. padding: EdgeInsets.all(10),
  238. child: Column(
  239. mainAxisAlignment: MainAxisAlignment.center,
  240. children: [
  241. index == 3
  242. ? Badge(
  243. // badgeContent: textCountNoti(),
  244. // shape: BadgeShape.circle,
  245. // badgeColor: Colors.red,
  246. // position: BadgePosition(top: -15, start: 10),
  247. child: SvgPicture.asset(
  248. itemsTabbar[index].icon,
  249. width: 24,
  250. height: 24,
  251. color: (tabbarSelected.index == itemsTabbar[index].index) ? AppColors.YELLOW : AppColors.GRAY1,
  252. ),
  253. )
  254. : 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. Flexible(
  261. child: Text(
  262. itemsTabbar[index].title,
  263. style: TextStyle(
  264. color: (tabbarSelected.index == itemsTabbar[index].index) ? AppColors.DEFAULT : Colors.grey,
  265. fontSize: 9),
  266. ),
  267. )
  268. ],
  269. )),
  270. onTap: () {
  271. //Open scan qr code when tap icon in tabbar
  272. if (index == 2) {
  273. changeTabbar.changeIndex(changeTabbar.index ?? TabBarIndex.plot);
  274. // scan(context);
  275. Get.to(
  276. QrCodeScannerScreen(),
  277. )?.then((value) {
  278. if (value != null) {
  279. _showAlertCheckCropCode(value);
  280. }
  281. });
  282. } else {
  283. changeTabbar.changeIndex(itemsTabbar[index].index);
  284. }
  285. // changeTabbar.changeIndex(itemsTabbar[index].index);
  286. },
  287. );
  288. }),
  289. );
  290. })),
  291. )));
  292. }
  293. _showAlertCheckCropCode(String cropCode) async {
  294. var repository = Repository();
  295. Get.defaultDialog(title: "Kiểm tra thông tin lô ....", middleText: "", content: CircularProgressIndicator());
  296. try {
  297. await repository.getPlotDetailByCode(cropCode).then((value) {
  298. print("ok");
  299. if (Get.isDialogOpen ?? false) Get.back();
  300. Get.to(PlotDetailScreen(cropId: value.tbCropDTO?.id ?? -1, cropType: value.tbCropDTO?.tbCropTypeId ?? -1, initialIndex: 0));
  301. }).catchError((onError) {
  302. Utils.showDialog(
  303. title: "Không tìm thấy lô",
  304. message: "Thử lại với mã tem khác?",
  305. textConfirm: "Thử lại",
  306. textCancel: "Huỷ",
  307. onConfirm: () {
  308. Get.back();
  309. // scan(context);
  310. });
  311. });
  312. } catch (e) {
  313. Utils.showDialog(
  314. title: "Không tìm thấy lô",
  315. message: "Thử lại với mã tem khác?",
  316. textConfirm: "Thử lại",
  317. textCancel: "Huỷ",
  318. onConfirm: () {
  319. Get.back();
  320. // scan(context);
  321. });
  322. }
  323. }
  324. }
  325. class TabbarSelected extends GetxController {
  326. TabBarIndex? index = TabBarIndex.plot;
  327. void initValue() {
  328. index = TabBarIndex.plot;
  329. update();
  330. }
  331. void changeIndex(TabBarIndex changedIndex) {
  332. index = changedIndex;
  333. update();
  334. }
  335. }
  336. enum TabBarIndex {
  337. plot,
  338. // device,
  339. qrManage,
  340. qr,
  341. notification,
  342. account,
  343. }
  344. class TabbarItem {
  345. TabBarIndex index;
  346. String icon;
  347. String title;
  348. TabbarItem({required this.icon, required this.title, required this.index});
  349. }