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.

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