import 'package:dio/dio.dart'; import 'package:farm_tpf/custom_model/NotificationObjectDTO.dart'; import 'package:farm_tpf/data/repository/repository.dart'; import 'package:farm_tpf/data/repository/user_repository.dart'; import 'package:farm_tpf/presentation/custom_widgets/widget_utils.dart'; import 'package:farm_tpf/presentation/screens/account/sc_account.dart'; import 'package:farm_tpf/presentation/screens/codes/code_page.dart'; import 'package:farm_tpf/presentation/screens/control_device/sc_control_device.dart'; import 'package:farm_tpf/presentation/screens/notification/sc_notification.dart'; import 'package:farm_tpf/presentation/screens/notification/update_count_noti_bloc.dart'; import 'package:farm_tpf/presentation/screens/plot/sc_plot.dart'; import 'package:farm_tpf/presentation/screens/plot_detail/sc_plot_detail.dart'; import 'package:farm_tpf/utils/NotificationsBloc.dart'; import 'package:farm_tpf/utils/const_color.dart'; import 'package:farm_tpf/utils/const_common.dart'; import 'package:farm_tpf/utils/const_icons.dart'; import 'package:farm_tpf/utils/pref.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:get/get.dart'; import '../qr_scan/qr_scan_page.dart'; class TabbarScreen extends StatefulWidget { static Route route() { return MaterialPageRoute(builder: (_) => TabbarScreen()); } @override _TabbarScreenState createState() => _TabbarScreenState(); } class _TabbarScreenState extends State { Stream? _notificationsStream; UserRepository _userRepository = UserRepository(); // final FirebaseMessaging _firebaseMessaging = FirebaseMessaging(); var pref = LocalPref(); String pushkey = ""; String currentFullName = ""; var token; var client; final changeTabbar = Get.put(TabbarSelected()); List itemsTabbar = [ TabbarItem(icon: AppIcons.icPlot, title: 'Lô trồng', index: TabBarIndex.plot), TabbarItem(icon: AppIcons.icDevice, title: 'Thiết bị', index: TabBarIndex.device), // TabbarItem(icon: AppIcons.icQrManage, title: 'Quản lý QR', index: TabBarIndex.qrManage), TabbarItem(icon: AppIcons.icQr, title: 'Quét QR', index: TabBarIndex.qr), TabbarItem(icon: AppIcons.icNotification, title: 'Thông báo', index: TabBarIndex.notification), TabbarItem(icon: AppIcons.icPerson, title: 'Cá nhân', index: TabBarIndex.account) ]; Future getSharedPrefs() async { token = await pref.getString(DATA_CONST.TOKEN_KEY); pushkey = await pref.getString(DATA_CONST.PUSH_KEY); currentFullName = await pref.getString(DATA_CONST.CURRENT_FULL_NAME); var options = BaseOptions(baseUrl: ConstCommon.baseUrl); options.headers["Authorization"] = "Bearer $token"; client = Dio(options); // if (Platform.isIOS) { // _firebaseMessaging.requestNotificationPermissions(IosNotificationSettings()); // } // _firebaseMessaging.configure( // onMessage: (Map message) async { // print("onMessage--tabbar-: $message"); // try { // final String type = message['tbCropType']; // final String contents = message['contents']; // final String tbCropId = message['tbCropId']; // updateCountNotiBloc.getNotifications((data) {}, (err) {}); // final notification = LocalNotification(type, contents, tbCropId); // NotificationsBloc.instance.newNotification(notification); // if (contents == "ENV_UPDATE") { // if (Get.isSnackbarOpen) Get.back(); // Get.snackbar(null, 'Thông số môi trường được cập nhật'); // } else if (contents == "PIC_UPDATE") { // if (Get.isSnackbarOpen) Get.back(); // Get.snackbar(null, 'Người phụ trách được cập nhật'); // } else { // //Go home // } // } catch (e) { // print('error'); // print(e); // } // }, // onBackgroundMessage: Platform.isIOS ? null : myBackgroundMessageHandler, // onLaunch: (Map message) async { // print("onLaunch: $message"); // Future.delayed(Duration(milliseconds: 500), () { // updateCountNotiBloc.getNotifications((data) {}, (err) {}); // _notificationNavigateOnFCM(message); // }); // }, // onResume: (Map message) async { // print("onResume: $message"); // updateCountNotiBloc.getNotifications((data) {}, (err) {}); // _notificationNavigateOnFCM(message); // }, // ); // _firebaseMessaging.requestNotificationPermissions(const IosNotificationSettings(sound: true, badge: true, alert: true, provisional: true)); // _firebaseMessaging.onIosSettingsRegistered.listen((IosNotificationSettings settings) { // print("Settings registered: $settings"); // }); // if (pushkey?.isEmpty ?? true) { // _firebaseMessaging.getToken().then((String token) { // assert(token != null); // print("Push Messaging token: $token"); // _userRepository.updateFcmToken(token).then((value) { // print("send push key successful"); // pref.saveString(DATA_CONST.PUSH_KEY, token); // }); // // client.put(""); // }); // } else { // print("Don't need get push key"); // } if (currentFullName?.isEmpty ?? true) { try { var currentUser = await _userRepository.getUser(); pref.saveString(DATA_CONST.CURRENT_FULL_NAME, currentUser.fullName ?? ''); print("fullname: ${currentUser.fullName}"); } catch (e) { print("error: ${e.toString()}"); } } } @override void initState() { super.initState(); getSharedPrefs(); changeTabbar.initValue(); updateCountNotiBloc.getNotifications((data) {}, (err) {}); _notificationsStream = NotificationsBloc.instance.notificationsStream; _notificationsStream?.listen((notification) { updateCountNotiBloc.getNotifications((data) {}, (err) {}); print('Notification: $notification'); }); } _notificationNavigateOnFCM(Map message) { try { final String type = message['tbCropType']; final String contents = message['contents']; final String tbCropId = message['tbCropId']; if (contents == "ENV_UPDATE") { Get.to(PlotDetailScreen( cropType: int.parse(type), cropId: int.parse(tbCropId), initialIndex: 0, )); } else if (contents == "PIC_UPDATE") { Get.to(PlotDetailScreen( cropType: int.parse(type), cropId: int.parse(tbCropId), initialIndex: 1, )); } else { //Go home } } catch (e) { //Go home } Get.to(PlotDetailScreen( cropType: 0, cropId: 1, initialIndex: 0, )); } Widget textCountNoti() { return StreamBuilder( stream: updateCountNotiBloc.actions, builder: (context, AsyncSnapshot snapshot) { if (snapshot.hasData) { var noti = snapshot.data as NotificationObjectDTO; var unreadNoti = (noti.numberUnreadTotal ?? 0) > 99 ? '99+' : '${noti.numberUnreadTotal}'; return Text( '$unreadNoti', softWrap: true, style: TextStyle(color: Colors.white, fontSize: 10), ); } else { return Text( 'O', softWrap: true, style: TextStyle(color: Colors.white, fontSize: 10), ); } }, ); } @override Widget build(BuildContext context) { return Container( color: Colors.white, child: SafeArea( top: false, bottom: true, child: Scaffold( body: GetBuilder( init: changeTabbar, builder: (tabbarSelected) { switch (tabbarSelected.index) { case TabBarIndex.plot: return PlotListScreen(); break; case TabBarIndex.device: return ControlDeviceScreen(); break; // case TabBarIndex.qrManage: // return CodePage(); // break; case TabBarIndex.qr: return Container(); break; case TabBarIndex.notification: return NotificationScreen(); break; case TabBarIndex.account: return AccountScreen(); break; default: return PlotListScreen(); } }), bottomNavigationBar: Container( padding: EdgeInsets.all(4), height: 70, decoration: BoxDecoration(color: Colors.white, border: Border(top: BorderSide(color: Colors.grey, width: 0.35))), child: GetBuilder( init: changeTabbar, builder: (tabbarSelected) { return Center( child: ListView.builder( scrollDirection: Axis.horizontal, shrinkWrap: true, physics: NeverScrollableScrollPhysics(), itemCount: itemsTabbar.length, itemBuilder: (context, index) { return GestureDetector( child: Container( width: (Get.width - 20) / 5, margin: EdgeInsets.all(1), padding: EdgeInsets.all(10), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ index == 3 ? Badge( // badgeContent: textCountNoti(), // shape: BadgeShape.circle, // badgeColor: Colors.red, // position: BadgePosition(top: -15, start: 10), child: SvgPicture.asset( itemsTabbar[index].icon, width: 24, height: 24, color: (tabbarSelected.index == itemsTabbar[index].index) ? AppColors.YELLOW : AppColors.GRAY1, ), ) : SvgPicture.asset( itemsTabbar[index].icon, width: 24, height: 24, color: (tabbarSelected.index == itemsTabbar[index].index) ? AppColors.YELLOW : AppColors.GRAY1, ), Flexible( child: Text( itemsTabbar[index].title, style: TextStyle( color: (tabbarSelected.index == itemsTabbar[index].index) ? AppColors.DEFAULT : Colors.grey, fontSize: 9), ), ) ], )), onTap: () { //Open scan qr code when tap icon in tabbar if (index == 2) { changeTabbar.changeIndex(changeTabbar.index ?? TabBarIndex.plot); // scan(context); Get.to( QrCodeScannerScreen(), )?.then((value) { if (value != null) { _showAlertCheckCropCode(value); } }); } else { changeTabbar.changeIndex(itemsTabbar[index].index); } // changeTabbar.changeIndex(itemsTabbar[index].index); }, ); }), ); })), ))); } _showAlertCheckCropCode(String cropCode) async { var repository = Repository(); Get.defaultDialog(title: "Kiểm tra thông tin lô ....", middleText: "", content: CircularProgressIndicator()); try { await repository.getPlotDetailByCode(cropCode).then((value) { print("ok"); if (Get.isDialogOpen ?? false) Get.back(); Get.to(PlotDetailScreen(cropId: value.tbCropDTO?.id ?? -1, cropType: value.tbCropDTO?.tbCropTypeId ?? -1, initialIndex: 0)); }).catchError((onError) { Utils.showDialog( title: "Không tìm thấy lô", message: "Thử lại với mã tem khác?", textConfirm: "Thử lại", textCancel: "Huỷ", onConfirm: () { Get.back(); // scan(context); }); }); } catch (e) { Utils.showDialog( title: "Không tìm thấy lô", message: "Thử lại với mã tem khác?", textConfirm: "Thử lại", textCancel: "Huỷ", onConfirm: () { Get.back(); // scan(context); }); } } } class TabbarSelected extends GetxController { TabBarIndex? index = TabBarIndex.plot; void initValue() { index = TabBarIndex.plot; update(); } void changeIndex(TabBarIndex changedIndex) { index = changedIndex; update(); } } enum TabBarIndex { plot, device, // qrManage, qr, notification, account, } class TabbarItem { TabBarIndex index; String icon; String title; TabbarItem({required this.icon, required this.title, required this.index}); }