import 'dart:ui';

import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/ImagesInfo.dart';
import 'package:diplomaticquarterapp/core/service/AuthenticatedUserObject.dart';
import 'package:diplomaticquarterapp/core/service/medical/vital_sign_service.dart';
import 'package:diplomaticquarterapp/core/viewModels/appointment_rate_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/pharmacy_module_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/extensions/string_extensions.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/models/Appointments/toDoCountProviderModel.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/models/Authentication/check_activation_code_response.dart' as list;
import 'package:diplomaticquarterapp/models/FamilyFiles/GetAllSharedRecordByStatusResponse.dart';
import 'package:diplomaticquarterapp/pages/landing/landing_page.dart';
import 'package:diplomaticquarterapp/pages/rateAppointment/rate_appointment_doctor.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/clinic_services/get_clinic_service.dart';
import 'package:diplomaticquarterapp/services/family_files/family_files_provider.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/ConfirmWithMessageDialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_expandable_notifier.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/text/app_texts_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';

class MyFamily extends StatefulWidget {
  final bool isAppbarVisible;
  Function onBackClick;

  MyFamily({this.isAppbarVisible = true, this.onBackClick});

  @override
  _MyFamily createState() => _MyFamily();
}

class _MyFamily extends State<MyFamily> with TickerProviderStateMixin {
  List<ImagesInfo> imagesInfo = List();
  final familyFileProvider = FamilyFilesProvider();
  AppSharedPreferences sharedPref = new AppSharedPreferences();
  var userID;
  TabController _tabController;
  int _tabIndex = 0;
  AuthenticatedUserObject authenticatedUserObject = locator<AuthenticatedUserObject>();
  AppointmentRateViewModel appointmentRateViewModel = locator<AppointmentRateViewModel>();
  ProjectViewModel projectViewModel;
  AuthenticatedUser user;
  VitalSignService _vitalSignService = locator<VitalSignService>();
  PharmacyModuleViewModel pharmacyModuleViewModel = locator<PharmacyModuleViewModel>();
  ToDoCountProviderModel toDoProvider;
  var isVaiable = false;
  bool isSwitchUser = false;

  @override
  void initState() {
    _tabController = new TabController(length: 2, vsync: this, initialIndex: 0);
    checkUserData();
    super.initState();
  }

  bool expandFlag = false;

