import 'dart:convert';
import 'dart:developer';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:mwf_app/model/PackageRequest_model.dart';
import 'package:flutter_app_badger/flutter_app_badger.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

import 'package:mwf_app/model/chat_master.dart';
import 'package:mwf_app/model/customer_list_model.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/service/pref.dart';
import 'package:mwf_app/service/notification_firebase.dart';
import 'package:mwf_app/set1/schedule.dart';
import 'package:mwf_app/set2/activity_relationship.dart';
import 'package:mwf_app/set2/notification.dart';
import 'package:mwf_app/set2/visiting_plan_list.dart';
import 'package:mwf_app/set3/offer_additional_list.dart';
import 'package:mwf_app/set7/chat_home.dart';
import 'package:mwf_app/set7/chat_list_group.dart';
import 'package:mwf_app/set7/chat_page.dart';
import 'package:mwf_app/set7/power_fail_user.dart';
import 'package:mwf_app/set7/public_relation_view.dart';
import 'package:mwf_app/set8/list_request_additional.dart';
import 'package:mwf_app/set9/timeline.dart';

final sharedPrefs = NotificationCount();

class NotificationCount extends ChangeNotifier {
  static int couter = 0;
  static int newsCount = 0;
  static int chatCount = 0;
  static int countGroup = 0;
  static int timelineCount = 0;
  static int scheduleCount = 0;
  static int activityCount = 0;
  static int visitplanCount = 0;
  static int visitResultCount = 0;
  static int notificationCount = 0;
  static int packageOptionCount = 0;
  static int packageRequestCount = 0;
  static int electricProblemCount = 0;
  int count = 0;

  static SharedPreferences _sharedPrefs;

  init() async {
    if (_sharedPrefs == null) {
      _sharedPrefs = await SharedPreferences.getInstance();
    }
  }

  static String notiName = "";
  String get notival => _sharedPrefs.getInt(notiName) ?? "";
 
  static getCounts(name){
    var value = _sharedPrefs.getInt(name) == null ? 0 : _sharedPrefs.getInt(name);
    return value;
  }
  static getPrefString(name){
    var value = _sharedPrefs.getString(name);
    return value;
  }
  static getPrefBool(name){
    bool value = _sharedPrefs.getBool(name);
    return value;
  }
  set notival(String value) {
    _sharedPrefs.setString(notiName, value);
  }
  void addChatCount(int number) {
    chatCount = number;
    notifyListeners();
  }
  static void setChat(int count){
    chatCount = count;
  }

  int get getChat => chatCount;

