import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/core/enum/master_lookup_key.dart';
import 'package:doctor_app_flutter/core/enum/viewstate.dart';
import 'package:doctor_app_flutter/core/viewModel/SOAP_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/models/SOAP/GetAssessmentReqModel.dart';
import 'package:doctor_app_flutter/models/SOAP/master_key_model.dart';
import 'package:doctor_app_flutter/models/SOAP/my_selected_assement.dart';
import 'package:doctor_app_flutter/models/SOAP/post_assessment_request_model.dart';
import 'package:doctor_app_flutter/models/doctor/doctor_profile_model.dart';
import 'package:doctor_app_flutter/models/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/util/helpers.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/TextFields.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_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/dialogs/master_key_dailog.dart';
import 'package:doctor_app_flutter/widgets/shared/divider_with_spaces_around.dart';
import 'package:doctor_app_flutter/widgets/shared/expandable-widget-header-body.dart';
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart';

import 'custom_validation_error.dart';

class UpdateAssessmentPage extends StatefulWidget {
  final Function changePageViewIndex;
  List<MySelectedAssessment> mySelectedAssessmentList;
  final PatiantInformtion patientInfo;
  final Function changeLoadingState;

  UpdateAssessmentPage({Key key,
    this.changePageViewIndex,
    this.mySelectedAssessmentList,
    this.patientInfo, this.changeLoadingState});

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

class _UpdateAssessmentPageState extends State<UpdateAssessmentPage> {
  bool isAssessmentExpand = false;
  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);