  Widget build(BuildContext context) {
    imagesInfo.add(
      ImagesInfo(
          imageEn: 'https://hmgwebservices.com/Images/MobileApp/images-info-home/family-file/en/0.png', imageAr: 'https://hmgwebservices.com/Images/MobileApp/images-info-home/family-file/ar/0.png'),
    );

    imagesInfo.add(
      ImagesInfo(
          imageEn: 'https://hmgwebservices.com/Images/MobileApp/images-info-home/family-file/en/1.png', imageAr: 'https://hmgwebservices.com/Images/MobileApp/images-info-home/family-file/ar/1.png'),
    );
    projectViewModel = Provider.of(context);
    toDoProvider = Provider.of<ToDoCountProviderModel>(context);
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).myFamilyFiles,
      isShowAppBar: widget.isAppbarVisible,
      imagesInfo: imagesInfo,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      onTap: widget.isAppbarVisible == false ? widget.onBackClick : null,
      icon: "assets/images/new/bottom_nav/family_files.svg",
      description: TranslationBase.of(context).familyInfo,
      body: Column(
        children: [
          TabBar(
            controller: _tabController,
            indicatorWeight: 3.0,
            indicatorSize: TabBarIndicatorSize.tab,
            labelColor: Color(0xff2B353E),
            unselectedLabelColor: Color(0xff575757),
            labelPadding: EdgeInsets.only(top: 15, bottom: 13, left: 20, right: 20),
            labelStyle: TextStyle(
              fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins',
              fontSize: 16,
              fontWeight: FontWeight.w600,
              letterSpacing: -0.48,
            ),
            unselectedLabelStyle: TextStyle(
              fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins',
              fontSize: 16,
              fontWeight: FontWeight.w600,
              letterSpacing: -0.48,
            ),
            tabs: [Text(TranslationBase.of(context).family), Text(TranslationBase.of(context).request)],
          ),
          Expanded(
            child: (user != null && projectViewModel.isLogin)
                ? TabBarView(
                    physics: BouncingScrollPhysics(),
                    controller: _tabController,
                    children: [myFamilyDetails(context), myFamilyRequest(context)],
                  )
                : Container(child: AppText('')),
          ),
        ],
      ),
      bottomSheet: Container(
        color: Theme.of(context).scaffoldBackgroundColor,
        width: double.infinity,
        padding: EdgeInsets.all(14),
        child: DefaultButton(
          TranslationBase.of(context).addFamilyMember,
          () async {
            Navigator.of(context).pushNamed(ADD_FAMILY_MEMBER_TYPE);
          },
        ),
      ),
    );
  }

  Widget myFamilyDetails(context) {
    return Container(
        margin: EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 0.0),
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 4,
              child: FutureBuilder(
                future: getFamilyFiles(), // async work
                builder: (BuildContext context, AsyncSnapshot<GetAllSharedRecordsByStatusResponse> snapshot) {
                  switch (snapshot.connectionState) {
                    case ConnectionState.waiting:
                      return Padding(padding: EdgeInsets.only(top: 50), child: Text('Loading...'));
                    default:
                      if (snapshot.hasError)
                        return Padding(padding: EdgeInsets.all(10), child: Text(TranslationBase.of(context).noDataAvailable));
                      else
                        return checkActive(snapshot.data.getAllSharedRecordsByStatusList) > 0
                            ? ListView.separated(
                                itemBuilder: (context, index) {
                                  if (snapshot.data.getAllSharedRecordsByStatusList[index].status == 3)
                                    return Container(
                                        margin: EdgeInsets.all(5),
                                        decoration: cardRadius(
                                          15,
                                          elevation: 0,
                                          color: snapshot.data.getAllSharedRecordsByStatusList[index].gender == 2 ? Color(0xffFDA4B0) : Color(0xff6EA8FF),
                                        ),
                                        child: Container(
                                            // height: 130,0xffFDA4B0
                                            width: MediaQuery.of(context).size.width,
                                            padding: EdgeInsets.all(10),
                                            child: Row(
                                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                              children: [
                                                Column(
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  children: <Widget>[
                                                    Texts(
                                                      snapshot.data.getAllSharedRecordsByStatusList[index].patientName.toLowerCase().capitalizeFirstofEach,
                                                      fontSize: 18,
                                                      fontWeight: FontWeight.bold,
                                                      color: Colors.white,
                                                    ),
                                                    Texts(TranslationBase.of(context).fileNumber + ': ' + snapshot.data.getAllSharedRecordsByStatusList[index].responseID.toString(),
                                                        fontSize: 12, color: Colors.white),
                                                    Texts(
                                                        snapshot.data.getAllSharedRecordsByStatusList[index].age.toString() +
                                                            ' ' +
                                                            TranslationBase.of(context).years +
                                                            ', ' +
                                                            snapshot.data.getAllSharedRecordsByStatusList[index].genderDescription,
                                                        fontSize: 12,
                                                        color: Colors.white),
                                                  ],
                                                ),
                                                Column(
                                                  children: [
                                                    SizedBox(height: 10),
                                                    InkWell(
                                                        onTap: () {
                                                          switchUser(snapshot.data.getAllSharedRecordsByStatusList[index], context);
                                                        },
                                                        child: Container(
                                                            decoration: BoxDecoration(color: Colors.black.withOpacity(0.1), borderRadius: BorderRadius.circular(20)),
                                                            padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
                                                            child: Row(
                                                              mainAxisAlignment: MainAxisAlignment.center,
                                                              children: [
                                                                SvgPicture.asset("assets/images/new-design/switch.svg",
                                                                    height: 22, color: snapshot.data.getAllSharedRecordsByStatusList[index].gender == 2 ? Color(0Xff5A282E) : Colors.white),
                                                                SizedBox(
                                                                  width: 5,
                                                                ),
                                                                // CupertinoSwitch(
                                                                //   value: isSwitchUser,
                                                                //   onChanged: (value) {
                                                                //     setState(() {
                                                                //       isSwitchUser = value;
                                                                //     });
                                                                //     if (isSwitchUser == true) switchUser(snapshot.data.getAllSharedRecordsByStatusList[index], context);
                                                                //   },
                                                                // ),
                                                                Texts(TranslationBase.of(context).switchUser,
                                                                    color: snapshot.data.getAllSharedRecordsByStatusList[index].gender == 2 ? Color(0Xff5A282E) : Colors.white,
                                                                    fontSize: 12,
                                                                    fontWeight: FontWeight.w600)
                                                              ],
                                                            ))),
                                                    SizedBox(
                                                      height: 10,
                                                    ),
                                                    InkWell(
                                                        onTap: () {
                                                          deleteFamily(snapshot.data.getAllSharedRecordsByStatusList[index], context);
                                                        },
                                                        child: Container(
                                                            decoration: BoxDecoration(color: Colors.black.withOpacity(0.1), borderRadius: BorderRadius.circular(20)),
                                                            padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
                                                            child: Row(
                                                              mainAxisAlignment: MainAxisAlignment.center,
                                                              children: [
                                                                SvgPicture.asset("assets/images/new-design/delete.svg",
                                                                    height: 22, color: snapshot.data.getAllSharedRecordsByStatusList[index].gender == 2 ? Color(0Xff5A282E) : Colors.white),
                                                                SizedBox(
                                                                  width: 5,
                                                                ),
                                                                Texts(TranslationBase.of(context).delete,
                                                                    color: snapshot.data.getAllSharedRecordsByStatusList[index].gender == 2 ? Color(0Xff5A282E) : Colors.white,
                                                                    fontSize: 12,
                                                                    fontWeight: FontWeight.w600),
                                                              ],
                                                            ))),
                                                    SizedBox(height: 10),
                                                  ],
                                                ),
                                              ],
                                            )));
                                  // else if (checkActive(snapshot.data.getAllSharedRecordsByStatusList) == 0)
                                  //   return getNoDataWidget(context);
                                  else
                                    return SizedBox(height: 0);
                                },
                                separatorBuilder: (context, index) => SizedBox(height: 0),
                                itemCount: snapshot.data.getAllSharedRecordsByStatusList.length)
                            : getNoDataWidget(context);
                  }
                },
              ),
            ),
            SizedBox(height: 80.0)
          ],
        ));
  }

  int checkActive(List<GetAllSharedRecordsByStatusList> list) {
    return list.where((o) => o.status == 3).toList().length;
  }

  Widget myFamilyRequest(context) {
    return //Padding(
        // padding: const EdgeInsets.symmetric(horizontal: 10.0),
        // child:
        SingleChildScrollView(
      child: Container(
        height: MediaQuery.of(context).size.height,
        margin: EdgeInsets.only(top: 10),
        child: Column(
          children: <Widget>[
            FractionallySizedBox(
              widthFactor: 1.0,
              child: AppExpandableNotifier(
                title: TranslationBase.of(context).userViewRequest,
                bodyWidget: FutureBuilder(
                  future: getUserViewRequest(), // async work
                  builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
                    switch (snapshot.connectionState) {
                      case ConnectionState.waiting:
                        return SizedBox();

                      default:
                        if (snapshot.hasError)
                          return Padding(padding: EdgeInsets.all(10), child: Text(TranslationBase.of(context).noDataAvailable));
                        else
                          return ListView.separated(
                              shrinkWrap: true,
                              physics: NeverScrollableScrollPhysics(),
                              padding: EdgeInsets.only(bottom: 14, top: 14, left: 21, right: 21),
                              itemBuilder: (context, _index) {
                                return Container(
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.all(
                                          Radius.circular(10.0),
                                        ),
                                        border: Border.all(width: 1, color: Color(0xffEFEFEF)),
                                        boxShadow: [
                                          BoxShadow(
                                            color: Color(0xff000000).withOpacity(.05),
                                            //spreadRadius: 5,
                                            blurRadius: 27,
                                            offset: Offset(0, -3),
                                          ),
                                        ],
                                        color: Colors.white),
                                    child: Column(
                                      children: [
                                        Column(children: [
                                          Padding(
                                              padding: EdgeInsets.all(10),
                                              child: Row(children: [
                                                Expanded(flex: 3, child: AppText(TranslationBase.of(context).name, fontWeight: FontWeight.w600)),
                                                Expanded(flex: 1, child: AppText(TranslationBase.of(context).allow, fontWeight: FontWeight.w600)),
                                                Expanded(flex: 1, child: AppText(TranslationBase.of(context).reject, fontWeight: FontWeight.w600)),
                                              ])),
                                          Padding(
                                            padding: const EdgeInsets.only(left: 10.0, right: 10.0),
                                            child: Divider(color: Colors.black, height: 1.5, thickness: 1.5),
                                          ),
                                          Column(
                                              children: familyFileProvider.allSharedRecordsByStatusResponse.getAllSharedRecordsByStatusList.map<Widget>((result) {
                                            return Container(
                                                padding: EdgeInsets.all(10),
                                                child: Row(
                                                  children: <Widget>[
                                                    Expanded(
                                                        flex: 3,
                                                        child: Texts(
                                                          result.patientName,
                                                          fontWeight: FontWeight.w600,
                                                          fontSize: 12,
                                                        )),
                                                    Expanded(
                                                        flex: 1,
                                                        child: IconButton(
                                                          icon: SvgPicture.asset("assets/images/new-design/allow.svg", height: 22),
                                                          onPressed: () {
                                                            acceptRemoveRequest(result.iD, 3, context);
                                                          },
                                                        )),
                                                    Expanded(
                                                        flex: 1,
                                                        child: IconButton(
                                                          icon: SvgPicture.asset("assets/images/new-design/reject.svg", height: 22),
                                                          color: Colors.white,
                                                          onPressed: () {
                                                            acceptRemoveRequest(result.iD, 4, context);
                                                          },
                                                        ))
                                                  ],
                                                ));
                                          }).toList())
                                        ])
                                      ],
                                    ));
                              },
                              separatorBuilder: (context, index) => SizedBox(height: 14),
                              itemCount: 1);
                    }
                  },
                ),
              ),
            ),
            SizedBox(height: 15),
            FractionallySizedBox(
                widthFactor: 1.0,
                child: AppExpandableNotifier(
                    title: TranslationBase.of(context).sentRequest,
                    bodyWidget: FutureBuilder(
                        future: getSentRequest(), // async work
                        builder: (BuildContext context, AsyncSnapshot<GetAllSharedRecordsByStatusResponse> snapshot) {
                          switch (snapshot.connectionState) {
                            case ConnectionState.waiting:
                              return SizedBox();
                            default:
                              if (snapshot.hasError)
                                return Padding(padding: EdgeInsets.all(10), child: Text(TranslationBase.of(context).noDataAvailable));
                              else
                                return ListView.separated(
                                  shrinkWrap: true,
                                  physics: NeverScrollableScrollPhysics(),
                                  padding: EdgeInsets.only(bottom: 14, top: 14, left: 21, right: 21),
                                  itemBuilder: (context, _index) {
                                    return Container(
                                        decoration: BoxDecoration(
                                            borderRadius: BorderRadius.all(
                                              Radius.circular(10.0),
                                            ),
                                            border: Border.all(width: 1, color: Color(0xffEFEFEF)),
                                            boxShadow: [
                                              BoxShadow(
                                                color: Color(0xff000000).withOpacity(.05),
                                                //spreadRadius: 5,
                                                blurRadius: 27,
                                                offset: Offset(0, -3),
                                              ),
                                            ],
                                            color: Colors.white),
                                        child: Column(
                                          children: [
                                            Padding(
                                                padding: EdgeInsets.all(10),
                                                child: Row(children: [
                                                  Expanded(flex: 3, child: AppText(TranslationBase.of(context).name, fontWeight: FontWeight.w600)),
                                                  Expanded(flex: 1, child: AppText(TranslationBase.of(context).status, fontWeight: FontWeight.w600))
                                                ])),
                                            Padding(
                                              padding: const EdgeInsets.only(left: 10.0, right: 10.0),
                                              child: Divider(color: Colors.black, height: 1.5, thickness: 1.5),
                                            ),
                                            Column(
                                              children: snapshot.data.getAllSharedRecordsByStatusList.map<Widget>((result) {
                                                return Padding(
                                                    padding: EdgeInsets.all(10),
                                                    child: Row(
                                                      children: <Widget>[
                                                        Expanded(
                                                            flex: 3,
                                                            child: Texts(
                                                              result.patientName,
                                                              fontWeight: FontWeight.w600,
                                                              fontSize: 12,
                                                            )),
                                                        Expanded(
                                                          flex: 1,
                                                          child: Card(
                                                            // shape: cardRadius(10),
                                                            color: result.status == 3 ? Color(0xff349745) : Color(0xffD02127),
                                                            child: Padding(
                                                              padding: EdgeInsets.all(5),
                                                              child: AppText(
                                                                result.statusDescription != null ? result.statusDescription : "",
                                                                color: Colors.white,
                                                                textAlign: TextAlign.center,
                                                                fontSize: 12,
                                                              ),
                                                            ),
                                                          ),
                                                        ),
                                                      ],
                                                    ));
                                              }).toList(),
                                            )
                                          ],
                                        ));
                                  },
                                  separatorBuilder: (context, index) => SizedBox(height: 14),
                                  itemCount: 1,
                                );
                          }
                        }))),
            SizedBox(
              height: 15,
            ),
            FractionallySizedBox(
                widthFactor: 1.0,
                child: AppExpandableNotifier(
                    title: TranslationBase.of(context).userView,
                    bodyWidget: FutureBuilder(
                        future: getUserViewRequest(), // async work
                        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
                          switch (snapshot.connectionState) {
                            case ConnectionState.waiting:
                              return Padding(padding: EdgeInsets.only(top: 50), child: Text(''));
                            default:
                              if (snapshot.hasError)
                                return Padding(padding: EdgeInsets.all(10), child: Text(TranslationBase.of(context).noDataAvailable));
                              else
                                return Container(
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.all(
                                          Radius.circular(10.0),
                                        ),
                                        border: Border.all(width: 1, color: Color(0xffEFEFEF)),
                                        boxShadow: [
                                          BoxShadow(
                                            color: Color(0xff000000).withOpacity(.05),
                                            //spreadRadius: 5,
                                            blurRadius: 27,
                                            offset: Offset(0, -3),
                                          ),
                                        ],
                                        color: Colors.white),
                                    child: Column(
                                      children: [
                                        Column(children: [
                                          Padding(
                                              padding: EdgeInsets.all(10),
                                              child: Row(children: [
                                                Expanded(
                                                    flex: 3,
                                                    child: AppText(
                                                      TranslationBase.of(context).name,
                                                      fontWeight: FontWeight.w600,
                                                    )),
                                                Expanded(
                                                    flex: 1,
                                                    child: AppText(
                                                      TranslationBase.of(context).delete,
                                                      fontWeight: FontWeight.w600,
                                                      textAlign: TextAlign.center,
                                                    )),
                                              ])),
                                          Padding(
                                            padding: const EdgeInsets.only(left: 10.0, right: 10.0),
                                            child: Divider(color: Colors.black, height: 1.5, thickness: 1.5),
                                          ),
                                          Column(
                                              children: familyFileProvider.allSharedRecordsByStatusResponse.getAllSharedRecordsByStatusList.map<Widget>((result) {
                                            return Padding(
                                                padding: EdgeInsets.all(10),
                                                child: Row(
                                                  children: <Widget>[
                                                    Expanded(
                                                        flex: 3,
                                                        child: Texts(
                                                          result.patientName,
                                                          fontWeight: FontWeight.w600,
                                                          fontSize: 12,
                                                        )),
                                                    Expanded(
                                                        flex: 1,
                                                        child: IconButton(
                                                          icon: Icon(
                                                            Icons.delete,
                                                            color: Colors.red,
                                                          ),
                                                          onPressed: () {
                                                            deactivateRequest(result.iD, 5, context);
                                                          },
                                                        )),
                                                  ],
                                                ));
                                          }).toList())
                                        ])
                                      ],
                                    ));
                          }
                        })))
          ],
        ),
      ),
    );
  }

  String isAvailable() {
    if (isVaiable == false) {
      this.isVaiable = true;
      return TranslationBase.of(context).noDataAvailable;
    } else {
      return "";
    }
  }

  Future<GetAllSharedRecordsByStatusResponse> getFamilyFiles() async {
    if (await sharedPref.getObject(FAMILY_FILE) != null) {
      return Future.value(GetAllSharedRecordsByStatusResponse.fromJson(await sharedPref.getObject(FAMILY_FILE)));
    } else {
      return familyFileProvider.getSharedRecordByStatus();
    }
  }

  Future getUserViewRequest() async {
    var user = await sharedPref.getObject(USER_PROFILE);
    return familyFileProvider.getUserViewRequest(user['PatientID']);
  }

  Future<GetAllSharedRecordsByStatusResponse> getSentRequest() async {
    // var user = await sharedPref.getObject(USER_PROFILE);
    return familyFileProvider.getUserSentRequest();
  }

  deleteFamily(family, context) {
    showDialog(
      context: context,
      builder: (cxt) => ConfirmWithMessageDialog(
        message: TranslationBase.of(context).removeFamilyMember,
        onTap: () {
          removeFamily(family, context);
        },
      ),
    );
  }

  removeFamily(GetAllSharedRecordsByStatusList family, context) {
    GifLoaderDialogUtils.showMyDialog(context);
    this.userID = family.iD;
    Map<String, dynamic> request = {};
    request['ID'] = this.userID;
    request['IsActive'] = false;
    this.familyFileProvider.deativateActivateMemberFile(request).then((value) => refreshFamily(context));
  }

  refreshFamily(context) {
    GifLoaderDialogUtils.hideDialog(context);
    setState(() {
      sharedPref.remove(FAMILY_FILE);
    });
  }

  switchUser(user, context) {
    GifLoaderDialogUtils.showMyDialog(context);
    // this
    //     .familyFileProvider
    //     .silentLoggin(user)
    //     .then((value) => loginAfter(value, context));

    // Utils.showProgressDialog(context);
    this.familyFileProvider.silentLoggin(user is AuthenticatedUser ? null : user, mainUser: user is AuthenticatedUser).then((value) => loginAfter(value, context)).catchError((err) {
      print(err);
      AppToast.showErrorToast(message: err.toString());
      Navigator.of(context).pop();
    });
  }

  loginAfter(result, context) async {
    var currentLang = await sharedPref.getString(APP_LANGUAGE);
    Provider.of<ProjectViewModel>(AppGlobal.context, listen: false).setPrivilege(privilegeList: result, isLoginChild: true);
    result = list.CheckActivationCode.fromJson(result);

    var familyFile = await sharedPref.getObject(FAMILY_FILE);
    var bloodType = await sharedPref.getString(BLOOD_TYPE);
    var mainUser = await sharedPref.getObject(MAIN_USER);
    var loginType = await sharedPref.getInt(LAST_LOGIN);
    this.sharedPref.clear();
    if (mainUser["PatientID"] != result.list.patientID) {
      result.list.isFamily = true;
    }
    this.sharedPref.setString(BLOOD_TYPE, bloodType);
    this.sharedPref.setString(APP_LANGUAGE, currentLang);
    this.sharedPref.setInt(LAST_LOGIN, loginType);
    this.sharedPref.setObject(MAIN_USER, mainUser);
    this.sharedPref.setObject(USER_PROFILE, result.list);
    this.sharedPref.setObject(FAMILY_FILE, familyFile);
    this.sharedPref.setObject(LOGIN_TOKEN_ID, result.logInTokenID);
    this.sharedPref.setString(TOKEN, result.authenticationTokenID);
    _vitalSignService.heightCm = "";
    _vitalSignService.weightKg = "";
    // await authenticatedUserObject.getUser(getUser: true);
    Provider.of<ProjectViewModel>(context, listen: false).user = result.list;
    Provider.of<ProjectViewModel>(context, listen: false).setUser(result.list);

    appointmentRateViewModel
        .getIsLastAppointmentRatedList()
        .then((value) => {
              getToDoCount(),
              GifLoaderDialogUtils.hideDialog(context),
              if (appointmentRateViewModel.isHaveAppointmentNotRate)
                {
                  Navigator.pushAndRemoveUntil(
                      context,
                      FadePage(
                        page: RateAppointmentDoctor(),
                      ),
                      (r) => false)
                }
              else
                {Navigator.pushAndRemoveUntil(AppGlobal.context, MaterialPageRoute(builder: (context) => LandingPage()), (Route<dynamic> r) => false)}
            })
        .catchError((err) {
      print(err);
      // Utils.hideProgressDialog();
      GifLoaderDialogUtils.hideDialog(context);
    });
  }

  deactivateRequest(ID, status, context) {
    GifLoaderDialogUtils.showMyDialog(context);
    Map<String, dynamic> request = {};
    request["ID"] = ID;
    request["Status"] = status;
    this.familyFileProvider.deactivateFamily(request).then((value) => {GifLoaderDialogUtils.hideDialog(context), refreshFamily(context)});
  }

  acceptRemoveRequest(ID, status, context) {
    GifLoaderDialogUtils.showMyDialog(context);
    Map<String, dynamic> request = {};
    request["ID"] = ID;
    request["Status"] = status;
    this.familyFileProvider.acceptRejectFamily(request).then((value) => {GifLoaderDialogUtils.hideDialog(context), refreshFamily(context)});
  }

  checkUserData() async {
    if (await this.sharedPref.getObject(USER_PROFILE) != null) {
      var data = AuthenticatedUser.fromJson(await this.sharedPref.getObject(USER_PROFILE));

      var data2 = AuthenticatedUser.fromJson(await this.sharedPref.getObject(MAIN_USER));
      setState(() {
        this.user = data;
      });
    }
  }

  getToDoCount() {
    toDoProvider.setState(0, true, toDoProvider.notificationsCount);
    ClinicListService service = new ClinicListService();
    service.getActiveAppointmentNo(context).then((res) {
      print(res['AppointmentActiveNumber']);
      if (res['MessageStatus'] == 1 && res['AppointmentActiveNumber'] != null) {
        toDoProvider.setState(res['AppointmentActiveNumber'], true, toDoProvider.notificationsCount);
      } else {}
    }).catchError((err) {
      print(err);
    });
  }
}