  static sumChatNotify(context, sumRunning) async {
    final list = await ChatMaster.getData();
    int calcSum = 0;
    int currentChat = getCounts("chat") == null ? 0 : getCounts("chat");
    int currentChatStore = getCounts("chat_store") == null ? 0 : getCounts("chat_store");
    int sumCurrentNumber = 0;
    int sumCurrentNumberStore = 0;
    
    list.forEach((v) async {
      final ChatMaster chatMasterList = ChatMaster.fromJson(v);
      if(chatMasterList.chatMasterId != "fb0593bf-bee9-4350-845f-9aad236f7186"){
        sumCurrentNumber = sumCurrentNumber + getCounts(chatMasterList.ca);
        sumCurrentNumberStore = sumCurrentNumberStore + getCounts(chatMasterList.ca+"_store");
      }
    });
    if(currentChat.isNegative){
      currentChat = 0;
    }
    sumCurrentNumber = sumCurrentNumber + getCounts("fb0593bf-bee9-4350-845f-9aad236f7186");
    sumCurrentNumberStore = sumCurrentNumberStore + getCounts("fb0593bf-bee9-4350-845f-9aad236f7186_store");
    if(sumCurrentNumberStore == 0){
      setChat(0);
      setPref('int', "chat", 0);
      setPref('int', "chat_store", sumRunning);
    }else{
      print("-------------> 1111111 <--------------- ");
      print("----------> Sum <---------- : " + sumCurrentNumber.toString());
      print("----> sumNotify running : " + sumRunning.toString());
      print("----------> Sum _store <---------- : " + sumCurrentNumberStore.toString());
      print("----> currentChat  : " + currentChat.toString());

      print("calc : $sumRunning  $sumCurrentNumberStore  $sumCurrentNumber");
      calcSum = (sumRunning - sumCurrentNumberStore) + sumCurrentNumber;
      print("----> calcChat  : " + calcSum.toString());
      if(sumRunning == 0 && sumCurrentNumberStore > sumRunning && sumCurrentNumber != 0){
        print("======   Condition extra =======");
        setChat(sumCurrentNumber);
        Provider.of<NotificationCount>(context,listen: false).addChatCount(sumCurrentNumber);
        setPref('int', "chat", sumCurrentNumber);
      }else if(currentChat < calcSum && calcSum != 0){
        print("======   Condition 1 =======");
        setChat(calcSum);
        Provider.of<NotificationCount>(context,listen: false).addChatCount(calcSum);
        setPref('int', "chat", calcSum);
      }else if(currentChat >= calcSum  && calcSum != 0) {
        print("======   Condition 2 =======");
        calcSum = (sumRunning - sumCurrentNumberStore) + sumCurrentNumber;
        setChat(calcSum);
        Provider.of<NotificationCount>(context,listen: false).addChatCount(calcSum);
        setPref('int', "chat", calcSum);
      }else if((sumRunning == sumCurrentNumberStore 
        && sumCurrentNumber == 0) && (calcSum == 0 && currentChat == 0)){
        print("======   Condition 3 =======");
        calcSum = 0;
        setChat(calcSum);
        Provider.of<NotificationCount>(context,listen: false).addChatCount(calcSum);
        setPref('int', "chat", calcSum);
      }
      setPref('int', "chat_store", sumRunning);
    }

    print("----> chat  : " + chatCount.toString());
    print("----> chat store : " + currentChatStore.toString());
    print("----> sumNotify running : " + sumRunning.toString());
    print("----------> Sum <---------- : " + sumCurrentNumber.toString());
    print("----------> Sum _store <---------- : " + sumCurrentNumberStore.toString());
    print("----> sumNotify : " + calcSum.toString());
    print("----> currentChat  : " + currentChat.toString());
    await NotificationCount.getCount();
  }