    return BaseView<SOAPViewModel>(
        onModelReady: (model) async{
          widget.mySelectedAssessmentList.clear();
          GetAssessmentReqModel getAssessmentReqModel = GetAssessmentReqModel(
              patientMRN: widget.patientInfo.patientMRN,
              episodeID: widget.patientInfo.episodeNo.toString(),
              editedBy: '',
              doctorID: '',
              appointmentNo: widget.patientInfo.appointmentNo);
          await model.getPatientAssessment(getAssessmentReqModel);
          if(model.patientAssessmentList.isNotEmpty){
            if (model.listOfDiagnosisCondition.length == 0) {
              await model.getMasterLookup(MasterKeysService.DiagnosisCondition);
            }
            if (model.listOfDiagnosisType.length == 0) {
              await model.getMasterLookup(MasterKeysService.DiagnosisType);
            }
            if (model.listOfICD10.length == 0) {
              await model.getMasterLookup(MasterKeysService.ICD10);
            }
            model.patientAssessmentList.forEach((element) {
              MasterKeyModel diagnosisType = model.getOneMasterKey(
                masterKeys: MasterKeysService.DiagnosisType,
                id: element.diagnosisTypeID,
              );
              MasterKeyModel selectedICD = model.getOneMasterKey(
                masterKeys: MasterKeysService.ICD10,
                id: element.icdCode10ID,
              );
              MasterKeyModel diagnosisCondition = model.getOneMasterKey(
                masterKeys: MasterKeysService.DiagnosisCondition,
                id: element.conditionID,
              );
              if(diagnosisCondition !=null &&diagnosisType !=null &&  diagnosisCondition!=null) {
                MySelectedAssessment temMySelectedAssessment = MySelectedAssessment(
                    appointmentId: element.appointmentNo,
                    remark: element.remarks,
                    selectedDiagnosisType: diagnosisType,
                    selectedDiagnosisCondition: diagnosisCondition,
                    selectedICD: selectedICD,
                    doctorID: element.doctorID,
                    doctorName: element.doctorName,
                    createdBy: element.createdBy,
                    createdOn: element.createdOn,
                    icdCode10ID: element.icdCode10ID
                );

                widget.mySelectedAssessmentList.add(temMySelectedAssessment);
              }

            });
          }

          widget.changeLoadingState(false);

        },
        builder: (_, model, w) => AppScaffold(
            isShowAppBar: false,
            // baseViewModel: model,
            body: SingleChildScrollView(
              physics: ScrollPhysics(),
              child: Center(
                child: FractionallySizedBox(
                  widthFactor: 0.9,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      SizedBox(
                            height: 30,
                          ),
                          HeaderBodyExpandableNotifier(
                            headerWidget: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Texts(TranslationBase.of(context).assessment.toUpperCase(),
                                        variant:
                                        isAssessmentExpand ? "bodyText" : '',
                                        bold: isAssessmentExpand ? true : false,
                                        color: Colors.black),
                                    Icon(
                                      FontAwesomeIcons.asterisk,
                                      color: AppGlobal.appPrimaryColor,
                                      size: 12,
                                    )
                                  ],
                                ),
                                InkWell(
                                    onTap: () {
                                      setState(() {
                                        isAssessmentExpand = !isAssessmentExpand;
                                      });
                                    },
                                    child: Icon(isAssessmentExpand
                                        ? EvaIcons.minus
                                        : EvaIcons.plus))
                              ],
                            ),
                            bodyWidget: Column(children: [
                              SizedBox(
                                height: 20,
                              ),
                              Column(
                                children: [
                                  Container(
                                    margin:
                                    EdgeInsets.only(left: 5, right: 5, top: 15),
                                    child: TextFields(
                                        hintText: TranslationBase.of(context).addAssessment,
                                        fontSize: 13.5,
                                        onTapTextFields: () {
                                          openAssessmentDialog(context,isUpdate: false,
                                              model: model);
                                        },
                                        readOnly: true,
                                        suffixIcon: EvaIcons.plusCircleOutline,
                                        suffixIconColor: AppGlobal
                                            .appPrimaryColor,
                                        fontWeight: FontWeight.w600,
                                        validator: (value) {
                                          if (value == null)
                                            return TranslationBase
                                                .of(context)
                                                .emptyMessage;
                                          else
                                            return null;
                                        }),
                                  ),
                                  SizedBox(
                                    height: 20,
                                  ),

                                  Column(
                                    children: widget.mySelectedAssessmentList.map((
                                        assessment) {
                                      return Container(
                                        margin: EdgeInsets.only(
                                            left: 5, right: 5, top: 15),
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment
                                              .spaceBetween,
                                          crossAxisAlignment: CrossAxisAlignment
                                              .start,
                                          children: [
                                            Column(
                                              mainAxisAlignment: MainAxisAlignment
                                                  .start,
                                              children: [
                                                Column(
                                                  mainAxisAlignment:
                                                  MainAxisAlignment.start,
                                                  crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                                  children: [
                                                    AppText(

                                                      assessment.createdOn !=null?DateTime.parse(assessment.createdOn).day.toString():DateTime.now().day.toString(),
                                                      fontWeight: FontWeight
                                                          .bold,
                                                      fontSize: 13,
                                                    ),
                                                    AppText(
                                                      Helpers.getMonth(assessment.createdOn !=null?DateTime.parse(assessment.createdOn).month:DateTime.now().month).toUpperCase(),
                                                      fontSize: 10,
                                                      color: Colors.grey,
                                                    ),
                                                  ],
                                                )
                                              ],
                                            ),
                                            Column(
                                              crossAxisAlignment: CrossAxisAlignment
                                                  .start,
                                              children: [
                                                Row(
                                                  mainAxisAlignment:
                                                  MainAxisAlignment.start,
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  children: [
                                                    AppText(
                                                      TranslationBase.of(context).ICDName +" : ",
                                                      fontWeight: FontWeight
                                                          .bold,
                                                      fontSize: 13,
                                                    ),
                                                    Container(
                                                      width: MediaQuery
                                                          .of(context)
                                                          .size
                                                          .width * 0.29,
                                                      child: AppText(
                                                        assessment
                                                            .selectedICD.description
                                                            .toString(),
                                                        fontSize: 10,
                                                        color: Colors.grey,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                                Row(
                                                  mainAxisAlignment:
                                                  MainAxisAlignment.start,
                                                  children: [
                                                    AppText(
                                                      TranslationBase.of(context).appointmentNo,
                                                      fontWeight: FontWeight
                                                          .bold,
                                                      fontSize: 13,
                                                    ),
                                                    AppText(
                                                      assessment
                                                          .appointmentId
                                                          .toString(),
                                                      fontSize: 10,
                                                      color: Colors.grey,
                                                    ),
                                                  ],
                                                ),
                                                Row(
                                                  mainAxisAlignment:
                                                  MainAxisAlignment.start,
                                                  children: [
                                                    AppText(
                                                      TranslationBase.of(context).condition + " : ",
                                                      fontWeight: FontWeight
                                                          .bold,
                                                      fontSize: 13,
                                                    ),
                                                    AppText(
                                                     projectViewModel.isArabic?assessment
                                                         .selectedDiagnosisCondition
                                                         .nameAr : assessment
                                                          .selectedDiagnosisCondition
                                                          .nameEn,
                                                      fontSize: 10,
                                                      color: Colors.grey,

                                                    ),
                                                  ],
                                                ),
                                                Row(
                                                  mainAxisAlignment:
                                                  MainAxisAlignment.start,
                                                  children: [
                                                    AppText(
                                                      TranslationBase.of(context).dType+' : ',
                                                      fontWeight: FontWeight
                                                          .bold,
                                                      fontSize: 13,
                                                    ),
                                                    AppText(
                                                      projectViewModel.isArabic?assessment
                                                          .selectedDiagnosisType
                                                          .nameAr:assessment
                                                          .selectedDiagnosisType
                                                          .nameEn,
                                                      fontSize: 10,
                                                      color: Colors.grey,
                                                    ),
                                                  ],
                                                ),
                                                if(assessment.doctorName != null)
                                                Row(
                                                  mainAxisAlignment:
                                                  MainAxisAlignment.start,
                                                  children: [
                                                    AppText(
                                                      TranslationBase.of(context).doc,
                                                      fontWeight: FontWeight
                                                          .bold,
                                                      fontSize: 13,
                                                    ),
                                                    AppText(
                                                      assessment.doctorName??'',
                                                      fontSize: 10,
                                                      color: Colors.grey,
                                                    ),
                                                  ],
                                                ),
                                                SizedBox(
                                                  height: 6,
                                                ),
                                                Row(
                                                  mainAxisAlignment:
                                                  MainAxisAlignment.start,
                                                  children: [
                                                    SizedBox(
                                                      height: 6,
                                                    ),
                                                    AppText(
                                                        assessment.remark != null ||
                                                            assessment.remark == ''
                                                            ? TranslationBase.of(context).remarks + " : "
                                                            : '',
                                                  fontWeight: FontWeight.bold,
                                                  fontSize: 13,
                                                ),
                                                    Container(
                                                      width: MediaQuery
                                                          .of(context)
                                                          .size
                                                          .width * 0.38,
                                                      child: AppText(
                                                        assessment.remark ?? "",
                                                        fontSize: 10,
                                                        color: Colors.grey,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ],
                                            ),
                                            Column(
                                              crossAxisAlignment: CrossAxisAlignment
                                                  .start,
                                              children: [
                                                Row(

                                                  children: [
                                                    AppText(
                                                      "ICD : ".toUpperCase(),
                                                      fontWeight: FontWeight
                                                          .bold,
                                                      fontSize: 13,
                                                    ),
                                                    Container(
                                                      child: AppText(
                                                        assessment.selectedICD
                                                            .code.trim()
                                                            .toUpperCase() ??
                                                            "",
                                                        fontSize: 10,
                                                        color: Colors.grey,
                                                      ),
                                                    ),
                                                  ],
                                                )
                                              ],
                                            ),
                                            Column(
                                              children: [
                                                InkWell(
                                                  onTap: () {
                                                    openAssessmentDialog(
                                                        context, isUpdate: true,
                                                        assessment: assessment,
                                                        model: model);
                                                  },
                                                  child: Icon(EvaIcons
                                                      .edit2Outline),
                                                )
                                              ],
                                            ),
                                          ],
                                        ),
                                      );
                                    }).toList(),)
                                ],
                              )
                            ]),
                            isExpand: isAssessmentExpand,
                          ),
                      DividerWithSpacesAround(
                        height: 30,
                      ),
                      AppButton(
                        title: TranslationBase
                            .of(context)
                            .next,
                        loading: model.state == ViewState.BusyLocal,
                        onPressed: () async {
                          if (widget.mySelectedAssessmentList.isEmpty) {
                            helpers.showErrorToast(
                                TranslationBase.of(context).assessmentErrorMsg);
                          } else {
                            widget.changePageViewIndex(3);
                            widget.changeLoadingState(true);
                          }
                        },
                      ),
                      SizedBox(
                        height: 30,
                      ),
                    ],
                  ),
                ),
              ),
            )));
  }


