import 'dart:ui';

import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/model/ImagesInfo.dart';
import 'package:hmg_patient_app/core/service/AuthenticatedUserObject.dart';
import 'package:hmg_patient_app/core/service/medical/vital_sign_service.dart';
import 'package:hmg_patient_app/core/viewModels/appointment_rate_view_model.dart';
import 'package:hmg_patient_app/core/viewModels/pharmacyModule/pharmacy_module_view_model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/extensions/string_extensions.dart';
import 'package:hmg_patient_app/locator.dart';
import 'package:hmg_patient_app/models/Appointments/toDoCountProviderModel.dart';
import 'package:hmg_patient_app/models/Authentication/authenticated_user.dart';
import 'package:hmg_patient_app/models/Authentication/check_activation_code_response.dart' as list;
import 'package:hmg_patient_app/models/FamilyFiles/GetAllSharedRecordByStatusResponse.dart';
import 'package:hmg_patient_app/models/InPatientServices/get_admission_info_response_model.dart';
import 'package:hmg_patient_app/models/InPatientServices/get_admission_request_info_response_model.dart';
import 'package:hmg_patient_app/pages/landing/landing_page.dart';
import 'package:hmg_patient_app/pages/rateAppointment/rate_appointment_doctor.dart';
import 'package:hmg_patient_app/routes.dart';
import 'package:hmg_patient_app/services/clinic_services/get_clinic_service.dart';
import 'package:hmg_patient_app/services/family_files/family_files_provider.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/app_shared_preferences.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/buttons/defaultButton.dart';
import 'package:hmg_patient_app/widgets/data_display/text.dart';
import 'package:hmg_patient_app/widgets/dialogs/ConfirmWithMessageDialog.dart';
import 'package:hmg_patient_app/widgets/others/app_expandable_notifier.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:hmg_patient_app/widgets/text/app_texts_widget.dart';
import 'package:hmg_patient_app/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 = [];
  final familyFileProvider = FamilyFilesProvider();
  AppSharedPreferences sharedPref = AppSharedPreferences();
  var userID;
  late TabController _tabController;
  int _tabIndex = 0;
  AuthenticatedUserObject authenticatedUserObject = locator<AuthenticatedUserObject>();
  AppointmentRateViewModel appointmentRateViewModel = locator<AppointmentRateViewModel>();
  late ProjectViewModel projectViewModel;
  AuthenticatedUser user = AuthenticatedUser();
  VitalSignService _vitalSignService = locator<VitalSignService>();
  PharmacyModuleViewModel pharmacyModuleViewModel = locator<PharmacyModuleViewModel>();
  late 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, listen: false);
    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('')),
          ),
          DefaultButton(
            TranslationBase.of(context).addFamilyMember,
            () async {
              Navigator.of(context).pushNamed(ADD_FAMILY_MEMBER_TYPE);
            },
          ).insideContainer,
        ],
      ),
    );
  }

  Widget myFamilyDetails(context) {
    return (familySharedRecordsList.length ?? 0) > 0
        ? ListView.separated(
            padding: EdgeInsets.all(21),
            itemBuilder: (context, index) {
              bool isFemale = familySharedRecordsList[index].gender == 2;
              if (familySharedRecordsList[index].status == 3) {
                return Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(
                      Radius.circular(15),
                    ),
                    gradient: LinearGradient(
                      colors: isFemale
                          ? [
                              Color(0xFFFBC8CC),
                              Color(0xFFFDA4B0),
                            ]
                          : [
                              Color(0xFF7AB8FD),
                              Color(0xFF6EA8FF),
                            ],
                      begin: Alignment.topRight,
                      end: Alignment.bottomLeft,
                    ),
                  ),
                  child: Container(
                    width: MediaQuery.of(context).size.width,
                    padding: EdgeInsets.all(15),
                    child: Row(
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                familySharedRecordsList[index].patientName!.toLowerCase().capitalizeFirstofEach,
                                style: TextStyle(fontSize: 14, fontWeight: FontWeight.w700, color: isFemale ? Color(0xff5A282E) : Colors.white, letterSpacing: -0.42),
                              ),
                              Text(
                                TranslationBase.of(context).fileNumber + ': ' + familySharedRecordsList[index].responseID.toString(),
                                style: TextStyle(fontSize: 12, fontWeight: FontWeight.w400, color: isFemale ? Color(0xff5A282E) : Colors.white, letterSpacing: -0.4, height: 16 / 10),
                              ),
                              Text(
                                familySharedRecordsList[index].age.toString() + ' ' + TranslationBase.of(context).years + ', ' + familySharedRecordsList[index].genderDescription!,
                                style: TextStyle(fontSize: 12, fontWeight: FontWeight.w400, color: isFemale ? Color(0xff5A282E) : Colors.white, letterSpacing: -0.4, height: 16 / 10),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(width: 4),
                        Column(
                          children: [
                            InkWell(
                              onTap: () {
                                switchUser(familySharedRecordsList[index], context);
                              },
                              child: Container(
                                decoration: BoxDecoration(color: Colors.black.withOpacity(0.1), borderRadius: BorderRadius.circular(20)),
                                padding: EdgeInsets.fromLTRB(10, 8, 12, 8),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    SvgPicture.asset("assets/images/new-design/switch.svg", height: 16, color: isFemale ? Color(0Xff5A282E) : Colors.white),
                                    SizedBox(width: 4),
                                    Texts(TranslationBase.of(context).switchUser, color: isFemale ? Color(0Xff5A282E) : Colors.white, fontSize: 12, fontWeight: FontWeight.w600)
                                  ],
                                ),
                              ),
                            ),
                            SizedBox(height: 8),
                            InkWell(
                              onTap: () {
                                deleteFamily(familySharedRecordsList[index], context);
                              },
                              child: Container(
                                decoration: BoxDecoration(color: Colors.black.withOpacity(0.1), borderRadius: BorderRadius.circular(20)),
                                padding: EdgeInsets.fromLTRB(10, 8, 12, 8),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    SvgPicture.asset("assets/images/new-design/delete.svg", height: 22, color: isFemale ? Color(0Xff5A282E) : Colors.white),
                                    SizedBox(width: 4),
                                    Texts(TranslationBase.of(context).delete, color: isFemale ? Color(0Xff5A282E) : Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                );
              } else
                return SizedBox(height: 0);
            },
            separatorBuilder: (context, index) => SizedBox(height: 12),
            itemCount: familySharedRecordsList.length)
        : getNoDataWidget(context);
  }

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

  Widget myFamilyRequest(context) {
    return ListView(
      children: <Widget>[
        SizedBox(height: 21),
        pendingRequestView(),
        SizedBox(height: 12),
        sentRequestView(),
        SizedBox(height: 12),
        approvedRequestView(),
      ],
    );
  }

  Widget requestDecoratedContainerWithExpandable(String title, List<Widget> columns, List<Widget> rows) {
    return AppExpandableNotifier(
      title: title,
      bodyWidget: Container(
        margin: EdgeInsets.only(left: 21, right: 21, bottom: 21),
        padding: EdgeInsets.only(top: 12, bottom: 12, left: 14, right: 14),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(
              Radius.circular(10.0),
            ),
            border: Border.all(width: 1, color: CustomColors.backgroudGreyColor),
            boxShadow: [
              BoxShadow(
                color: Color(0xff000000).withOpacity(.05),
                blurRadius: 27,
                offset: Offset(0, -3),
              ),
            ],
            color: Colors.white),
        child: Column(children: [
          Row(children: columns),
          SizedBox(height: 6),
          Divider(color: CustomColors.textDarkColor, height: 1, thickness: 1),
          SizedBox(height: 8),
          ListView.separated(
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              padding: EdgeInsets.zero,
              itemBuilder: (cxt, index) => rows[index],
              separatorBuilder: (cxt, index) => SizedBox(height: 12),
              itemCount: rows.length),
        ]),
      ),
    );
  }

  Widget pendingRequestView() {
    return requestDecoratedContainerWithExpandable(
        TranslationBase.of(context).userViewRequest,
        [
          Expanded(flex: 3, child: columnText(TranslationBase.of(context).name)),
          Expanded(flex: 1, child: columnText(TranslationBase.of(context).allow)),
          Expanded(flex: 1, child: columnText(TranslationBase.of(context).reject)),
        ],
        pendingRecordsList.map<Widget>((result) {
          return pendingItemView(result);
        }).toList());
  }

  Widget pendingItemView(GetAllSharedRecordsByStatusList result) {
    return Row(
      children: <Widget>[
        Expanded(flex: 3, child: rowText(result.patientName!)),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.centerLeft,
            child: InkWell(
              child: SvgPicture.asset("assets/images/new-design/allow.svg", height: 17),
              onTap: () {
                acceptRemoveRequest(result.iD, 3, context);
              },
            ),
          ),
        ),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.centerLeft,
            child: InkWell(
              child: SvgPicture.asset("assets/images/new-design/reject.svg", height: 17),
              onTap: () {
                acceptRemoveRequest(result.iD, 4, context);
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget sentRequestView() {
    return requestDecoratedContainerWithExpandable(
        TranslationBase.of(context).sentRequest,
        [
          Expanded(flex: 3, child: columnText(TranslationBase.of(context).name)),
          Expanded(flex: 1, child: columnText(TranslationBase.of(context).status)),
        ],
        sentRecordsList.map<Widget>((result) {
          return sentItemView(result);
        }).toList());
  }

  Widget sentItemView(GetAllSharedRecordsByStatusList result) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Expanded(flex: 3, child: rowText(result.patientName!)),
        Expanded(
          flex: 1,
          child: Container(
            padding: EdgeInsets.only(top: 3, bottom: 3, left: 8, right: 8),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(50),
              color: result.status == 3 ? Color(0xff349745) : Color(0xffD02127),
            ),
            child: Text(
              result.statusDescription != null ? result.statusDescription! : "",
              style: TextStyle(
                fontSize: 10,
                color: Colors.white,
                letterSpacing: -0.4,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget approvedRequestView() {
    return requestDecoratedContainerWithExpandable(
        TranslationBase.of(context).userView,
        [
          Expanded(flex: 4, child: columnText(TranslationBase.of(context).name)),
          Expanded(flex: 2, child: columnText(TranslationBase.of(context).delete)),
        ],
        approvedRecordsList.map<Widget>((result) {
          return approvedItemView(result);
        }).toList());
  }

  Widget approvedItemView(GetAllSharedRecordsByStatusList result) {
    return Row(
      children: <Widget>[
        Expanded(flex: 4, child: rowText(result.patientName!)),
        Expanded(
          flex: 2,
          child: Align(
            alignment: Alignment.centerLeft,
            child: InkWell(
              child: Icon(
                Icons.delete,
                color: Colors.red,
                size: 22,
              ),
              onTap: () {
                acceptRemoveRequest(result.iD, 4, context);
              },
            ),
          ),
        ),
      ],
    );
  }

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

  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);
      GifLoaderDialogUtils.hideDialog(context);
    });
  }

  refreshFamily(context) async {
    await sharedPref.remove(FAMILY_FILE);
    await checkUserData();
  }

  switchUser(user, context) {
    GifLoaderDialogUtils.showMyDialog(context);
    int languageID = Provider.of<ProjectViewModel>(context, listen: false).isArabic ? 1 : 2;
    // this
    //     .familyFileProvider
    //     .silentLoggin(user)
    //     .then((value) => loginAfter(value, context));

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

  checkIfIsInPatient(BuildContext context) {
    bool isAdmitted = false;
    bool hasAdmissionRequest = false;
    GetAdmissionInfoResponseModel getAdmissionInfoResponseModel;
    GetAdmissionRequestInfoResponseModel getAdmissionRequestInfoResponseModel;
    ClinicListService service = new ClinicListService();
    service.checkIfInPatientAPI(context).then((res) {
      if (res['MessageStatus'] == 1) {
        isAdmitted = res['isAdmitted'];
        hasAdmissionRequest = res['hasAdmissionRequests'];
        print("IS ADMITTED: $isAdmitted");
        print("Has Admission Request: $hasAdmissionRequest");
        if (isAdmitted) {
          if (res['PatientAdmittedInformation'].length != 0) {
            getAdmissionInfoResponseModel = GetAdmissionInfoResponseModel.fromJson(res['PatientAdmittedInformation'][0]);
            projectViewModel.setInPatientProjectID(res['PatientAdmittedInformation'][0]['ProjectID']);
            projectViewModel.setInPatientAdmissionInfo(getAdmissionInfoResponseModel);
            projectViewModel.setIsPatientAdmitted(true);
          }
        }
        if (hasAdmissionRequest) {
          if (res['MedicalInstruction'].length != 0) {
            getAdmissionRequestInfoResponseModel = GetAdmissionRequestInfoResponseModel.fromJson(res['MedicalInstruction'][0]);
            // projectViewModel.setInPatientProjectID(res['MedicalInstruction'][0]['ProjectID']);
            projectViewModel.setInPatientProjectID(res['MedicalInstruction'][0]['projectId']);
            projectViewModel.setInPatientAdmissionRequest(getAdmissionRequestInfoResponseModel);
            projectViewModel.setPatientHasAdmissionRequest(true);
          }
        }
      } else {}
    }).catchError((err) {
      projectViewModel.setIsPatientAdmitted(false);
      projectViewModel.setPatientHasAdmissionRequest(false);
    });
  }

  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);
    var pushToken = await sharedPref.getString(PUSH_TOKEN);
    // var oneSignalPushToken = await sharedPref.getString(ONESIGNAL_APNS_TOKEN ?? "");
    this.sharedPref.clear();
    if (mainUser["PatientID"] != result.list.patientID) {
      result.list.isFamily = true;
    }
    this.sharedPref.setString(APP_LANGUAGE, currentLang);
    this.sharedPref.setString(BLOOD_TYPE, bloodType);
    this.sharedPref.setString(PUSH_TOKEN, pushToken);
    // this.sharedPref.setString(ONESIGNAL_APNS_TOKEN, oneSignalPushToken);
    this.sharedPref.setInt(LAST_LOGIN, loginType ?? 1);
    await this.sharedPref.setObject(MAIN_USER, mainUser);
    await this.sharedPref.setObject(USER_PROFILE, result.list);
    await this.sharedPref.setObject(FAMILY_FILE, familyFile);
    await this.sharedPref.setObject(LOGIN_TOKEN_ID, result.logInTokenID);
    await this.sharedPref.setString(TOKEN, result.authenticationTokenID);
    _vitalSignService.heightCm = "";
    _vitalSignService.weightKg = "";
    Provider.of<ProjectViewModel>(context, listen: false).user = result.list;
    Provider.of<ProjectViewModel>(context, listen: false).setUser(result.list);
    Provider.of<ProjectViewModel>(context, listen: false).authenticatedUserObject.user = result.list;

    await this.sharedPref.remove(APPOINTMENT_HISTORY_MEDICAL);

    try {
      // await appointmentRateViewModel.getIsLastAppointmentRatedList();
      checkIfIsInPatient(context);
      await getToDoCount();
      if (appointmentRateViewModel.isHaveAppointmentNotRate) {
        Navigator.pushAndRemoveUntil(
            context,
            FadePage(
              page: RateAppointmentDoctor(),
            ),
            (r) => false);
      } else {
        Navigator.pushAndRemoveUntil(AppGlobal.context, MaterialPageRoute(builder: (context) => LandingPage()), (Route<dynamic> r) => false);
      }
    } catch (er) {
      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) async {
      await refreshFamily(context);
      await GifLoaderDialogUtils.hideDialog(context);
    });
  }

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

  List<GetAllSharedRecordsByStatusList> familySharedRecordsList = [];
  List<GetAllSharedRecordsByStatusList> pendingRecordsList = [];
  List<GetAllSharedRecordsByStatusList> approvedRecordsList = [];
  List<GetAllSharedRecordsByStatusList> sentRecordsList = [];

  Future getFamilyFiles() async {
    int languageID = projectViewModel.isArabic ? 1 : 2;
    GetAllSharedRecordsByStatusResponse? familySharedRecords;
    if (await sharedPref.getObject(FAMILY_FILE) != null) {
      familySharedRecords = GetAllSharedRecordsByStatusResponse.fromJson(await sharedPref.getObject(FAMILY_FILE));
    }
    GifLoaderDialogUtils.showMyDialog(context);
    try {
      if (familySharedRecords == null) {
        familySharedRecords = await familyFileProvider.getSharedRecordByStatus(languageID);
      }
      familySharedRecordsList = [];
      sentRecordsList = [];
      familySharedRecords!.getAllSharedRecordsByStatusList!.forEach((element) {
        if (element.status == 3) {
          familySharedRecordsList.add(element);
        }
        sentRecordsList.add(element);
      });
      approvedRecordsList = [];
      pendingRecordsList = [];
      GetAllSharedRecordsByStatusResponse pendingAndApprovedRecords = await getUserViewRequest(languageID);

      pendingAndApprovedRecords.getAllSharedRecordsByStatusList!.forEach((element) {
        print(element.toJson());
        if (element.status == 2) {
          pendingRecordsList.add(element);
        } else if (element.status == 3) {
          approvedRecordsList.add(element);
        }
      });
      GifLoaderDialogUtils.hideDialog(context);
    } catch (ex) {
      familySharedRecords = GetAllSharedRecordsByStatusResponse(getAllSharedRecordsByStatusList: []);
      GifLoaderDialogUtils.hideDialog(context);
    }
  }

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

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

  getToDoCount() async {
    toDoProvider.setState(0, 0, true, toDoProvider.notificationsCount);
    ClinicListService service = ClinicListService();
    try {
      var res = await service.getActiveAppointmentNo(context);
      print(res['AppointmentActiveNumber']);
      if (res['MessageStatus'] == 1 && res['AppointmentActiveNumber'] != null) {
        // toDoProvider.setState(res['AppointmentActiveNumber'], true, toDoProvider.notificationsCount);
        toDoProvider.setState(res['AppointmentActiveNumber'], res['AncillaryOrderListCount'], true, toDoProvider.notificationsCount);
      } else {}
    } catch (ex) {
      print("getToDoCount:$ex");
    }
  }

  Widget columnText(String title) {
    return Text(
      title,
      // textAlign: TextAlign.left,
      style: TextStyle(
        fontSize: 12,
        color: CustomColors.textDarkColor,
        letterSpacing: -0.48,
        fontWeight: FontWeight.w600,
      ),
    );
  }

  Widget rowText(String title) {
    return Text(
      title,
      // textAlign: TextAlign.left,
      style: TextStyle(
        fontSize: 10,
        color: CustomColors.textColor,
        letterSpacing: -0.4,
        fontWeight: FontWeight.w600,
      ),
    );
  }
}