  static setCount(String data){
    var nameMenu = data.toLowerCase();
    switch (nameMenu) {
      case "visitplan":  // เยี่ยมเยือน
        visitplanCount =  visitplanCount + 1;
        setPref('int', "visitplan", visitplanCount);
        break;
      case "activity":  // กิจกรรมสร้างความสัมพันธ์
        activityCount = activityCount + 1;
        setPref('int', "activity", activityCount);
        break;
      case "packageoption":  // เสนอบริการเสริม
        packageOptionCount = packageOptionCount + 1;
        setPref('int', "packageoption", packageOptionCount);
        break;
      case "chat":  //แชท
        chatCount = chatCount + 1;
        print("chatCount : " + chatCount.toString());
        //setPref('int', "chat", chatCount);
        int calcChat = 0;
        int currentChat = NotificationCount.getCounts("chat");
        if(currentChat > 0) {
          calcChat = currentChat+1;
        }else{
          calcChat = chatCount;
        }
        print("currentChat : " + currentChat.toString());
        print("calcChat : " + calcChat.toString());
        setPref("int", "chat", calcChat);
        setPref('int', "chat_store", chatCount);
        break;
      case "notification":  //แจ้งเตือน
        notificationCount = notificationCount + 1;
        setPref('int', "notification", notificationCount);
        setPref('int', "notification_store", notificationCount);
        break;
      case "todolist":  // ตารางงาน
        scheduleCount = scheduleCount + 1;
        setPref('int', "todolist", scheduleCount);
        break;
      default:
        break;
    }
  }
  static Future<void> getStreamCountGroup(context) async {
    FirebaseFirestore.instance
    .collection('mwf_count_notification').doc("chat-masterid-fb0593bf-bee9-4350-845f-9aad236f7186")
    .get().then((querySnapshot) {
      countGroup = querySnapshot['running_number'];
    });
  }
  static Future<void> goStream(context) async {
    await getStreamCountGroup(context);
    final list = await ChatMaster.getData();
    int sum = 0;
    String ca = "";
    FirebaseFirestore.instance
    .collection('mwf_count_notification')
    .get()
    .then((QuerySnapshot querySnapshot) => {
      querySnapshot.docs.forEach((doc) async {
        if(doc.id.contains("chat-ca")){
          ca = doc.id.split("chat-ca-")[1].trim();
          try{
            list.forEach((v) async {
            final ChatMaster chatMasterList = ChatMaster.fromJson(v);
            if(ca == chatMasterList.ca){
              if(doc["running_number"] != 0){
                sum = sum + doc["running_number"];
              }
            }
            });
          }catch(e){
            print("e - : " + e);
          }
        }
      }),
      couter = sum,
      sum = 0,
    });
  }
  static getNumberFromCustomer(context) async {
    int calcSum = 0;
    await goStream(context);
    await Future.delayed(Duration(milliseconds: 700));
    calcSum = couter + countGroup;
    print("--- out calc sum  go stream count ::  " + couter.toString());
    print("--- getNumberFromCustomer calc sum  ::  " + calcSum.toString());
    print("--- out calc countGroup  go stream countGroup ::  " + countGroup.toString());
    couter = 0;
    await sumChatNotify(context, calcSum);
  }
  static resetNoti(notifyName){ // ห้ามใช้
    final databaseReference = FirebaseFirestore.instance;
    databaseReference
        .collection(AppStrings.collection)
        .doc(notifyName)
        .update({'running_number': 0});
  }
  static fetchSumStore(String name) async {
    int clName =  await getPref('int', "cloud_"+name) ?? 0;
    setPref('int', name+"_store", clName);
  }
  static calcNoti(String notiName, int runningNumber){
    int currentChat = getCounts("chat") == null ? 0 : getCounts("chat");
    int currentNumber = getCounts(notiName) == null ? 0 : getCounts(notiName);
    int currentNumberStore = getCounts(notiName+"_store") == null ? 0 : getCounts(notiName+"_store");
    int calc = 0;
    if(currentNumberStore == 0){
      calc = 0;
      setPref('int', notiName, 0);
      setPref('int', notiName+"_store", runningNumber);
      return calc;
    }else if(currentNumber != 0 && currentNumberStore != runningNumber){
      print("1 runningNumber");
      calc = (runningNumber - currentNumberStore) + currentNumber;
      setPref('int', notiName, calc);
      setPref('int', notiName+"_store", runningNumber);
      return calc;
    }else if (currentNumber == 0 && currentNumberStore != runningNumber){
      calc = runningNumber - currentNumberStore;
      setPref('int', notiName+"_store", runningNumber);
      print("2 runningNumber");
      setPref('int', notiName, calc);
      setPref('int', "chat", calc+currentChat);
      return calc;
    }else{
      calc = currentNumber;
      setPref('int', notiName+"_store", runningNumber);
      return calc;
    }
  }
  static getCount() {
    newsCount = getCounts("news") != null ? getCounts("news") : 0;
    chatCount = getCounts("chat") != null ? getCounts("chat") : 0;
    print("==== > Chatttttttttt ::   " + chatCount.toString());
    scheduleCount = getCounts("todolist") != null ? getCounts("todolist") : 0;
    activityCount = getCounts("activity") != null ? getCounts("activity") : 0;
    timelineCount = getCounts("timeline") != null ? getCounts("timeline") : 0;
    visitplanCount = getCounts("visitplan") != null ? getCounts("visitplan") : 0;
    notificationCount = getCounts("notification") != null ? getCounts("notification") : 0;
    packageOptionCount = getCounts("packageoption") != null ? getCounts("packageoption") : 0;
    packageRequestCount = getCounts("packagerequest") != null ? getCounts("packagerequest") : 0;
    electricProblemCount = getCounts("electricproblem") != null ? getCounts("electricproblem") : 0;
  }
  static handleCountChatNotify(message) async{
    print("Handle chat notification count...");
    int count = 0;

    if(message.isNotEmpty){
      if(message.containsKey("data") && message.containsKey("notification")){
        String type = message['data']['noti_type'].toString().toLowerCase();
        if(type == "chat") {
          count +=1;
          setCount("chat");
          
          String chatMaster = message['data']['chatMasterId'].toString().toLowerCase();
          String isChatGroup = message['data']['isGroupChat'];
          var customerCA = message['data']['CA'];
          if(isChatGroup == "true"){
            var dataGroup;
            print("======== count :: " + count.toString());
            dataGroup = NotificationCount.getCounts(chatMaster);
            if(dataGroup != null){
              //setPref("int", chatMaster, dataGroup+1);
              var g = NotificationCount.getCounts(chatMaster);
              print("======== data g :: " + g.toString());
            }else if(dataGroup == null){
              setPref("int", chatMaster, count);
            }

          }else if(isChatGroup == "false"){
            var data;
            data = await getPref("int" , customerCA);
            if(data != null){
              //setPref("int", customerCA, data+count);
            }else if(data == null){
              setPref("int", customerCA, count);
            }
          }
          count = 0;
        }
      }
    }
  }// End function handle count notification chat...
  static handleCountChat(message) async{
      print("Handle chat");
      int count = 0;
      String customerCA;

      if(message.isNotEmpty){
        if(message.containsKey("data") && message.containsKey("notification")){
          String type = message['data']['noti_type'].toString().toLowerCase();
          if(type == "chat") {
            count +=1;
            String chatMaster = message['data']['chatMasterId'].toString().toLowerCase();
            String isChatGroup = message['data']['isGroupChat'];
            Chathome.setValue(message['data']['CA']);
            customerCA = message['data']['CA'];
            
            if(isChatGroup == "true"){
              var dataGroup;
              dataGroup = await getPref("int" , chatMaster);
              if(dataGroup != null){
                //setPref("int", chatMaster, dataGroup+count);
              }else if(dataGroup == null || dataGroup == 0){
                setPref("int", chatMaster, count);
              }
              ChatListGroup.getCountGroup(chatMaster);
            }else if(isChatGroup == "false"){
              var data;
              data = await getPref("int" , customerCA);
              if(data != null){
                print("1");
                setPref("int", customerCA, data);
                //counter = await getPref('int', customerCA);
              }else if(data == null){
                print("2");
                setPref("int", customerCA, count);
                //counter = await getPref('int', customerCA);
              }
            }
            count = 0;
          }
        }
      }
  }// End function count chat
}