  openAssessmentDialog(BuildContext context,
      {
        MySelectedAssessment assessment, bool isUpdate,
        SOAPViewModel model
      }) {
    if (assessment == null) {
      assessment = MySelectedAssessment(
          remark: '', appointmentId: widget.patientInfo.appointmentNo);
    }
    showModalBottomSheet(
        backgroundColor: Colors.white,
        isScrollControlled: true,
        context: context,
        builder: (context) {
          return AddAssessmentDetails(
              mySelectedAssessment: assessment,
              patientInfo: widget.patientInfo,
              isUpdate: isUpdate,
              mySelectedAssessmentList: widget.mySelectedAssessmentList,
              addSelectedAssessment: (MySelectedAssessment mySelectedAssessment,
                  bool isUpdate) async {
                setState(() {
                  widget.mySelectedAssessmentList.add(mySelectedAssessment);

                });
              });
        });
  }

}

class AddAssessmentDetails extends StatefulWidget {
  final MySelectedAssessment mySelectedAssessment;
  final List<MySelectedAssessment> mySelectedAssessmentList;
  final Function(MySelectedAssessment mySelectedAssessment, bool isUpdate) addSelectedAssessment;
  final PatiantInformtion patientInfo;
  final bool isUpdate;
  AddAssessmentDetails(
      {Key key, this.mySelectedAssessment, this.addSelectedAssessment, this.patientInfo, this.isUpdate = false, this.mySelectedAssessmentList});


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

class _AddAssessmentDetailsState extends State<AddAssessmentDetails> {
  TextEditingController remarkController = TextEditingController();
  TextEditingController appointmentIdController = TextEditingController();
  TextEditingController conditionController = TextEditingController();
  TextEditingController typeController = TextEditingController();
  TextEditingController icdNameController = TextEditingController();

