import 'dart:convert';
import 'dart:io';
import 'dart:ui';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mwf_app/screen/bottom_menu.dart';
import 'package:mwf_app/service/api.dart';
import 'package:mwf_app/service/assets.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/drawer.dart';
import 'package:mwf_app/service/fontsize.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/notification_count.dart';
import 'package:mwf_app/service/notification_firebase.dart';
import 'package:mwf_app/service/pref.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/shadow.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/set1/schedule.dart';
import 'package:mwf_app/set2/list_customer.dart';
import 'package:mwf_app/set2/notification.dart';
import 'package:mwf_app/set7/chat_home.dart';
import 'package:mwf_app/set7/power_fail_user.dart';
import 'package:mwf_app/set7/public_relation.dart';
import 'package:mwf_app/set8/performance_statistics.dart';
import 'package:mwf_app/set8/request_additional.dart';
import 'package:mwf_app/set9/timeline.dart';
import 'package:provider/provider.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  bool isLoading = false;
  String currentPage = 'home';
  String collection;
  String doc;
  final _channel = const MethodChannel('com.pea/app_retain');

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();
    countVisitor();
    ManageNotify.initNotify();
    initFirebaseMessaging();
    setPref('bool', "isAppOpen", true);
  }

  void initFirebaseMessaging() async {
    FirebaseMessaging firebaseMessaging = FirebaseMessaging();
    await ManageNotify.subScribesNotifyTopic(firebaseMessaging);
    // firebaseMessaging.subscribeToTopic("pea_notification").whenComplete(()=> print("Everything is Okay.."));
    // firebaseMessaging.subscribeToTopic("fb0593bf-bee9-4350-845f-9aad236f7186").whenComplete(()=> print("Everything of group Okay.."));

    firebaseMessaging.configure(
      onBackgroundMessage: backgrounfHandler,
      onMessage: (Map<String, dynamic> message) async {
        if (message.isNotEmpty) {
          print("::  " + message.toString());
          print(currentPage);
          setState(() {
            if (message['data']['noti_type'].toString().toLowerCase() ==
                "chat") {
              if (message['data']['accountId'] != AppUrl.userID) {
                NotificationCount.handleCountChat(message);
                NotificationCount.handleCountChatNotify(message);
                ManageNotify.showNotify(message);
              }
            } else {
              ManageNotify.showNotify(message);
            }
          });
        } else {
          message.clear();
        }
      },
      onLaunch: (Map<String, dynamic> message) async {
        bool status = NotificationCount.getPrefBool("isLaunch") == null
            ? true
            : NotificationCount.getPrefBool("isLaunch");
        if (status == false) {
          if (message.containsKey("data")) {
            await ManageNotify.manageOnLaunch(message);
          }
        }
      },
      onResume: (Map<String, dynamic> message) async {
        if (message.containsKey("data")) {
          FirebaseNotificationModel datas =
              FirebaseNotificationModel.fromJson(message['data']);
          var receivedData = await ManageNotify.getDataNoti(datas);
          FirebaseNotificationModel data =
              FirebaseNotificationModel.fromJson(jsonDecode(receivedData));
          await ManageNotify.selectNotifyOnResume(data);
          message.clear();
        }
      },
    );

    firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, badge: true, alert: true));

    firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    });

    firebaseMessaging.getToken().then((String token) {
      assert(token != null);
      print("Token : $token");
    });
  }

  countVisitor() async {
    final response = await AppApi.apiGetRequest(
        AppUrl.VisitCount + "?authenKey=" + AppUrl.AuthenKey);
    try {
      return response;
    } catch (e) {
      print(e);
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.inactive) {
      setPref('bool', "isAppOpen", false);
      setPref('bool', "isLaunch", false);
    } else if (state == AppLifecycleState.resumed) {
      print("--------------> " + state.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    NotificationCount.getNumberFromCustomer(context);
    NotificationCount.chatCount = NotificationCount.getCounts("chat");
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    double _width = MediaQuery.of(context).size.width;
    return Scaffold(
      key: _scaffoldKey,
      drawer: SizedBox(width: mediaQuery(context, 'w', 990), child: Drawers()),
      body: WillPopScope(
        onWillPop: () async {
          if (Platform.isAndroid) {
            if (Navigator.of(context).canPop()) {
              return Future.value(true);
            } else {
              _channel.invokeMethod("sendToBackground");
              return Future.value(false);
            }
          } else {
            return Future.value(true);
          }
        },
        child: Stack(
          children: <Widget>[
            Container(
              width: _width,
              height: mediaQuery(context, 'h', 796.7),
              color: Color(0xFFf2f5f7),
            ),
            Container(
              width: mediaQuery(context, 'w', 1125),
              height: mediaQuery(context, 'h', 796.7),
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(
                    AppAssets.bg_home_layer1,
                  ),
                  fit: BoxFit.cover,
                ),
              ),
              child: Container(
                padding: EdgeInsets.fromLTRB(
                  mediaQuery(context, 'w', 31),
                  mediaQuery(context, 'h', 130),
                  mediaQuery(context, 'w', 31),
                  mediaQuery(context, 'h', 0),
                ),
                child: Stack(
                  children: <Widget>[
                    Positioned(
                      left: mediaQuery(context, 'w', 20),
                      child: GestureDetector(
                        onTap: () {
                          _scaffoldKey.currentState.openDrawer();
                        },
                        child: Image.asset(
                          AppAssets.bg_sort_icon,
                          width: mediaQuery(context, 'w', 88.25),
                        ),
                      ),
                    ),
                    Positioned(
                      right: mediaQuery(context, 'w', 20),
                      child: GestureDetector(
                        onTap: () async {
                          comfirmLogut(context);
                        },
                        child: Image.asset(
                          AppAssets.logout_icon,
                          width: mediaQuery(context, 'w', 60),
                        ),
                      ),
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: <Widget>[
                            Container(
                              width: mediaQuery(context, 'h', 236),
                              height: mediaQuery(context, 'h', 236),
                              margin: EdgeInsets.only(
                                top: mediaQuery(context, 'h', 70),
                              ),
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                border: Border.all(
                                  color: Colors.white,
                                  width: 2,
                                ),
                                boxShadow: [
                                  appShadow(),
                                ],
                                image: DecorationImage(
                                  fit: BoxFit.fill,
                                  image: AssetImage(AppAssets.imageProfile),
                                ),
                              ),
                            )
                          ],
                        ),
                        SizedBox(
                          height: mediaQuery(context, 'h', 25),
                        ),
                        Text(
                          AppStrings.profileFullName,
                          style: TextStyle(
                            fontSize: mediaQuery(context, 'h', AppFontSize.h1),
                            color: Colors.white,
                          ),
                        ),
                        SizedBox(
                          height: mediaQuery(context, 'h', 10),
                        ),
                        Text(
                          //'หัวหน้าแผนก',
                          AppStrings.profilePosition,
                          style: TextStyle(
                            fontSize: mediaQuery(context, 'h', AppFontSize.h2),
                            color: Colors.white,
                          ),
                        ),
                        Text(
                          //'แผนกพัฒนาระบบงานด้านบริหารลูกค้าสัมพันธ์',
                          AppStrings.profilePositionName,
                          style: TextStyle(
                            fontSize: mediaQuery(context, 'h', AppFontSize.h2),
                            color: Colors.white,
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              ),
            ),
            Container(
              width: _width,
              height: mediaQuery(context, 'h', 175),
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 2267.16),
              ),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topRight: Radius.circular(
                    mediaQuery(context, 'h', 100),
                  ),
                ),
                color: Color(0xFF7F3F98),
              ),
              child: BottomMenu(activePage: currentPage),
            ),
            Container(
              width: _width,
              height: mediaQuery(context, 'h', 121.87),
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 2146),
              ),
              color: Color(0xFF7F3F98),
            ),
            Container(
              width: _width,
              height: mediaQuery(context, 'h', 1570),
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 699.51),
              ),
              padding: EdgeInsets.fromLTRB(
                mediaQuery(context, 'w', 60),
                mediaQuery(context, 'w', 80),
                mediaQuery(context, 'w', 60),
                mediaQuery(context, 'w', 80),
              ),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(
                    mediaQuery(context, 'h', 100),
                  ),
                  bottomLeft: Radius.circular(
                    mediaQuery(context, 'h', 100),
                  ),
                ),
                color: Color(0xFFf2f5f7),
              ),
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        _buildHomeMenuSchedule(
                          context,
                          AppAssets.img_home_schedule,
                          AppStrings.home_schedule,
                          Schedule(),
                        ),
                        _buildHomeMenuNotify(
                          context,
                          AppAssets.img_home_notification,
                          AppStrings.home_alert,
                          NotificationPage(),
                        ),
                        _buildHomeMenu(
                          context,
                          AppAssets.img_home_service,
                          AppStrings.home_service,
                          ListCustomer(),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: mediaQuery(context, 'h', 60),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        _buildHomeMenuOfferService(
                          context,
                          AppAssets.img_home_additional,
                          AppStrings.home_request,
                          RequestAdditional(),
                        ),
                        _buildHomeMenuChat(
                          context,
                          AppAssets.img_home_conversation,
                          AppStrings.home_chat,
                          Chathome(),
                        ),
                        _buildHomeMenu(
                          context,
                          AppAssets.img_home_statistics,
                          AppStrings.home_statistics,
                          PerformanceStatistics(),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: mediaQuery(context, 'h', 60),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        _buildHomeMenuPowerFail(
                          context,
                          AppAssets.img_home_interrupted,
                          AppStrings.home_powerFail,
                          PowerFail(),
                        ),
                        _buildHomeMenuTimeline(
                          context,
                          AppAssets.img_home_timeline,
                          AppStrings.home_timeline,
                          Timeline(),
                        ),
                        _buildHomeMenuNews(
                          context,
                          AppAssets.img_home_public_relations,
                          AppStrings.home_pr,
                          PublicRelation(),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  _buildHomeMenu(context, image, name, pageClass) {
    return Material(
      type: MaterialType.transparency,
      elevation: 6.0,
      color: Colors.transparent,
      child: Ink(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          color: Colors.white,
        ),
        child: InkWell(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          splashColor: Colors.white70,
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => pageClass),
            );
          },
          child: Container(
            width: mediaQuery(context, 'w', 300),
            height: mediaQuery(context, 'h', 365),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(
                Radius.circular(
                  mediaQuery(context, 'h', 40),
                ),
              ),
              boxShadow: [
                appShadow(),
              ],
              color: Colors.white,
            ),
            alignment: Alignment.center,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset(
                  image,
                  width: mediaQuery(context, 'w', 124),
                  height: mediaQuery(context, 'h', 120),
                ),
                SizedBox(
                  height: mediaQuery(context, 'h', 20),
                ),
                Text(
                  name == "คำขอใช้บริการเสริม" ? "คำขอ\nใช้บริการเสริม" : name,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: mediaQuery(context, 'h', AppFontSize.menuHome),
                  ),
                )
              ],
            ),
          ), // other widget
        ),
      ),
    );
  }

  _buildHomeMenuSchedule(context, image, name, pageClass) {
    return Material(
      type: MaterialType.transparency,
      elevation: 6.0,
      color: Colors.transparent,
      child: Ink(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          color: Colors.white,
        ),
        child: InkWell(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          splashColor: Colors.white70,
          onTap: () async {
            setState(() {
              setPref('int', "todolist", 0);
              NotificationCount.fetchSumStore("todolist");
            });
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => pageClass),
            );
          },
          child: Stack(
            children: [
              Positioned(
                child: Container(
                  width: mediaQuery(context, 'w', 300),
                  height: mediaQuery(context, 'h', 365),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(
                      Radius.circular(
                        mediaQuery(context, 'h', 40),
                      ),
                    ),
                    boxShadow: [
                      appShadow(),
                    ],
                    color: Colors.white,
                  ),
                  alignment: Alignment.center,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                        image,
                        width: mediaQuery(context, 'w', 124),
                        height: mediaQuery(context, 'h', 120),
                      ),
                      SizedBox(
                        height: mediaQuery(context, 'h', 20),
                      ),
                      Text(
                        name == "คำขอใช้บริการเสริม"
                            ? "คำขอ\nใช้บริการเสริม"
                            : name,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize:
                              mediaQuery(context, 'h', AppFontSize.menuHome),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              NotificationCount.scheduleCount != 0 &&
                      NotificationCount.scheduleCount != null
                  ? Row(
                      children: [
                        SizedBox(
                          width: mediaQuery(context, 'w', 200),
                          height: 1,
                        ),
                        Container(
                          width: mediaQuery(context, 'w', 89),
                          decoration: BoxDecoration(
                              color: Colors.red,
                              borderRadius: BorderRadius.circular(10.0)),
                          alignment: Alignment.center,
                          child: Text(
                            NotificationCount.scheduleCount.toString(),
                            style: TextStyle(
                                fontSize: mediaQuery(context, 'h', 50),
                                letterSpacing: 0.8,
                                color: Colors.white,
                                fontWeight: FontWeight.w500),
                          ),
                        ),
                      ],
                    )
                  : Container(),
            ],
          ), // other widget
        ),
      ),
    );
  }

  _buildHomeMenuNotify(context, image, name, pageClass) {
    return Material(
      type: MaterialType.transparency,
      elevation: 6.0,
      color: Colors.transparent,
      child: Ink(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          color: Colors.white,
        ),
        child: InkWell(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          splashColor: Colors.white70,
          onTap: () async {
            setState(() {
              setPref('int', "notification", 0);
              //NotificationCount.fetchSumStore("notification");
            });
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => pageClass),
            );
          },
          child: Stack(
            children: [
              Positioned(
                child: Container(
                  width: mediaQuery(context, 'w', 300),
                  height: mediaQuery(context, 'h', 365),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(
                      Radius.circular(
                        mediaQuery(context, 'h', 40),
                      ),
                    ),
                    boxShadow: [
                      appShadow(),
                    ],
                    color: Colors.white,
                  ),
                  alignment: Alignment.center,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                        image,
                        width: mediaQuery(context, 'w', 124),
                        height: mediaQuery(context, 'h', 120),
                      ),
                      SizedBox(
                        height: mediaQuery(context, 'h', 20),
                      ),
                      Text(
                        name == "คำขอใช้บริการเสริม"
                            ? "คำขอ\nใช้บริการเสริม"
                            : name,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize:
                              mediaQuery(context, 'h', AppFontSize.menuHome),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              NotificationCount.notificationCount != 0 &&
                      NotificationCount.notificationCount != null
                  ? Row(
                      children: [
                        SizedBox(
                          width: mediaQuery(context, 'w', 200),
                          height: 1,
                        ),
                        Container(
                          width: mediaQuery(context, 'w', 89),
                          decoration: BoxDecoration(
                            color: Colors.red,
                            borderRadius: BorderRadius.circular(10.0),
                          ),
                          alignment: Alignment.center,
                          child: Text(
                            NotificationCount.notificationCount.toString(),
                            style: TextStyle(
                              fontSize: mediaQuery(context, 'h', 50),
                              letterSpacing: 0.8,
                              color: Colors.white,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ],
                    )
                  : Container(),
            ],
          ), // other widget
        ),
      ),
    );
  }

  _buildHomeMenuOfferService(context, image, name, pageClass) {
    return Material(
      type: MaterialType.transparency,
      elevation: 6.0,
      color: Colors.transparent,
      child: Ink(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          color: Colors.white,
        ),
        child: InkWell(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          splashColor: Colors.white70,
          onTap: () async {
            setState(() {
              setPref('int', AppStrings.packagerequest, 0);
              NotificationCount.packageRequestCount = 0;
              //NotificationCount.fetchSumStore("packagerequest");
            });
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => pageClass),
            );
          },
          child: Stack(
            children: [
              Positioned(
                child: Container(
                  width: mediaQuery(context, 'w', 300),
                  height: mediaQuery(context, 'h', 365),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(
                      Radius.circular(
                        mediaQuery(context, 'h', 40),
                      ),
                    ),
                    boxShadow: [
                      appShadow(),
                    ],
                    color: Colors.white,
                  ),
                  alignment: Alignment.center,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                        image,
                        width: mediaQuery(context, 'w', 124),
                        height: mediaQuery(context, 'h', 120),
                      ),
                      SizedBox(
                        height: mediaQuery(context, 'h', 20),
                      ),
                      Text(
                        name == "คำขอใช้บริการเสริม"
                            ? "คำขอ\nใช้บริการเสริม"
                            : name,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize:
                              mediaQuery(context, 'h', AppFontSize.menuHome),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              StreamBuilder(
                stream: FirebaseFirestore.instance
                    .collection(AppStrings.collection)
                    .doc(AppStrings.packagerequest)
                    .snapshots(),
                builder: (BuildContext context, snapshot) {
                  if (!snapshot.hasData) {
                    return Container();
                  } else {
                    var number = snapshot.data["running_number"];
                    int calc = NotificationCount.calcNoti(
                        AppStrings.packagerequest, number);
                    if (number != 0) {
                      if (number > 99) {
                        number = "99+";
                      }
                      return _notifyAlert(calc);
                    } else {
                      return Container();
                    }
                  }
                },
              ),
            ],
          ), // other widget
        ),
      ),
    );
  }

  _buildHomeMenuChat(context, image, name, pageClass) {
    return Material(
      type: MaterialType.transparency,
      elevation: 6.0,
      color: Colors.transparent,
      child: Ink(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          color: Colors.white,
        ),
        child: InkWell(
            borderRadius: BorderRadius.all(
              Radius.circular(
                mediaQuery(context, 'h', 40),
              ),
            ),
            splashColor: Colors.white70,
            onTap: () async {
              // setState(() {
              //   NotificationCount.fetchSumStore("chat");
              // });
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => pageClass),
              );
            },
            child: Consumer<NotificationCount>(
              builder: (BuildContext context, count, Widget child) {
                return Stack(
                  children: [
                    Positioned(
                      child: Container(
                        width: mediaQuery(context, 'w', 300),
                        height: mediaQuery(context, 'h', 365),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(
                            Radius.circular(
                              mediaQuery(context, 'h', 40),
                            ),
                          ),
                          boxShadow: [
                            appShadow(),
                          ],
                          color: Colors.white,
                        ),
                        alignment: Alignment.center,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Image.asset(
                              image,
                              width: mediaQuery(context, 'w', 124),
                              height: mediaQuery(context, 'h', 120),
                            ),
                            SizedBox(
                              height: mediaQuery(context, 'h', 20),
                            ),
                            Text(
                              name == "คำขอใช้บริการเสริม"
                                  ? "คำขอ\nใช้บริการเสริม"
                                  : name,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: mediaQuery(
                                    context, 'h', AppFontSize.menuHome),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    // StreamBuilder(
                    //   stream: FirebaseFirestore
                    //     .instance.collection(AppStrings.collection)
                    //     .snapshots(),
                    //   builder: (BuildContext context,  snapshot) {
                    //     if(!snapshot.hasData){
                    //       return Container();
                    //     }else{
                    //       NotificationCount.sumChatNotify(context);
                    //       // Provider.of<NotificationCount>(context, listen: true).addChatCount(2);
                    //       var chat = Provider.of<NotificationCount>(context).count;
                    //       // print("value notifer :  " + count.countChats.toString());
                    //       // print("Stream Chat ::: " + chat.toString());
                    //       print("Provider :::: " + chat.toString());
                    //       if(chat != 0){
                    //         if(chat > 99){
                    //           chat = 99;
                    //         }
                    //         return _notifyAlert(chat);
                    //       }else{
                    //         return Container();
                    //       }
                    //       ///return Container();
                    //     }
                    //   },
                    // ),

                    // NotificationCount().getChat != 0 &&
                    // NotificationCount().getChat != null
                    // NotificationCount.chatCount != 0 &&
                    // NotificationCount.chatCount != null
                    // NotificationCount.chatCount != 0 &&
                    // NotificationCount.chatCount != null
                    NotificationCount().getChat > 0
                        ? Row(
                            children: [
                              SizedBox(
                                width: mediaQuery(context, 'w', 200),
                                height: 1,
                              ),
                              Container(
                                width: mediaQuery(context, 'w', 89),
                                decoration: BoxDecoration(
                                    color: Colors.red,
                                    borderRadius: BorderRadius.circular(10.0)),
                                alignment: Alignment.center,
                                child: Text(
                                  NotificationCount().getChat > 99
                                      ? "99+"
                                      : NotificationCount().getChat.toString(),
                                  // count.getChat > 99 ? "99+" : count.getChat.toString(),
                                  //NotificationCount.chatCount > 99 ? "99+" : NotificationCount.chatCount.toString(),
                                  style: TextStyle(
                                    fontSize: mediaQuery(context, 'h', 50),
                                    letterSpacing: 0.8,
                                    color: Colors.white,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                            ],
                          )
                        : Container(),
                  ],
                ); // other widget
              },
            )),
      ),
    );
  }

  _buildHomeMenuPowerFail(context, image, name, pageClass) {
    return Material(
      type: MaterialType.transparency,
      elevation: 6.0,
      color: Colors.transparent,
      child: Ink(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          color: Colors.white,
        ),
        child: InkWell(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          splashColor: Colors.white70,
          onTap: () async {
            setState(() {
              setPref('int', "electricproblem", 0);
              NotificationCount.electricProblemCount = 0;
              //NotificationCount.fetchSumStore("electricproblem");
            });
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => pageClass),
            );
          },
          child: Stack(
            children: [
              Positioned(
                child: Container(
                  width: mediaQuery(context, 'w', 300),
                  height: mediaQuery(context, 'h', 365),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(
                      Radius.circular(
                        mediaQuery(context, 'h', 40),
                      ),
                    ),
                    boxShadow: [
                      appShadow(),
                    ],
                    color: Colors.white,
                  ),
                  alignment: Alignment.center,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                        image,
                        width: mediaQuery(context, 'w', 124),
                        height: mediaQuery(context, 'h', 120),
                      ),
                      SizedBox(
                        height: mediaQuery(context, 'h', 20),
                      ),
                      Text(
                        name == "คำขอใช้บริการเสริม"
                            ? "คำขอ\nใช้บริการเสริม"
                            : name,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: mediaQuery(context, 'h', 49),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              StreamBuilder(
                stream: FirebaseFirestore.instance
                    .collection(AppStrings.collection)
                    .doc(AppStrings.electricproblem)
                    .snapshots(),
                builder: (BuildContext context, snapshot) {
                  if (!snapshot.hasData) {
                    return Container();
                  } else {
                    var number = snapshot.data["running_number"];
                    int calc = NotificationCount.calcNoti(
                        AppStrings.electricproblem, number);
                    if (number != 0) {
                      if (number > 99) {
                        number = "99+";
                      }
                      return _notifyAlert(calc);
                    } else {
                      return Container();
                    }
                  }
                },
              ),
            ],
          ), // other widget
        ),
      ),
    );
  }

  _buildHomeMenuTimeline(context, image, name, pageClass) {
    return Material(
      type: MaterialType.transparency,
      elevation: 6.0,
      color: Colors.transparent,
      child: Ink(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          color: Colors.white,
        ),
        child: InkWell(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          splashColor: Colors.white70,
          onTap: () async {
            setState(() {
              setPref('int', "timeline", 0);
              NotificationCount.timelineCount = 0;
              //NotificationCount.fetchSumStore("timeline");
            });
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => pageClass),
            );
          },
          child: Stack(
            children: [
              Positioned(
                child: Container(
                  width: mediaQuery(context, 'w', 300),
                  height: mediaQuery(context, 'h', 365),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(
                      Radius.circular(
                        mediaQuery(context, 'h', 40),
                      ),
                    ),
                    boxShadow: [
                      appShadow(),
                    ],
                    color: Colors.white,
                  ),
                  alignment: Alignment.center,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                        image,
                        width: mediaQuery(context, 'w', 124),
                        height: mediaQuery(context, 'h', 120),
                      ),
                      SizedBox(
                        height: mediaQuery(context, 'h', 20),
                      ),
                      Text(
                        name == "คำขอใช้บริการเสริม"
                            ? "คำขอ\nใช้บริการเสริม"
                            : name,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize:
                              mediaQuery(context, 'h', AppFontSize.menuHome),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              StreamBuilder(
                stream: FirebaseFirestore.instance
                    .collection(AppStrings.collection)
                    .doc(AppStrings.timeline)
                    .snapshots(),
                builder: (BuildContext context, snapshot) {
                  if (!snapshot.hasData) {
                    return Container();
                  } else {
                    var number = snapshot.data["running_number"];
                    int calc =
                        NotificationCount.calcNoti(AppStrings.timeline, number);
                    if (number != 0) {
                      if (number > 99) {
                        number = "99+";
                      }
                      return _notifyAlert(calc);
                    } else {
                      return Container();
                    }
                  }
                },
              ),
            ],
          ), // other widget
        ),
      ),
    );
  }

  _buildHomeMenuNews(context, image, name, pageClass) {
    return Material(
      type: MaterialType.transparency,
      elevation: 6.0,
      color: Colors.transparent,
      child: Ink(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          color: Colors.white,
        ),
        child: InkWell(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 40),
            ),
          ),
          splashColor: Colors.white70,
          onTap: () async {
            setState(() {
              setPref('int', "news", 0);
              NotificationCount.newsCount = 0;
              //NotificationCount.fetchSumStore("news");
            });
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => pageClass),
            );
          },
          child: Stack(
            children: [
              Positioned(
                child: Container(
                  width: mediaQuery(context, 'w', 300),
                  height: mediaQuery(context, 'h', 365),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(
                      Radius.circular(
                        mediaQuery(context, 'h', 40),
                      ),
                    ),
                    boxShadow: [
                      appShadow(),
                    ],
                    color: Colors.white,
                  ),
                  alignment: Alignment.center,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                        image,
                        width: mediaQuery(context, 'w', 124),
                        height: mediaQuery(context, 'h', 120),
                      ),
                      SizedBox(
                        height: mediaQuery(context, 'h', 20),
                      ),
                      Text(
                        name == "คำขอใช้บริการเสริม"
                            ? "คำขอ\nใช้บริการเสริม"
                            : name,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize:
                              mediaQuery(context, 'h', AppFontSize.menuHome),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              StreamBuilder(
                stream: FirebaseFirestore.instance
                    .collection(AppStrings.collection)
                    .doc(AppStrings.news)
                    .snapshots(),
                builder: (BuildContext context, snapshot) {
                  if (!snapshot.hasData) {
                    return Container();
                  } else {
                    var number = snapshot.data["running_number"];
                    int calc =
                        NotificationCount.calcNoti(AppStrings.news, number);
                    if (number != 0) {
                      if (number > 99) {
                        number = "99+";
                      }
                      return _notifyAlert(calc);
                    } else {
                      return Container();
                    }
                  }
                },
              ),
            ],
          ), // other widget
        ),
      ),
    );
  }

  static comfirmLogut(context) {
    return showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return Center(
          child: AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(
                Radius.circular(
                  mediaQuery(context, 'h', 50),
                ),
              ),
            ),
            title: Column(
              children: <Widget>[
                Container(
                  child: Image.asset(
                    'assets/images/question.png',
                    width: mediaQuery(context, 'w', 200),
                    height: mediaQuery(context, 'h', 200),
                  ),
                ),
              ],
            ),
            content: Container(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Text(
                    'ออกจากระบบ',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: mediaQuery(context, 'h', 60),
                    ),
                    textAlign: TextAlign.center,
                  ),
                  SizedBox(
                    height: mediaQuery(context, 'h', 10),
                  ),
                  Text(
                    'คุณแน่ใจว่าต้องการออกจากระบบ?',
                    style: TextStyle(
                      fontSize: mediaQuery(context, 'h', 46),
                    ),
                    textAlign: TextAlign.center,
                  ),
                  SizedBox(
                    height: mediaQuery(context, 'h', 40),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      ButtonTheme(
                        minWidth: mediaQuery(context, 'h', 320),
                        height: mediaQuery(context, 'h', 120),
                        child: RaisedButton(
                          color: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(
                              mediaQuery(context, 'h', 50),
                            ),
                            side: BorderSide(
                              color: AppColors.color.withOpacity(0.51),
                            ),
                          ),
                          onPressed: () async {
                            Map<String, dynamic> data = {
                              "EmployeeID": AppStrings.employeeNo.toString()
                            };
                            print(data);
                            var response = await AppApi.postWithMap(
                                AppUrl.PEALogout, data);
                            print(response);
                            logout(context);
                            Navigator.pop(context);
                          },
                          splashColor: AppColors.color,
                          child: Text(
                            'ยืนยัน',
                            style: TextStyle(
                              color: AppColors.color,
                              fontSize: mediaQuery(context, 'h', 46),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(
                        width: mediaQuery(context, 'w', 20),
                      ),
                      ButtonTheme(
                        minWidth: mediaQuery(context, 'h', 320),
                        height: mediaQuery(context, 'h', 120),
                        child: RaisedButton(
                          color: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(
                              mediaQuery(context, 'h', 50),
                            ),
                            side: BorderSide(
                              color: AppColors.color.withOpacity(0.51),
                            ),
                          ),
                          onPressed: () {
                            Navigator.of(context).pop(false);
                          },
                          splashColor: AppColors.color,
                          child: Text(
                            "ยกเลิก",
                            style: TextStyle(
                              color: AppColors.color,
                              fontSize: mediaQuery(context, 'h', 46),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _notifyAlert(int number) {
    return number != 0
        ? Row(
            children: [
              SizedBox(
                width: mediaQuery(context, 'w', 200),
                height: 1,
              ),
              Container(
                  width: mediaQuery(context, 'w', 100),
                  decoration: BoxDecoration(
                    color: Colors.red,
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  alignment: Alignment.center,
                  child: Text(
                    "$number",
                    style: TextStyle(
                      fontSize: mediaQuery(context, 'h', 45),
                      letterSpacing: 0.8,
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                    ),
                  )),
            ],
          )
        : Container();
  }
}
