import 'package:date_time_picker/date_time_picker.dart';
import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/viewModel/patient_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/sick_leave_view_model.dart';
import 'package:doctor_app_flutter/models/sickleave/add_sickleave_request.dart';
import 'package:doctor_app_flutter/routes.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/util/dr_app_shared_pref.dart';
import 'package:doctor_app_flutter/util/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/util/helpers.dart';
import 'package:doctor_app_flutter/util/text_validator.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:doctor_app_flutter/widgets/shared/Text.dart';
import 'package:doctor_app_flutter/widgets/shared/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_text_form_field.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/rounded_container_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:intl/intl.dart';
import 'package:doctor_app_flutter/models/sickleave/get_all_sickleave_response.dart';
import 'package:provider/provider.dart';
import 'package:doctor_app_flutter/screens/reschedule-leaves/add-rescheduleleave.dart';
import 'package:dropdown_search/dropdown_search.dart';

Helpers helpers = Helpers();

class RescheduleLeaveScreen extends StatefulWidget {
  final isUpdate;
  final updateData;
  RescheduleLeaveScreen(this.isUpdate, this.updateData);
  @override
  _RescheduleLeaveScreen createState() => _RescheduleLeaveScreen();
}

class _RescheduleLeaveScreen extends State<RescheduleLeaveScreen> {
  DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();
  TextEditingController _toDateController = new TextEditingController();
  TextEditingController _toDateController2 = new TextEditingController();
  ProjectViewModel projectsProvider;
  SickLeaveViewModel sickLeaveViewModel;
  String _selectedClinic;
  Map profile = {};
  var offTime = '1';
  var date;
  var doctorID;
  var reason;
  var fromDate;
  var toDate;
  var clinicID;
  String fromTime;
  String toTime;
  TextEditingController _controller4 = new TextEditingController();
  TextEditingController _controller5 = new TextEditingController();
  void _presentDatePicker(id) {
    var date = new DateTime.now();
    var initialDate = id == 'fromDate'
        ? new DateTime(date.year, date.month, date.day + 15)
        : new DateTime(fromDate.year, fromDate.month, fromDate.day);
    var firstDate = id == 'fromDate'
        ? new DateTime(date.year, date.month, date.day + 15)
        : new DateTime(fromDate.year, fromDate.month, fromDate.day);
    showDatePicker(
      context: context,
      initialDate: initialDate,
      firstDate: firstDate,
      lastDate: DateTime(2050),
    ).then((pickedDate) {
      if (pickedDate == null) {
        return;
      }
      setState(() {
        final df = new DateFormat('yyyy-MM-dd');
        if (id == 'fromDate') {
          fromDate = pickedDate; //df.format();
          _toDateController.text = df.format(pickedDate);
        } else {
          toDate = pickedDate; //
          _toDateController2.text = df.format(pickedDate);
        }
      });

      setState(() {
        final df = new DateFormat('yyyy-MM-dd');
        fromDate = pickedDate; //df.format();
        _toDateController.text = df.format(pickedDate);
        toDate = pickedDate;
      });
    });
  }