  GlobalKey key = new GlobalKey<AutoCompleteTextFieldState<MasterKeyModel>>();
  bool isFormSubmitted = false;

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

    remarkController.text = widget.mySelectedAssessment.remark ?? "";
    appointmentIdController.text =
        widget.mySelectedAssessment.appointmentId.toString();
    if(widget.isUpdate){
      if(widget.mySelectedAssessment
          .selectedDiagnosisCondition != null)
      conditionController.text = projectViewModel.isArabic
          ? widget.mySelectedAssessment
          .selectedDiagnosisCondition
          .nameAr
          : widget.mySelectedAssessment
          .selectedDiagnosisCondition
          .nameEn;
      if(widget.mySelectedAssessment
          .selectedDiagnosisType !=null)
      typeController.text = projectViewModel.isArabic
          ? widget.mySelectedAssessment
          .selectedDiagnosisType
          .nameAr
          : widget.mySelectedAssessment
          .selectedDiagnosisType
          .nameEn;
      if(widget.mySelectedAssessment.selectedICD !=null)
      icdNameController.text = widget.mySelectedAssessment.selectedICD.code;
    }
    final screenSize = MediaQuery.of(context).size;
    InputDecoration textFieldSelectorDecoration(
        String hintText, String selectedText, bool isDropDown,
        {IconData icon}) {
      return InputDecoration(
        contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
        focusedBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Colors.grey, width: 1.0),
          borderRadius: BorderRadius.circular(8),
        ),
        enabledBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Colors.grey, width: 1.0),
          borderRadius: BorderRadius.circular(8),
        ),
        disabledBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Colors.grey, width: 1.0),
          borderRadius: BorderRadius.circular(8),
        ),
        hintText: selectedText != null ? selectedText : hintText,
        suffixIcon: isDropDown ? Icon(icon ?? Icons.arrow_drop_down) : null,
        hintStyle: TextStyle(
            fontSize: 10,
            color: Theme.of(context).hintColor,
            fontWeight: FontWeight.w700),
      );
    }
    return FractionallySizedBox(
      heightFactor: 0.75,
      child: BaseView<SOAPViewModel>(
          onModelReady: (model) async {
            if (model.listOfDiagnosisCondition.length == 0) {
              await model.getMasterLookup(MasterKeysService.DiagnosisCondition);
            }
            if (model.listOfDiagnosisType.length == 0) {
              await model.getMasterLookup(MasterKeysService.DiagnosisType);
            }
            if (model.listOfICD10.length == 0) {
              await model.getMasterLookup(MasterKeysService.ICD10);
            }
          },
          builder: (_, model, w) =>
              AppScaffold(
                  baseViewModel: model,
                  isShowAppBar: false,
                  body: SingleChildScrollView(
                    child: Center(
                      child: FractionallySizedBox(
                        widthFactor: 0.9,
                        child: Container(
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  SizedBox(
                                    height: 16,
                                  ),
                                  AppText(
                                    TranslationBase.of(context).addAssessmentDetails.toUpperCase(),
                                    fontWeight: FontWeight.bold,
                                    fontSize: 13,
                                  ),
                                  SizedBox(
                                    height: 16,
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(
                                        left: 0, right: 0, top: 15),
                                    child: TextFields(
                                        hintText: TranslationBase.of(context).appointmentNumber,
                                        fontSize: 13.5,
                                        // hintColor: Colors.black,
                                        hasLabelText: appointmentIdController.text != ''?true:false,
                                        showLabelText: true,
                                        fontWeight: FontWeight.w600,
                                        readOnly: true,
                                        controller: appointmentIdController,
                                        validator: (value) {
                                          if (value == null)
                                            return TranslationBase
                                                .of(context)
                                                .emptyMessage;
                                          else
                                            return null;
                                        }),
                                  ),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  Container(
                                    height: screenSize.height * 0.080,
                                    child: InkWell(
                                        onTap: model.listOfICD10 != null
                                            ? () {
                                          setState(() {
                                            widget.mySelectedAssessment
                                                .selectedICD = null;
                                            icdNameController.text = null;
                                          });
                                        }
                                            : null,
                              child: widget.mySelectedAssessment.selectedICD == null ? AutoCompleteTextField<MasterKeyModel>(
                                decoration: textFieldSelectorDecoration(
                                    TranslationBase
                                        .of(context)
                                        .nameOrICD,
                                    widget.mySelectedAssessment.selectedICD !=
                                        null ? widget.mySelectedAssessment
                                        .selectedICD.nameEn : null, true,
                                    icon: EvaIcons.search),
                                itemSubmitted: (item) =>
                                    setState(()
                                    {
                                      widget.mySelectedAssessment
                                          .selectedICD = item;
                                      icdNameController.text =item.code;
                                    }),
                                key: key,
                                suggestions: model.listOfICD10,
                                itemBuilder: (context, suggestion) =>
                                new Padding(
                                    child: Texts(
                                        suggestion.description + " / " +
                                            suggestion.code.toString()),
                                    padding: EdgeInsets.all(8.0)),
                                itemSorter: (a, b) => 1,
                                itemFilter: (suggestion, input) =>
                                suggestion.description.toLowerCase().startsWith(
                                    input.toLowerCase()) ||
                                    suggestion.description.toLowerCase()
                                        .startsWith(input.toLowerCase())
                                    || suggestion.code.toLowerCase().startsWith(
                                    input.toLowerCase())
                                ,
                              )
                                  : TextFields(
                                  onTapTextFields: model.listOfICD10 != null
                                      ? () {
                                    setState(() {
                                      widget.mySelectedAssessment.selectedICD =
                                      null;
                                      icdNameController.text = null;
                                    });
                                  }
                                      : null,
                                  hasLabelText: icdNameController.text !=
                                      '' ? true : false,
                                  showLabelText: true,
                                  hintText: TranslationBase
                                      .of(context)
                                      .nameOrICD,
                                  fontSize: 13.5,
                                  readOnly: true,
                                  fontWeight: FontWeight.w600,
                                  maxLines: 2,
                                  minLines: 1,
                                  controller: icdNameController,
                                  suffixIcon: EvaIcons.search,
                                  validator: (value) {
                                    if (value == null)
                                      return TranslationBase
                                          .of(context)
                                          .emptyMessage;
                                    else
                                      return null;
                                  })

                                      // TextField(
                                      //   decoration: textFieldSelectorDecoration(
                                      //       widget.mySelectedAssessment.selectedICD !=
                                      //           null ? widget.mySelectedAssessment
                                      //           .selectedICD.code : "Name or ICD",
                                      //       widget.mySelectedAssessment.selectedICD !=
                                      //           null ? projectViewModel.isArabic
                                      //           ? widget.mySelectedAssessment
                                      //           .selectedICD.nameAr
                                      //           : widget.mySelectedAssessment
                                      //           .selectedICD.nameEn : null, true,
                                      //       icon: EvaIcons.search),
                                      //   enabled: false,
                                      // ),
                                    ),
                                  ),
                                  if(isFormSubmitted &&
                                      widget.mySelectedAssessment
                                          .selectedICD == null)
                                    CustomValidationError(),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  TextFields(
                                      onTapTextFields: model
                                          .listOfDiagnosisCondition !=
                                          null
                                          ? () {
                                        MasterKeyDailog dialog = MasterKeyDailog(
                                          list: model.listOfDiagnosisCondition,
                                          okText: TranslationBase
                                              .of(context)
                                              .ok,
                                          okFunction: (
                                              MasterKeyModel selectedValue) {
                                            setState(() {
                                              widget.mySelectedAssessment
                                                  .selectedDiagnosisCondition =
                                                  selectedValue;
                                              conditionController.text =
                                              projectViewModel.isArabic
                                                  ? widget.mySelectedAssessment
                                                  .selectedDiagnosisCondition
                                                  .nameAr
                                                  : widget.mySelectedAssessment
                                                  .selectedDiagnosisCondition
                                                  .nameEn;
                                            });
                                          },
                                        );
                                        showDialog(
                                          barrierDismissible: false,
                                          context: context,
                                          builder: (BuildContext context) {
                                            return dialog;
                                          },
                                        );
                                      }
                                          : null,
                                      hasLabelText: conditionController.text !=
                                          '' ? true : false,
                                      showLabelText: true,
                                      hintText: TranslationBase
                                          .of(context)
                                          .condition,
                                      fontSize: 13.5,
                                      readOnly: true,
                                      // hintColor: Colors.black,
                                      fontWeight: FontWeight.w600,
                                      maxLines: 2,
                                      minLines: 1,
                                      controller: conditionController,
                                      validator: (value) {
                                        if (value == null)
                                          return TranslationBase
                                              .of(context)
                                              .emptyMessage;
                                        else
                                          return null;
                                      }),
                                  if(isFormSubmitted &&
                                      widget.mySelectedAssessment
                                          .selectedDiagnosisCondition == null)
                                    CustomValidationError(),
                                  SizedBox(
                                    height: 10,
                                  ),


                                  TextFields(
                                      onTapTextFields: model
                                          .listOfDiagnosisType != null
                                          ? () {
                                        MasterKeyDailog dialog = MasterKeyDailog(
                                          list: model.listOfDiagnosisType,
                                          okText: TranslationBase
                                              .of(context)
                                              .ok,
                                          okFunction: (
                                              MasterKeyModel selectedValue) {
                                            setState(() {
                                              // _selectedDiagnosisType =
                                              //     selectedValue;
                                              widget.mySelectedAssessment
                                                  .selectedDiagnosisType =
                                                  selectedValue;
                                              typeController.text =
                                              projectViewModel.isArabic
                                                  ? selectedValue
                                                  .nameAr
                                                  : selectedValue
                                                  .nameEn;
                                            });
                                          },
                                        );
                                        showDialog(
                                          barrierDismissible: false,
                                          context: context,
                                          builder: (BuildContext context) {
                                            return dialog;
                                          },
                                        );
                                      }
                                          : null,
                                      hasLabelText: typeController.text !=
                                          '' ? true : false,
                                      showLabelText: true,
                                      hintText: TranslationBase
                                          .of(context)
                                          .dType,
                                      fontSize: 13.5,
                                      readOnly: true,
                                      // hintColor: Colors.black,
                                      fontWeight: FontWeight.w600,
                                      maxLines: 2,
                                      minLines: 1,
                                      controller: typeController,
                                      validator: (value) {
                                        if (value == null)
                                          return TranslationBase
                                              .of(context)
                                              .emptyMessage;
                                        else
                                          return null;
                                      }),
                                  if(isFormSubmitted &&
                                      widget.mySelectedAssessment
                                          .selectedDiagnosisType == null)
                                    CustomValidationError(),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(
                                        left: 0, right: 0, top: 15),
                                    child: TextFields(
                                        hintText: TranslationBase
                                            .of(context)
                                            .remarks,
                                        fontSize: 13.5,
                                        // hintColor: Colors.black,
                                        fontWeight: FontWeight.w600,
                                        maxLines: 18,
                                        minLines: 5,
                                        hasLabelText: remarkController.text !=
                                            '' ? true : false,
                                        showLabelText: true,
                                        controller: remarkController,
                                        onChanged: (value) {
                                          widget.mySelectedAssessment.remark =
                                              remarkController.text;
                                        },
                                        validator: (value) {
                                          if (value == null)
                                            return TranslationBase
                                                .of(context)
                                                .emptyMessage;
                                          else
                                            return null;
                                        }),
                                  ),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  AppButton(
                                    title: (widget.isUpdate?TranslationBase.of(context).update:TranslationBase.of(context).add).toUpperCase(),
                                    loading: model.state == ViewState.BusyLocal,
                                    onPressed: () async {
                                      setState(() {
                                        isFormSubmitted = true;
                                      });
                                        widget.mySelectedAssessment.remark =
                                            remarkController.text;
                                        widget.mySelectedAssessment
                                            .appointmentId = int.parse(
                                            appointmentIdController.text);
                                        if (widget.mySelectedAssessment
                                            .selectedDiagnosisCondition !=
                                            null &&
                                            widget.mySelectedAssessment
                                                .selectedDiagnosisType !=
                                                null &&
                                            widget.mySelectedAssessment
                                                .selectedICD != null) {
                                          await submitAssessment(
                                              isUpdate: widget.isUpdate,
                                              model: model,
                                              mySelectedAssessment: widget
                                                  .mySelectedAssessment);
                                        }
                                    },
                                  ),
                                ])),
                      ),
                    ),
                  ))),
    );
  }

  submitAssessment(
      {SOAPViewModel model, MySelectedAssessment mySelectedAssessment, bool isUpdate = false}) async {
    if (isUpdate) {
      PatchAssessmentReqModel patchAssessmentReqModel =
      PatchAssessmentReqModel(
          patientMRN: widget.patientInfo.patientMRN,
          episodeID: widget.patientInfo.episodeNo,
          appointmentNo: widget.patientInfo.appointmentNo,
          remarks: mySelectedAssessment.remark,
          complexDiagnosis: true,
          conditionId:
          mySelectedAssessment.selectedDiagnosisCondition.id,
          diagnosisTypeId:
          mySelectedAssessment.selectedDiagnosisType.id,
          icdcode10Id: mySelectedAssessment.selectedICD.code,
          prevIcdCode10ID: mySelectedAssessment.icdCode10ID
      );

      await model.patchAssessment(patchAssessmentReqModel);
    } else {
      PostAssessmentRequestModel postAssessmentRequestModel =
      new PostAssessmentRequestModel(
          patientMRN: widget.patientInfo.patientMRN,
          episodeId: widget.patientInfo.episodeNo,
          appointmentNo: widget.patientInfo.appointmentNo,
          icdCodeDetails: [
            new IcdCodeDetails(
                remarks: mySelectedAssessment.remark,
                complexDiagnosis: true,
                conditionId:
                mySelectedAssessment.selectedDiagnosisCondition.id,
                diagnosisTypeId:
                mySelectedAssessment.selectedDiagnosisType.id,
                icdcode10Id: mySelectedAssessment.selectedICD.code)
          ]);

      await model.postAssessment(postAssessmentRequestModel);
    }


    if (model.state == ViewState.ErrorLocal) {
      helpers
          .showErrorToast(model.error);
    } else {
      Map profile = await sharedPref.getObj(DOCTOR_PROFILE);

      DoctorProfileModel doctorProfile = DoctorProfileModel.fromJson(profile);
      mySelectedAssessment.icdCode10ID = mySelectedAssessment.selectedICD.code;
      mySelectedAssessment.doctorName = doctorProfile.doctorName;

      if (!isUpdate) {
        // widget.mySelectedAssessmentList.add(mySelectedAssessment);
        widget.addSelectedAssessment(mySelectedAssessment,isUpdate);
      }
      Navigator.of(context).pop();
    }


    // widget.changePageViewIndex(3);
  }
}