setClick() {
  ManageNotify.isClick = false;
}

  Future<dynamic> backgrounfHandler(Map<String, dynamic> msg) async {
    if(msg.containsKey("data")){
      print("msg");
      return ManageNotify.showNotify(msg);
    }
  }

  Future onDidReceiveLocalNotification(int id, String title, String body, String payload) async {
  print("==> onDidReceiveLocalNotification");
}

class ManageNotify {
  static String checkValue = "";
  static bool isClick = false;
  static String channelId = "1000";
  static String channelName = "pea_notification";
  static String channelDescription = "FLUTTER_NOTIFICATION_CHANNEL_DETAIL";

  static FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  static Future<void> initNotify() async {
    const initializationSettingsAndroid =
        AndroidInitializationSettings('ic_launcher');
        
    const initializationSettingsIOS = IOSInitializationSettings(
      onDidReceiveLocalNotification: onDidReceiveLocalNotification,
    );

    final initializationSettings =
        InitializationSettings(
          android : initializationSettingsAndroid, 
          iOS: initializationSettingsIOS
        );

    await flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: selectNotification);
  }

  static Future<void> subScribesNotifyTopic(FirebaseMessaging firebaseMessaging) async {
    firebaseMessaging.subscribeToTopic("pea_notification").whenComplete(()=> print("Everything is Okay.."));
    firebaseMessaging.subscribeToTopic("fb0593bf-bee9-4350-845f-9aad236f7186").whenComplete(()=> print("Everything of group Okay.."));
    final list = await CustomerList.getListCustomerAPI();
    if(list.isNotEmpty){
      try{
        list.forEach((v){
          final CustomerList customerList = CustomerList.fromJson(v);
          firebaseMessaging.subscribeToTopic(customerList.ca).whenComplete(()=> print("Everything "+customerList.ca+" is Okay.."))  ;
        });
      }catch(e){
        print("Error : " + e);
      }
    }
  }

  static Future<void> unSubScribesNotifyTopic() async {
    FirebaseMessaging firebaseMessaging = FirebaseMessaging();
    firebaseMessaging.unsubscribeFromTopic("pea_notification");
    firebaseMessaging.unsubscribeFromTopic("fb0593bf-bee9-4350-845f-9aad236f7186");
    final list = await CustomerList.getListCustomerAPI();
    if(list.isNotEmpty){
      try{
        list.forEach((v){
          final CustomerList customerList = CustomerList.fromJson(v);
          firebaseMessaging.unsubscribeFromTopic(customerList.ca);
        });
      }catch(e){
        print("Error : " + e);
      }
    }
  }

  static Future selectNotification(String payload) async {
    if (isClick) {
      print(payload);
      FirebaseNotificationModel data = FirebaseNotificationModel.fromJson(jsonDecode(payload));
      String type = data.notiType.toLowerCase();
      if( type != "chat" && type != "news"){
        print("------- Not chat ------");
        await onSelectNotify(type, data.mwfNotiTypeId);
      }else if(type == "chat"){
        print("Select");
        AppUrl.CA = data.ca;
        AppUrl.chatMasterId = data.chatMasterId;
        AppUrl.accountId = data.accountId;
        AppUrl.CustomerID = data.customerId;
        AppUrl.typeChat = data.typeChat;
        print("AppUrl.CA : " + AppUrl.CA.toString());
        print("AppUrl.chatMasterId : " + AppUrl.chatMasterId.toString());
        print("AppUrl.accountId : " + AppUrl.accountId.toString());
        print("AppUrl.CustomerID : " + AppUrl.CustomerID.toString());
        print("AppUrl.typeChat : " + AppUrl.typeChat.toString());
        print("data.customerName : " + data.customerName.toString());
        print("data.roomType : " + data.roomType.toString());
        if(data.isGroupChat){
          int newCount =  await getPref('int', data.chatMasterId);
          setPref("int", data.chatMasterId, 0);
          int calc = 0;
          bool checkChat = await checkPref("chat");
          if(checkChat){
            var chat = await getPref('int', "chat");
            calc = chat - newCount;
            if(calc.isNegative){
              calc = 0;
            }
            setPref('int', "chat", calc);
          }else{
            setPref("int", "chat", 0);
          }
        }else{
          int newCount =  await getPref('int', data.ca);
          setPref("int", data.ca, 0);
          int calc = 0;
          bool checkChat = await checkPref("chat");
          if(checkChat){
            var chat = await getPref('int', "chat");
            calc = chat - newCount;
            if(calc.isNegative){
              calc = 0;
            }
          }else{
            setPref("int", "chat", 0);
          }
          setPref('int', "chat", calc);
        }

        Get.offAll(
          ChatPages(
            masterId: data.chatMasterId,
            customerId : data.customerId,
            roomName: data.customerName,
            id: data.typeChat,
            roomType: data.roomType
          )
        );
      }else if(type == "news"){
        setPref('int', "news", 0);
        NotificationCount.newsCount = 0;
        Get.offAll(PublicRelationView(data.mwfNotiTypeId));
      }
    }
    setClick();
    payload = "";
  }

  static Future selectNotifyOnResume(FirebaseNotificationModel data) async {
    print("selectNotifyOnResume");    
    await flutterLocalNotificationsPlugin.cancelAll();
    String type = data.notiType.toLowerCase();
    if( type != "chat" && type != "news"){
      print("------- Not chat ------");
      await onSelectNotify(type, data.mwfNotiTypeId);
    }else if(type == "chat"){
      AppUrl.CA = data.ca;
      AppUrl.chatMasterId = data.chatMasterId;
      AppUrl.accountId = data.accountId;
      AppUrl.CustomerID = data.customerId;
      AppUrl.typeChat = data.typeChat;
      print("AppUrl.CA : " + AppUrl.CA.toString());
      print("AppUrl.chatMasterId : " + AppUrl.chatMasterId.toString());
      print("AppUrl.accountId : " + AppUrl.accountId.toString());
      print("AppUrl.CustomerID : " + AppUrl.CustomerID.toString());
      print("AppUrl.typeChat : " + AppUrl.typeChat.toString());
      print("data.customerName : " + data.customerName.toString());
      print("data.roomType : " + data.roomType.toString());
      if(data.isGroupChat){
        int newCount =  await getPref('int', data.chatMasterId);
        setPref("int", data.chatMasterId, 0);
        int calc = 0;
        bool checkChat = await checkPref("chat");
        if(checkChat){
          var chat = await getPref('int', "chat");
          calc = chat - newCount;
          if(calc.isNegative){
            calc = 0;
          }
          setPref('int', "chat", calc);
        }else{
          setPref("int", "chat", 0);
        }
      }else{
        int newCount =  await getPref('int', data.ca);
        setPref("int", data.ca, 0);
        int calc = 0;
        bool checkChat = await checkPref("chat");
        if(checkChat){
          var chat = await getPref('int', "chat");
          calc = chat - newCount;
          if(calc.isNegative){
            calc = 0;
          }
        }else{
          setPref("int", "chat", 0);
        }
        setPref('int', "chat", calc);
      }
      Get.offAll(
        ChatPages(
          masterId: data.chatMasterId,
          customerId : data.customerId,
          roomName: data.customerName,
          id: data.typeChat,
          roomType: data.roomType
        )
      );
    }else if(type == "news"){
      setPref('int', "news", 0);
      NotificationCount.newsCount = 0;
      Get.offAll(PublicRelationView(data.mwfNotiTypeId));
    }
    
  }

  static Future<void> showNotify(msg) async {
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
      channelId,
      channelName,
      channelDescription,
      importance: Importance.max,
      priority: Priority.high,
      ticker: 'ticker',
      enableLights: true,
      visibility: NotificationVisibility.public
    );

    var platformChannelSpecifics =
        NotificationDetails(android: androidPlatformChannelSpecifics, iOS: null);
    var data;
    FirebaseNotificationModel datas = FirebaseNotificationModel.fromJson(msg['data']);

    data = await getDataNoti(datas);
    
    await flutterLocalNotificationsPlugin.show(
      0, 
      msg['notification']['title'],
      msg['notification']['body'], 
      platformChannelSpecifics,
      payload: data
    );
    
    
    
    if (msg.isNotEmpty) {
      FlutterAppBadger.updateBadgeCount(NotificationCount.couter);
      String message = msg['data']['noti_type'].toLowerCase();
      if(message != "chat"){
        NotificationCount.setCount(message.toLowerCase());
      }
      checkValue = 'value';
      isClick = true;
      print("MSG : " + message);
    }
  }

  static getDataNoti(FirebaseNotificationModel dataNoti) async{
    print("Getdata");
    var customerId = "";
    var customerName = "";
    if(dataNoti.notiType.toLowerCase() == "chat" && dataNoti.isGroupChat == false){
      CustomerList.dataContact.clear();
      final listCus = await CustomerList.getListCustomerAPI();
      listCus.forEach((v) {
        final employeeList = CustomerList.fromJson(v);
        if(dataNoti.ca == employeeList.ca){
          customerName = employeeList.customerName;
          customerId = employeeList.customerId;
        }
      });
      final list = await ChatMaster.getData();
      // ChatMaster.data.clear();
      ChatMaster.dataGroup.clear();
      if (list != null) {
        list.forEach((v){
          final ChatMaster chatMasterList = ChatMaster.fromJson(v);
          if(chatMasterList.typeChat.toUpperCase() != "0325D48B-0E85-4FCE-854A-88328D417426" && 
              chatMasterList.ca == dataNoti.ca){
              AppUrl.typeAccount = chatMasterList.typeAccount;
              AppUrl.chatId = chatMasterList.id;
          }
        });
      }
    }
    
    var data = jsonEncode({
        "chatFullname": dataNoti.chatFullname,
        "isNewMessageChat": dataNoti.isNewMessageChat,
        "mwf_noti_type_id": dataNoti.mwfNotiTypeId,
        "fileurl": dataNoti.fileurl,
        "typeChat": dataNoti.typeChat == null ? null : dataNoti.typeChat,
        "isGroupChat": dataNoti.isGroupChat,
        "CA": dataNoti.ca == null ? "" : dataNoti.ca,
        "body": dataNoti.body,
        "time": dataNoti.time,
        "type": dataNoti.type,
        "title": dataNoti.title,
        "click_action": dataNoti.clickAction,
        "accountId": dataNoti.accountId,
        "chatMasterId": dataNoti.chatMasterId == null ? null : dataNoti.chatMasterId.toLowerCase(),
        "noti_type": dataNoti.notiType,
        "customerId" : customerId == null ? "" : customerId,
        "customerName" : customerName.isEmpty ? "ห้องสนทนารวม" : customerName,
        "branchId": dataNoti.branchId,
        "saleInfoId": dataNoti.saleInfoId,
        "roomType" : dataNoti.isGroupChat == true ? "group" : "individual"
    });
    //print(data);
    return data;
  }

  static manageOnLaunch(Map<String, dynamic> message) async {
    if(message.containsKey("data")){
      print("onLaunch : " + message.toString());
      //String msg = message['data']['noti_type'].toString().toLowerCase();
      // if(msg == "chat"){
      //   if(message['data']['accountId'] != AppUrl.userID ){
      //     await NotificationCount.handleCountChat(message);
      //     await NotificationCount.handleCountChatNotify(message);
      //   }
      // } else {
      //   NotificationCount.setCount(msg);
      // }
      await NotificationCount.getCount();            
      FirebaseNotificationModel datas = FirebaseNotificationModel.fromJson(message['data']);
      var receivedData = await ManageNotify.getDataNoti(datas);
      FirebaseNotificationModel data = FirebaseNotificationModel.fromJson(jsonDecode(receivedData));
      await ManageNotify.selectNotifyOnResume(data);
      setPref('bool', "isLaunch", true);
    }
  }

  static onSelectNotify(String routes, String notiTypeId) async {
    var route = routes.toString().toLowerCase();
    print("Select route: " + route);
    setClick();
    switch (route) {
      case "visitplan":
        Get.to(VisitingPlanList());
        break;
      case "activity":
        Get.to(ActivityRelationship());
        break;
      case "packageoption":
        Get.to(OfferAdditionalList());
        break;
      case "electricproblem":
        setPref('int', "electricproblem", 0);
        NotificationCount.electricProblemCount = 0;
        Get.offAll(PowerFail());
        break;
      case "news":
        //Get.to(PublicRelation());
        break;
      case "notification":
        setPref('int', "notification", 0);
        NotificationCount.notificationCount = 0;
        Get.to(NotificationPage());
        break;
      case "timeline":
        setPref('int', "timeline", 0);
        NotificationCount.timelineCount = 0;
        Get.to(Timeline());
        break;
      case "packagerequest":
        print("--------- packagerequest ---------");
        await getDataPackageRequest(notiTypeId);
        break;
      case "todolist":
        Get.to(Schedule());
        break;
      default:
        break;
    }
  }

  static getDataPackageRequest(String prId) async {    
    AppUrl.PR_Id = prId;
    final list = await PackageRequest
        .getDataReadList(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
    final packageRequest = PackageRequest.fromJson(list);
    AppUrl.CA = packageRequest.ca;
    setPref('int', AppStrings.packagerequest, 0);
    NotificationCount.packageRequestCount = 0;
    Get.offAll(ListRequestAdditional());
  }

}

class ChatRoomData {
  //String lastmassageTime;
  String chatMasterId;
  int counterMsg;

  ChatRoomData({
    this.chatMasterId,
    this.counterMsg,
    //this.lastmassageTime,
  });

  factory ChatRoomData.fromJson(Map <dynamic, dynamic> json){
    return ChatRoomData(
      //lastmassageTime: json['lastmassageTime'] ?? "",
      chatMasterId: json['chatMasterId'] ?? "",
      counterMsg: json['counterMsg'] ?? 0,
    );
  }

  Map<dynamic, dynamic> toJson(){
    return {
      "lastmassageTime" : this.counterMsg,
      "chatMasterId" : this.chatMasterId,
      "counterMsg" : this.counterMsg,
    };
  }
}

class Notifier extends ValueNotifier<int> {
  Notifier({int value}) : super(value ?? 0);
  setTogle(int val){
    value = val;
    NotificationCount.chatCount = val;
    print("val :: " + val.toString());
    return value;
  }
}