  @override
  void initState() {
    getProfile();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectsProvider = Provider.of(context);

    return BaseView<PatientViewModel>(
        onModelReady: (model) => model.getClinicsList(),
        builder: (_, model, w) => BaseView<SickLeaveViewModel>(
            onModelReady: (model2) => {
                  model2.getOffTime(),
                  model2.getReasons(18),
                  model2.getCoveringDoctors()
                },
            builder: (_, model2, w) => GestureDetector(
              onTap: (){
                FocusScope.of(context).requestFocus(new FocusNode());
              },
              child: AppScaffold(
                    baseViewModel: model2,
                    isShowAppBar: false,
                    body: Center(
                      child: Container(
                        margin: EdgeInsets.only(top: 10),
                        child: FractionallySizedBox(
                          widthFactor: 0.9,
                          child: ListView(
                            children: [
                              Container(
                                  margin: EdgeInsets.all(8),
                                  decoration: BoxDecoration(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(6.0)),
                                      border: Border.all(
                                          width: 1.0,
                                          color: HexColor("#CCCCCC"))),
                                  width: double.infinity,
                                  child: Padding(
                                    padding: EdgeInsets.only(
                                        top: SizeConfig.widthMultiplier * 0.9,
                                        bottom: SizeConfig.widthMultiplier * 0.9,
                                        right: SizeConfig.widthMultiplier * 3,
                                        left: SizeConfig.widthMultiplier * 3),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          mainAxisSize: MainAxisSize.max,
                                          children: <Widget>[
                                            Expanded(
                                              // add Expanded to have your dropdown button fill remaining space
                                              child: DropdownButtonHideUnderline(
                                                  child: new IgnorePointer(
                                                      ignoring: true,
                                                      child: DropdownButton(
                                                        focusColor: Colors.grey,
                                                        isExpanded: true,
                                                        dropdownColor:
                                                            Colors.grey,
                                                        value: getClinicName(
                                                                model) ??
                                                            "",
                                                        iconSize: 0,
                                                        elevation: 16,
                                                        selectedItemBuilder:
                                                            (BuildContext
                                                                context) {
                                                          return model
                                                              .getClinicNameList()
                                                              .map((item) {
                                                            return Row(
                                                              mainAxisSize:
                                                                  MainAxisSize
                                                                      .max,
                                                              children: <Widget>[
                                                                AppText(
                                                                  item,
                                                                  fontSize: SizeConfig
                                                                          .textMultiplier *
                                                                      2.1,
                                                                  color: Colors
                                                                      .grey[500],
                                                                ),
                                                              ],
                                                            );
                                                          }).toList();
                                                        },
                                                        onChanged: (newValue) =>
                                                            {},
                                                        items: model
                                                            .getClinicNameList()
                                                            .map((item) {
                                                          return DropdownMenuItem(
                                                            value:
                                                                item.toString(),
                                                            child: Text(
                                                              item,
                                                              textAlign:
                                                                  TextAlign.end,
                                                            ),
                                                          );
                                                        }).toList(),
                                                      ))),
                                            ),
                                          ],
                                        )
                                      ],
                                    ),
                                  )),

                              Container(
                                margin: EdgeInsets.all(8),
                                decoration: BoxDecoration(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(6.0)),
                                    border: Border.all(
                                        width: 1.0, color: HexColor("#CCCCCC"))),
                                padding: EdgeInsets.all(5),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    new IgnorePointer(
                                        ignoring: true,
                                        child: AppTextFormField(
                                            readOnly: true,
                                            hintText: profile != null
                                                ? profile['DoctorName']
                                                : "",
                                            borderColor: Colors.white,
                                            onSaved: (value) {},
                                            inputFormatter: ONLY_NUMBERS))
                                  ],
                                ),
                              ),

                              Container(
                                  margin: EdgeInsets.all(8),
                                  decoration: BoxDecoration(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(6.0)),
                                      border: Border.all(
                                          width: 1.0,
                                          color: HexColor("#CCCCCC"))),
                                  width: double.infinity,
                                  child: Padding(
                                    padding: EdgeInsets.only(
                                        top: SizeConfig.widthMultiplier * 0.9,
                                        bottom: SizeConfig.widthMultiplier * 0.9,
                                        right: SizeConfig.widthMultiplier * 3,
                                        left: SizeConfig.widthMultiplier * 3),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          mainAxisSize: MainAxisSize.max,
                                          children: <Widget>[
                                            model2.allOffTime.length > 0
                                                ? Expanded(
                                                    // add Expanded to have your dropdown button fill remaining space
                                                    child:
                                                        DropdownButtonHideUnderline(
                                                            child: DropdownButton(
                                                      // focusColor: Colors.grey,
                                                      isExpanded: true,
                                                      value: offTime == null
                                                          ? model2.allOffTime[0]
                                                              ['code']
                                                          : offTime,
                                                      iconSize: 40,
                                                      elevation: 16,
                                                      selectedItemBuilder:
                                                          (BuildContext context) {
                                                        return model2.allOffTime
                                                            .map((item) {
                                                          return Row(
                                                            mainAxisSize:
                                                                MainAxisSize.max,
                                                            children: <Widget>[
                                                              AppText(
                                                                item[
                                                                    'description'],
                                                                fontSize: SizeConfig
                                                                        .textMultiplier *
                                                                    2.1,
                                                                // color:
                                                                //     Colors.grey,
                                                              ),
                                                            ],
                                                          );
                                                        }).toList();
                                                      },
                                                      onChanged: (newValue) => {
                                                        setState(() {
                                                          offTime = newValue;
                                                        }),
                                                        if (offTime == '1')
                                                          {model2.getReasons(18)}
                                                        else if (offTime == '2')
                                                          {model2.getReasons(19)}
                                                        else if (offTime == '3' ||
                                                            offTime == '5')
                                                          {model2.getReasons(102)}
                                                      },
                                                      items: model2.allOffTime
                                                          .map((item) {
                                                        return DropdownMenuItem<
                                                            String>(
                                                          value: item['code']
                                                              .toString(),
                                                          child: Text(
                                                            item['description'],
                                                            textAlign:
                                                                TextAlign.end,
                                                          ),
                                                        );
                                                      }).toList(),
                                                    )),
                                                  )
                                                : SizedBox(),
                                          ],
                                        )
                                      ],
                                    ),
                                  )),
                              offTime == '1'
                                  ? Column(
                                      children: [
                                        Container(
                                            margin: EdgeInsets.all(8),
                                            decoration: BoxDecoration(
                                                borderRadius: BorderRadius.all(
                                                    Radius.circular(6.0)),
                                                border: Border.all(
                                                    width: 1.0,
                                                    color: HexColor("#CCCCCC"))),
                                            padding: EdgeInsets.all(5),
                                            child: Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                AppTextFormField(
                                                  hintText:
                                                      TranslationBase.of(context)
                                                          .fromDate,
                                                  borderColor: Colors.white,
                                                  prefix: IconButton(
                                                      icon: Icon(
                                                          Icons.calendar_today)),
                                                  textInputType:
                                                      TextInputType.number,
                                                  controller: _toDateController,
                                                  onTap: () {
                                                    _presentDatePicker(
                                                        'fromDate');
                                                  },
                                                  inputFormatter: ONLY_DATE,
                                                  onChanged: (val) =>
                                                      fromDate = val,
                                                  onSaved: (val) =>
                                                      fromDate = val,
                                                )
                                              ],
                                            )),
                                        Row(
                                          children: [
                                            Expanded(
                                              child: Container(
                                                margin: EdgeInsets.all(8),
                                                decoration: BoxDecoration(
                                                    borderRadius:
                                                        BorderRadius.all(
                                                            Radius.circular(6.0)),
                                                    border: Border.all(
                                                        width: 1.0,
                                                        color:
                                                            HexColor("#CCCCCC"))),
                                                padding: EdgeInsets.all(5),
                                                child: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: [
                                                    DateTimePicker(
                                                      timeHintText:
                                                          TranslationBase.of(
                                                                  context)
                                                              .fromTime,
                                                      type:
                                                          DateTimePickerType.time,
                                                      controller: _controller4,
                                                      onChanged: (val) =>
                                                          fromTime = val,
                                                      validator: (val) {
                                                        print(val);
                                                        // setState(
                                                        //     () => _valueToValidate4 = val);
                                                        return null;
                                                      },
                                                      onSaved: (val) =>
                                                          fromTime = val,
                                                    )
                                                  ],
                                                ),
                                              ),
                                            ),
                                            Expanded(
                                              child: Container(
                                                margin: EdgeInsets.all(8),
                                                decoration: BoxDecoration(
                                                    borderRadius:
                                                        BorderRadius.all(
                                                            Radius.circular(6.0)),
                                                    border: Border.all(
                                                        width: 1.0,
                                                        color:
                                                            HexColor("#CCCCCC"))),
                                                padding: EdgeInsets.all(5),
                                                child: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: [
                                                    DateTimePicker(
                                                      timeHintText:
                                                          TranslationBase.of(
                                                                  context)
                                                              .toTime,
                                                      type:
                                                          DateTimePickerType.time,
                                                      controller: _controller5,
                                                      onChanged: (val) =>
                                                          toTime = val,
                                                      validator: (val) {
                                                        print(val);
                                                        // setState(
                                                        //     () => _valueToValidate4 = val);
                                                        return null;
                                                      },
                                                      onSaved: (val) =>
                                                          toTime = val,
                                                    )
                                                  ],
                                                ),
                                              ),
                                            )
                                          ],
                                        )
                                      ],
                                    )
                                  : Column(
                                      children: [
                                        Container(
                                            margin: EdgeInsets.all(8),
                                            decoration: BoxDecoration(
                                                borderRadius: BorderRadius.all(
                                                    Radius.circular(6.0)),
                                                border: Border.all(
                                                    width: 1.0,
                                                    color: HexColor("#CCCCCC"))),
                                            padding: EdgeInsets.all(5),
                                            child: Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                AppTextFormField(
                                                    hintText: TranslationBase.of(
                                                            context)
                                                        .fromDate,
                                                    borderColor: Colors.white,
                                                    prefix: IconButton(
                                                        icon: Icon(Icons
                                                            .calendar_today)),
                                                    textInputType:
                                                        TextInputType.number,
                                                    controller: _toDateController,
                                                    onTap: () {
                                                      _presentDatePicker(
                                                          'fromDate');
                                                    },
                                                    inputFormatter: ONLY_DATE,
                                                    onChanged: (value) {
                                                      setState(() {
                                                        toDate = value;
                                                      });
                                                    }),
                                              ],
                                            )),
                                        Container(
                                            margin: EdgeInsets.all(8),
                                            decoration: BoxDecoration(
                                                borderRadius: BorderRadius.all(
                                                    Radius.circular(6.0)),
                                                border: Border.all(
                                                    width: 1.0,
                                                    color: HexColor("#CCCCCC"))),
                                            padding: EdgeInsets.all(5),
                                            child: Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                AppTextFormField(
                                                    hintText: TranslationBase
                                                            .of(context)
                                                        .toDate,
                                                    borderColor: Colors.white,
                                                    prefix: IconButton(
                                                        icon: Icon(
                                                            Icons
                                                                .calendar_today)),
                                                    textInputType:
                                                        TextInputType.number,
                                                    controller:
                                                        _toDateController2,
                                                    onTap: () {
                                                      _presentDatePicker(
                                                          'toDate');
                                                    },
                                                    inputFormatter: ONLY_DATE,
                                                    onChanged: (value) {
                                                      setState(() {
                                                        toDate = value;
                                                      });
                                                    }),
                                              ],
                                            ))
                                      ],
                                    ),
                              Container(
                                  margin: EdgeInsets.all(8),
                                  decoration: BoxDecoration(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(6.0)),
                                      border: Border.all(
                                          width: 1.0,
                                          color: HexColor("#CCCCCC"))),
                                  width: double.infinity,
                                  child: Padding(
                                    padding: EdgeInsets.only(
                                        top: SizeConfig.widthMultiplier * 0.9,
                                        bottom: SizeConfig.widthMultiplier * 0.9,
                                        right: SizeConfig.widthMultiplier * 3,
                                        left: SizeConfig.widthMultiplier * 3),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          mainAxisSize: MainAxisSize.max,
                                          children: <Widget>[
                                            model2.allReasons.length > 0
                                                ? Expanded(
                                                    // add Expanded to have your dropdown button fill remaining space
                                                    child:
                                                        DropdownButtonHideUnderline(
                                                            child: DropdownButton(
                                                      focusColor: Colors.grey,
                                                      isExpanded: true,
                                                      value: reason == null
                                                          ? model2.allReasons[0]
                                                                  ['id']
                                                              .toString()
                                                          : reason,
                                                      iconSize: 40,
                                                      elevation: 16,
                                                      selectedItemBuilder:
                                                          (BuildContext context) {
                                                        return model2.allReasons
                                                            .map((item) {
                                                          return Row(
                                                            mainAxisSize:
                                                                MainAxisSize.max,
                                                            children: <Widget>[
                                                              AppText(
                                                                projectsProvider
                                                                        .isArabic
                                                                    ? item[
                                                                        'nameAr']
                                                                    : item[
                                                                        'nameEn'],
                                                                fontSize: SizeConfig
                                                                        .textMultiplier *
                                                                    2.1,
                                                                // color:
                                                                //     Colors.grey,
                                                              ),
                                                            ],
                                                          );
                                                        }).toList();
                                                      },
                                                      onChanged: (newValue) => {
                                                        setState(() {
                                                          reason = newValue;
                                                        })
                                                      },
                                                      items: model2.allReasons
                                                          .map((item) {
                                                        return DropdownMenuItem<
                                                            String>(
                                                          value: item['id']
                                                              .toString(),
                                                          child: Text(
                                                            projectsProvider
                                                                    .isArabic
                                                                ? item['nameAr']
                                                                : item['nameEn'],
                                                            textAlign:
                                                                TextAlign.end,
                                                          ),
                                                        );
                                                      }).toList(),
                                                    )),
                                                  )
                                                : SizedBox(),
                                          ],
                                        )
                                      ],
                                    ),
                                  )),

                              Container(
                                  margin: EdgeInsets.all(8),
                                  decoration: BoxDecoration(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(6.0)),
                                      border: Border.all(
                                          width: 1.0,
                                          color: HexColor("#CCCCCC"))),
                                  width: double.infinity,
                                  child: Padding(
                                    padding: EdgeInsets.only(
                                        top: SizeConfig.widthMultiplier * 0.9,
                                        bottom: SizeConfig.widthMultiplier * 0.9,
                                        right: SizeConfig.widthMultiplier * 3,
                                        left: SizeConfig.widthMultiplier * 3),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          mainAxisSize: MainAxisSize.max,
                                          children: <Widget>[
                                            model2.coveringDoctors.length > 0
                                                ? Expanded(
                                                    // add Expanded to have your dropdown button fill remaining space
                                                    child: DropdownSearch(
                                                      mode: Mode.BOTTOM_SHEET,

                                                      dropdownSearchDecoration:
                                                          InputDecoration(
                                                              contentPadding:
                                                                  EdgeInsets.all(
                                                                      0),
                                                              border: InputBorder
                                                                  .none),
                                                      //maxHeight: 300,
                                                      items: model2
                                                          .coveringDoctors
                                                          .map((item) {
                                                        return projectsProvider
                                                                .isArabic
                                                            ? item['doctorNameN']
                                                            : item['doctorName'];
                                                      }).toList(),
                                                      // label: "Doctor List",
                                                      onChanged: (item) {
                                                        model2.coveringDoctors
                                                            .forEach((newVal) => {
                                                                  if (newVal['doctorName'] ==
                                                                          item ||
                                                                      newVal['doctorName'] ==
                                                                          item)
                                                                    {
                                                                      doctorID =
                                                                          newVal[
                                                                              'DoctorID']
                                                                    }
                                                                });
                                                      },
                                                      selectedItem:
                                                          getSelectedDoctor(
                                                              model2),
                                                      showSearchBox: true,
                                                      searchBoxDecoration:
                                                          InputDecoration(
                                                        border:
                                                            OutlineInputBorder(),
                                                        contentPadding:
                                                            EdgeInsets.fromLTRB(
                                                                12, 12, 8, 0),
                                                        labelText:
                                                            "Search Doctor",
                                                      ),
                                                      popupTitle: Container(
                                                        height: 50,
                                                        decoration: BoxDecoration(
                                                          color: Theme.of(context)
                                                              .primaryColorDark,
                                                          borderRadius:
                                                              BorderRadius.only(
                                                            topLeft:
                                                                Radius.circular(
                                                                    20),
                                                            topRight:
                                                                Radius.circular(
                                                                    20),
                                                          ),
                                                        ),
                                                        child: Center(
                                                          child: Text(
                                                            '',
                                                            style: TextStyle(
                                                              fontSize: 24,
                                                              fontWeight:
                                                                  FontWeight.bold,
                                                              color: Colors.white,
                                                            ),
                                                          ),
                                                        ),
                                                      ),
                                                      popupShape:
                                                          RoundedRectangleBorder(
                                                        borderRadius:
                                                            BorderRadius.only(
                                                          topLeft:
                                                              Radius.circular(24),
                                                          topRight:
                                                              Radius.circular(24),
                                                        ),
                                                      ),
                                                    ),
                                                    //     DropdownButtonHideUnderline(
                                                    //         child: DropdownButton(
                                                    //   focusColor: Colors.grey,
                                                    //   isExpanded: true,
                                                    //   value: doctorID == null
                                                    //       ? model2
                                                    //           .coveringDoctors[0]
                                                    //               ['doctorID']
                                                    //           .toString()
                                                    //       : doctorID,
                                                    //   iconSize: 40,
                                                    //   elevation: 16,
                                                    //   selectedItemBuilder:
                                                    //       (BuildContext context) {
                                                    //     return model2
                                                    //         .coveringDoctors
                                                    //         .map((item) {
                                                    //       return Row(
                                                    //         mainAxisSize:
                                                    //             MainAxisSize.max,
                                                    //         children: <Widget>[
                                                    //           AppText(
                                                    //             projectsProvider
                                                    //                     .isArabic
                                                    //                 ? item[
                                                    //                     'doctorNameN']
                                                    //                 : item[
                                                    //                     'doctorName'],
                                                    //             fontSize: SizeConfig
                                                    //                     .textMultiplier *
                                                    //                 2.1,
                                                    //           ),
                                                    //         ],
                                                    //       );
                                                    //     }).toList();
                                                    //   },
                                                    //   onChanged: (newValue) => {
                                                    //     setState(() {
                                                    //       doctorID = newValue;
                                                    //     })
                                                    //   },
                                                    //   items: model2
                                                    //       .coveringDoctors
                                                    //       .map((item) {
                                                    //     return DropdownMenuItem<
                                                    //         String>(
                                                    //       value: item['doctorID']
                                                    //           .toString(),
                                                    //       child: Text(
                                                    //         projectsProvider
                                                    //                 .isArabic
                                                    //             ? item[
                                                    //                 'doctorNameN']
                                                    //             : item[
                                                    //                 'doctorName'],
                                                    //         textAlign:
                                                    //             TextAlign.start,
                                                    //       ),
                                                    //     );
                                                    //   }).toList(),
                                                    // )),
                                                  )
                                                : SizedBox(),
                                          ],
                                        )
                                      ],
                                    ),
                                  )),
                              Container(
                                margin: EdgeInsets.all(
                                    SizeConfig.widthMultiplier * 5),
                                child: Wrap(
                                  alignment: WrapAlignment.center,
                                  children: <Widget>[
                                    AppButton(
                                      title: widget.isUpdate == true
                                          ? TranslationBase.of(context).update
                                          : TranslationBase.of(context).add,
                                      onPressed: () {
                                        if (offTime == '1' || offTime == '2') {
                                          if (widget.isUpdate == true) {
                                            updateRecheduleLeave(model2);
                                          } else {
                                            addRecheduleLeave(model2);
                                          }
                                        } else {
                                          DrAppToastMsg.showErrorToast(
                                              TranslationBase.of(context)
                                                  .onlyOfftimeHoliday);
                                        }
                                      },
                                    ),
                                  ],
                                ),
                              ),
                              // Column(
                              //   children: [
                              //     Texts(TranslationBase.of(context)
                              //             .previousSickLeaveIssue +
                              //         ' ')
                              //   ],
                              // )
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
            )));
  }

  getProfile() async {
    Map p = await sharedPref.getObj(DOCTOR_PROFILE);

    setState(() {
      this.profile = p;
      if (widget.updateData != null) {
        this.clinicID = widget.updateData.clinicId;
        final df = new DateFormat('HH:mm:ss');
        final dateFormat = new DateFormat('yyyy-MM-dd');
        this.offTime = widget.updateData.requisitionType.toString();
        _toDateController.text =
            dateFormat.format(DateTime.parse(widget.updateData.dateTimeFrom));
        //df.format(DateTime.parse(widget.updateData.dateTimeFrom));
        this.fromTime =
            df.format(DateTime.parse(widget.updateData.dateTimeFrom));
        this.fromTime = this.fromTime.substring(0, this.fromTime.length - 3);
        this.toTime = df.format(DateTime.parse(widget.updateData.dateTimeTo));
        this.toTime = this.toTime.substring(0, this.toTime.length - 3);
        _toDateController2.text =
            dateFormat.format(DateTime.parse(widget.updateData.dateTimeTo));
        _controller5.text = toTime;
        _controller4.text = fromTime;
        toDate = _toDateController2.text;
        fromDate = _toDateController.text;
        this.reason = widget.updateData.reasonId.toString();
        doctorID = widget.updateData.coveringDoctorId;
      }
    });
  }

  getClinicName(model) {
    var clinicID = this.profile['ClinicID'] ?? 1;
    var clinicInfo =
        model.clinicsList.where((i) => i['ClinicID'] == clinicID).toList();
    return clinicInfo.length > 0 ? clinicInfo[0]['ClinicDescription'] : "";
  }

  addRecheduleLeave(model) async {
    final df = new DateFormat('yyyy-MM-ddTHH:MM:ss');
    final dateFormat = new DateFormat('yyyy-MM-dd');
    var fromDates = fromDate;
    var toDates = toDate;
    if (offTime == '1') {
      fromDate = df.format(DateTime.parse(dateFormat.format(fromDates) +
          'T' +
          fromTime +
          ':' +
          DateTime.now().second.toString()));
      toDate = df.format(DateTime.parse(dateFormat.format(fromDates) +
          'T' +
          toTime +
          ':' +
          DateTime.now().second.toString()));
    } else {
      fromDate = df.format(fromDates);
      toDate = df.format(toDates);
    }
    Map<String, dynamic> request = {
      "Requisition": {
        "requisitionNo": 0,
        "requisitionType": offTime,
        "clinicId": this.profile['ClinicID'],
        "doctorId": this.profile['DoctorID'],
        "dateTimeFrom": fromDate,
        "dateTimeTo": toDate,
        "date": offTime == '1' ? fromDate : df.format(DateTime.now()),
        "reasonId": reason == null ? model.allOffTime[0]['code'] : reason,
        "coveringDoctorId":
            doctorID == null ? model.coveringDoctors[0]['doctorID'] : doctorID,
        "status": 2,
        "schedule": [
          {
            "weekDayId": 1,
            "shiftId": 1,
            "isOpen": true,
            "timeFrom": fromTime,
            "timeTo": toTime,
            "timeFromstr": "",
            "timeTostr": ""
          }
        ]
      }
    };

    await model.addReschedule(request).then((value) {
      if (model.postSechedule != null) {
        DrAppToastMsg.showSuccesToast(TranslationBase.of(context).leaveCreated);
        Navigator.pushNamedAndRemoveUntil(context, HOME, (r) => false);
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => AddRescheduleLeavScreen(),
            // MyReferredPatient(),
          ),
        );
      }
    });
  }

  updateRecheduleLeave(model) {
    // final df = new DateFormat('yyyy-MM-ddTHH:MM:ss');
    final df = new DateFormat('yyyy-MM-dd');
    var fromDates = fromDate;
    var toDates = toDate;
    if (offTime == '1') {
      fromDate = df.format(DateTime.parse(_toDateController.text)) +
          'T' +
          fromTime +
          ':' +
          DateTime.now().second.toString();
      toDate = df.format(DateTime.parse(_toDateController.text)) +
          'T' +
          toTime +
          ':' +
          DateTime.now().second.toString();
    } else {
      fromDate = df.format(fromDates);
      toDate = df.format(toDates);
    }

    Map<String, dynamic> request = {
      "Requisition": {
        "requisitionNo": widget.updateData.requisitionNo,
        "requisitionType": offTime,
        "clinicId": this.profile['ClinicID'],
        "doctorId": this.profile['DoctorID'],
        "dateTimeFrom": fromDate,
        "dateTimeTo": toDate,
        "date": offTime == '1' ? fromDate : df.format(DateTime.now()),
        "reasonId": reason == null ? model.allOffTime[0]['code'] : reason,
        "coveringDoctorId":
            doctorID == null ? model.coveringDoctors[0]['doctorID'] : doctorID,
        "status": 2,
        "schedule": [
          {
            "weekDayId": 1,
            "shiftId": 1,
            "isOpen": true,
            "timeFrom": "",
            "timeTo": "",
            "timeFromstr": fromTime,
            "timeTostr": toTime
          }
        ]
      }
    };

    model.updateReschedule(request).then((response) {
      if (model.postSechedule != null) {
        DrAppToastMsg.showSuccesToast(TranslationBase.of(context).leaveCreated);
        Navigator.pushNamedAndRemoveUntil(context, HOME, (r) => false);
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => AddRescheduleLeavScreen(),
            // MyReferredPatient(),
          ),
        );
      }
    });
  }

  getSelectedDoctor(model2) {
    var doctorName;
    if (doctorID == null)
      return projectsProvider.isArabic
          ? model2.coveringDoctors[0]['doctorNameN']
          : model2.coveringDoctors[0]['doctorName'];
    else {
      model2.coveringDoctors.forEach((newVal) => {
            if (newVal['doctorID'].toString() == doctorID)
              {doctorName = newVal['doctorName']}
          });
      return doctorName;
    }
  }
}