class PatchAssessmentReqModel {
  int patientMRN;
  int appointmentNo;
  int episodeID;
  String icdcode10Id;
  String prevIcdCode10ID;
  int conditionId;
  int diagnosisTypeId;
  bool complexDiagnosis;
  String remarks;

  PatchAssessmentReqModel(
      {this.patientMRN,
        this.appointmentNo,
        this.episodeID,
        this.icdcode10Id,
        this.prevIcdCode10ID,
        this.conditionId,
        this.diagnosisTypeId,
        this.complexDiagnosis,
        this.remarks});

  PatchAssessmentReqModel.fromJson(Map<String, dynamic> json) {
    patientMRN = json['PatientMRN'];
    appointmentNo = json['AppointmentNo'];
    episodeID = json['EpisodeID'];
    icdcode10Id = json['Icdcode10Id'];
    prevIcdCode10ID = json['PrevIcdCode10ID'];
    conditionId = json['ConditionId'];
    diagnosisTypeId = json['DiagnosisTypeId'];
    complexDiagnosis = json['ComplexDiagnosis'];
    remarks = json['Remarks'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['PatientMRN'] = this.patientMRN;
    data['AppointmentNo'] = this.appointmentNo;
    data['EpisodeID'] = this.episodeID;
    data['Icdcode10Id'] = this.icdcode10Id;
    data['PrevIcdCode10ID'] = this.prevIcdCode10ID;
    data['ConditionId'] = this.conditionId;
    data['DiagnosisTypeId'] = this.diagnosisTypeId;
    data['ComplexDiagnosis'] = this.complexDiagnosis;
    data['Remarks'] = this.remarks;
    return data;
  }
}


