import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/api/leave_balance_api_client.dart';
import 'package:mohem_flutter_app/classes/date_uitl.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/config/routes.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/models/get_eit_dff_structure_list_model.dart';
import 'package:mohem_flutter_app/models/leave_balance/calculate_absence_duration_model.dart';
import 'package:mohem_flutter_app/models/leave_balance/get_absence_attendance_types_list_model.dart';
import 'package:mohem_flutter_app/models/leave_balance/get_absence_dff_structure_list_model.dart';
import 'package:mohem_flutter_app/models/leave_balance/sumbit_absence_transaction_list_model.dart';
import 'package:mohem_flutter_app/models/worklist/replacement_list_model.dart';
import 'package:mohem_flutter_app/ui/misc/request_submit_screen.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:mohem_flutter_app/widgets/bottom_sheet.dart';
import 'package:mohem_flutter_app/widgets/bottom_sheets/search_employee_bottom_sheet.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/dynamic_forms/dynamic_textfield_widget.dart';

class AddLeaveBalanceScreen extends StatefulWidget {
  AddLeaveBalanceScreen({Key? key}) : super(key: key);

  @override
  _AddLeaveBalanceScreenState createState() {
    return _AddLeaveBalanceScreenState();
  }
}

class _AddLeaveBalanceScreenState extends State<AddLeaveBalanceScreen> {
  List<GetAbsenceDffStructureList> getabsenceDffStructureList = [];
  List<GetAbsenceAttendanceTypesList> absenceList = [];

  GetAbsenceAttendanceTypesList? selectedAbsenceType;
  DateTime? startDateTime;
  DateTime? endDateTime;
  int? totalDays;
  String comment = "";
  ReplacementList? selectedReplacementEmployee;

  DateTime selectedDate = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day);

  @override
  void initState() {
    super.initState();
    getAbsenceAttendanceTypes();
  }

  void getAbsenceAttendanceTypes() async {
    try {
      Utils.showLoading(context);
      absenceList = await LeaveBalanceApiClient().getAbsenceAttendanceTypes();
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getAbsenceDffStructure() async {
    try {
      Utils.showLoading(context);
      getabsenceDffStructureList.clear();
      getabsenceDffStructureList = await LeaveBalanceApiClient().getAbsenceDffStructure(selectedAbsenceType!.dESCFLEXCONTEXTCODE!, "HR_LOA_SS", -999);
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getCalculatedAbsenceDuration() async {
    try {
      Utils.showLoading(context);
      CalculateAbsenceDuration duration = await LeaveBalanceApiClient()
          .calculateAbsenceDuration(selectedAbsenceType!.aBSENCEATTENDANCETYPEID!, Utils.getMonthNamedFormat(startDateTime!), Utils.getMonthNamedFormat(endDateTime!), -999);

      totalDays = duration.pABSENCEDAYS?.toInt();
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void validateAbsenceTransaction() async {
    try {
      Utils.showLoading(context);
      Map<String, String?> dffDataMap = {};
      for (int i = 1; i <= 20; i++) {
        dffDataMap["P_ATTRIBUTE$i"] = null;
        for (int dffIndex = 0; dffIndex < getabsenceDffStructureList.length; dffIndex++) {
          if ("ATTRIBUTE$i" == getabsenceDffStructureList[dffIndex].aPPLICATIONCOLUMNNAME) {
            if (getabsenceDffStructureList[dffIndex].fORMATTYPE == "X") {
              dffDataMap["P_ATTRIBUTE$i"] = Utils.formatDate(getabsenceDffStructureList[dffIndex].eSERVICESDV!.pIDCOLUMNNAME!);
            } else {
              dffDataMap["P_ATTRIBUTE$i"] = getabsenceDffStructureList[dffIndex].eSERVICESDV?.pIDCOLUMNNAME;
            }
            break;
          }
        }
      }
      await LeaveBalanceApiClient().validateAbsenceTransaction(selectedAbsenceType!.dESCFLEXCONTEXTCODE!, "HR_LOA_SS", selectedAbsenceType!.aBSENCEATTENDANCETYPEID!,
          selectedReplacementEmployee != null ? selectedReplacementEmployee!.userName! : "", DateUtil.getFormattedDate(startDateTime!, "MM/dd/yyyy"), DateUtil.getFormattedDate(endDateTime!, "MM/dd/yyyy"), -999, dffDataMap,
          comments: comment);

      SumbitAbsenceTransactionList submit = await LeaveBalanceApiClient().submitAbsenceTransaction(
          selectedAbsenceType!.dESCFLEXCONTEXTCODE!,
          "HR_LOA_SS",
          selectedAbsenceType!.aBSENCEATTENDANCETYPEID!,
          selectedReplacementEmployee != null ? selectedReplacementEmployee!.userName! : "",
          DateUtil.getFormattedDate(startDateTime!, "MM/dd/yyyy"),
          DateUtil.getFormattedDate(endDateTime!, "MM/dd/yyyy"),
          -999,
          dffDataMap,
          comments: comment);

      Utils.hideLoading(context);

      await Navigator.pushNamed(context, AppRoutes.requestSubmitScreen, arguments: RequestSubmitScreenParams(LocaleKeys.submit.tr(), submit.pTRANSACTIONID!, "", "add_leave_balance"));
      // Utils.showLoading(context);
      await LeaveBalanceApiClient().cancelHrTransaction(submit.pTRANSACTIONID!);
      // Utils.hideLoading(context);
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(
        context,
        title: LocaleKeys.leaveBalance.tr(),
      ),
      body: Column(
        children: [
          ListView(
            padding: const EdgeInsets.all(21),
            children: [
              PopupMenuButton(
                child: DynamicTextFieldWidget(
                  LocaleKeys.absenceType.tr() + "*",
                  selectedAbsenceType == null ? LocaleKeys.selectTypeT.tr() : selectedAbsenceType!.aBSENCEATTENDANCETYPENAME!,
                  isEnable: false,
                  isPopup: true,
                ),
                itemBuilder: (_) => <PopupMenuItem<int>>[
                  for (int i = 0; i < absenceList.length; i++) PopupMenuItem<int>(value: i, child: Text(absenceList[i].aBSENCEATTENDANCETYPENAME!)),
                ],
                onSelected: (int popupIndex) {
                  if (selectedAbsenceType == absenceList[popupIndex]) {
                    return;
                  }
                  selectedAbsenceType = absenceList[popupIndex];
                  setState(() {});
                  getAbsenceDffStructure();
                },
              ),
              12.height,
              DynamicTextFieldWidget(
                LocaleKeys.startDateT.tr() + "*",
                startDateTime == null ? LocaleKeys.pleaseSelectDate.tr() : startDateTime.toString().split(' ')[0],
                suffixIconData: Icons.calendar_today,
                isEnable: false,
                onTap: () async {
                  var start = await _selectDate(context);
                  if (start != startDateTime) {
                    startDateTime = start;
                    setState(() {});
                  }
                },
              ),
              12.height,
              DynamicTextFieldWidget(
                LocaleKeys.endDateT.tr() + "*",
                endDateTime == null ? LocaleKeys.pleaseSelectDate.tr() : endDateTime.toString().split(' ')[0],
                suffixIconData: Icons.calendar_today,
                isEnable: false,
                isReadOnly: selectedAbsenceType == null || startDateTime == null,
                onTap: () async {
                  if (selectedAbsenceType == null || startDateTime == null) return;
                  var end = await _selectDate(context);
                  if (end != endDateTime) {
                    endDateTime = end;
                    setState(() {});
                    getCalculatedAbsenceDuration();
                  }
                },
              ),
              12.height,
              DynamicTextFieldWidget(
                LocaleKeys.totalDays.tr(),
                totalDays?.toString() ?? LocaleKeys.calculatedDays.tr(),
                isInputTypeNum: true,
                isEnable: false,
                onChange: (input) {
                  totalDays = int.parse(input);
                },
              ),
              12.height,
              DynamicTextFieldWidget(
                LocaleKeys.selectEmployee.tr(),
                selectedReplacementEmployee == null ? LocaleKeys.searchForEmployee.tr() : selectedReplacementEmployee!.employeeDisplayName ?? "",
                isEnable: false,
                onTap: () {
                  showMyBottomSheet(
                    context,
                    child: SearchEmployeeBottomSheet(
                      title: LocaleKeys.searchForEmployee.tr(),
                      apiMode: LocaleKeys.delegate.tr(),
                      fromChat: false,
                      onSelectEmployee: (_selectedEmployee) {
                        //   Navigator.pop(context);
                        selectedReplacementEmployee = _selectedEmployee;
                        setState(() {});
                      },
                    ),
                  );
                },
              ),
              12.height,
              DynamicTextFieldWidget(
                LocaleKeys.comments.tr(),
                LocaleKeys.writeComment.tr(),
                lines: 2,
                onChange: (input) {
                  comment = input;
                },
              ),
              ListView.separated(
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                padding: const EdgeInsets.only(top: 12),
                itemBuilder: (cxt, int parentIndex) => parseDynamicFormatType(getabsenceDffStructureList[parentIndex], parentIndex),
                separatorBuilder: (cxt, index) => 0.height,
                itemCount: getabsenceDffStructureList.length,
              )
            ],
          ).expanded,
          DefaultButton(
            LocaleKeys.next.tr(),
            validateFieldData()
                ? null
                : () {
                    validateAbsenceTransaction();
                  },
          ).insideContainer
        ],
      ),
    );
  }

  bool validateFieldData() {
    List filteredList = getabsenceDffStructureList.where((element) => element.rEQUIREDFLAG == "Y" && (element.eSERVICESDV?.pVALUECOLUMNNAME) == null).toList();
    return (selectedAbsenceType == null || startDateTime == null || endDateTime == null || filteredList.isNotEmpty);
  }

  Widget parseDynamicFormatType(GetAbsenceDffStructureList model, int index) {
    if (model.dISPLAYFLAG != "N") {
      if (model.vALIDATIONTYPE == "N") {
        if (model.fORMATTYPE == "C") {
          return DynamicTextFieldWidget(
            (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
            model.eSERVICESDV?.pIDCOLUMNNAME ?? "",
            isReadOnly: model.rEADONLY == "Y",
            onChange: (text) {
              model.eSERVICESDV ??= ESERVICESDV();
              model.eSERVICESDV!.pIDCOLUMNNAME = text;
            },
          ).paddingOnly(bottom: 12);
        } else if (model.fORMATTYPE == "N") {
          return DynamicTextFieldWidget(
            (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
            model.eSERVICESDV?.pIDCOLUMNNAME ?? "",
            isReadOnly: model.rEADONLY == "Y",
            isInputTypeNum: true,
            onChange: (text) {
              model.eSERVICESDV ??= ESERVICESDV();
              model.eSERVICESDV!.pIDCOLUMNNAME = text;
            },
          ).paddingOnly(bottom: 12);
        } else if (model.fORMATTYPE == "X") {
          String displayText = model.eSERVICESDV?.pIDCOLUMNNAME ?? "";

          if (getabsenceDffStructureList[index].isDefaultTypeIsCDPS) {
            if (displayText.contains(" 00:00:00")) {
              displayText = displayText.replaceAll(" 00:00:00", "");
            }
            if (displayText.contains("/")) {
              displayText = DateFormat('yyyy-MM-dd').format(DateFormat("yyyy/MM/dd").parse(displayText));
            }
          }
          return DynamicTextFieldWidget(
            (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
            displayText,
            suffixIconData: Icons.calendar_today,
            isEnable: false,
            onTap: () async {
              if ((getabsenceDffStructureList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
                if (getabsenceDffStructureList![index].isDefaultTypeIsCDPS) {
                  selectedDate = DateFormat("yyyy/MM/dd").parse(getabsenceDffStructureList![index].eSERVICESDV!.pVALUECOLUMNNAME!.replaceAll('/"', '').replaceAll(" 00:00:00", ""));
                } else {
                  selectedDate = DateTime.parse(getabsenceDffStructureList![index].eSERVICESDV!.pVALUECOLUMNNAME!);
                }
              }
              DateTime date = await _selectDate(context);
              String dateString = date.toString().split(' ').first;
              // DateTime date1 = DateTime(date.year, date.month, date.day);
              // getabsenceDffStructureList![index].fieldAnswer = date.toString();
              ESERVICESDV eservicesdv;
              if (getabsenceDffStructureList![index].isDefaultTypeIsCDPS) {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: Utils.formatDate(dateString),
                    pRETURNMSG: "null",
                    pRETURNSTATUS: getabsenceDffStructureList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME:
                        getabsenceDffStructureList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              } else {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: dateString,
                    pRETURNMSG: "null",
                    pRETURNSTATUS: getabsenceDffStructureList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME:
                        getabsenceDffStructureList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              }
              getabsenceDffStructureList![index].eSERVICESDV = eservicesdv;
              setState(() {});
              // if (model.cHILDSEGMENTSVSSplited?.isNotEmpty ?? false) {
              //   await calGetValueSetValues(model);
              // }
              // if (model.cHILDSEGMENTSDVSplited?.isNotEmpty ?? false) {
              //   await getDefaultValues(model);
              // }
            },
          ).paddingOnly(bottom: 12);
        } else if (model.fORMATTYPE == "Y") {
          String displayText = model.eSERVICESDV?.pIDCOLUMNNAME ?? "";
          if (getabsenceDffStructureList![index].isDefaultTypeIsCDPS) {
            displayText = Utils.reverseFormatDate(displayText);
            // if (displayText.contains(" 00:00:00")) {
            //   displayText = displayText.replaceAll(" 00:00:00", "");
            // }
            // if (!displayText.contains("-")) {
            //   displayText = DateFormat('yyyy-MM-dd').format(DateFormat("yyyy/MM/dd").parse(displayText));
            // }
          }
          return DynamicTextFieldWidget(
            (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
            displayText,
            suffixIconData: Icons.calendar_today,
            isEnable: false,
            onTap: () async {
              if ((getabsenceDffStructureList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
                if (getabsenceDffStructureList![index].isDefaultTypeIsCDPS) {
                  String tempDate = getabsenceDffStructureList![index].eSERVICESDV!.pVALUECOLUMNNAME!;
                  if (tempDate.contains("00:00:00")) {
                    tempDate = tempDate.replaceAll("00:00:00", '').trim();
                  }
                  if (tempDate.contains("/")) {
                    selectedDate = DateFormat("yyyy/MM/dd").parse(tempDate);
                  } else {
                    selectedDate = DateFormat("yyyy-MM-dd").parse(tempDate);
                  }
                } else {
                  selectedDate = DateTime.parse(getabsenceDffStructureList![index].eSERVICESDV!.pVALUECOLUMNNAME!);
                }
              }
              DateTime date = await _selectDate(context);
              String dateString = date.toString().split(' ').first;
              // getabsenceDffStructureList![index].fieldAnswer = date.toString();
              ESERVICESDV eservicesdv;
              if (getabsenceDffStructureList![index].isDefaultTypeIsCDPS) {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: Utils.formatDate(dateString),
                    pRETURNMSG: "null",
                    pRETURNSTATUS: getabsenceDffStructureList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME:
                        getabsenceDffStructureList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              } else {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: dateString,
                    pRETURNMSG: "null",
                    pRETURNSTATUS: getabsenceDffStructureList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME:
                        getabsenceDffStructureList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              }

              getabsenceDffStructureList![index].eSERVICESDV = eservicesdv;
              setState(() {});
              // if (model.cHILDSEGMENTSVSSplited?.isNotEmpty ?? false) {
              //   await calGetValueSetValues(model);
              // }
              // if (model.cHILDSEGMENTSDVSplited?.isNotEmpty ?? false) {
              //   await getDefaultValues(model);
              // }
            },
          ).paddingOnly(bottom: 12);
        }
      } else {
        return PopupMenuButton(
            child: DynamicTextFieldWidget(
              (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
              model.eSERVICESDV?.pVALUECOLUMNNAME ?? "",
              isEnable: false,
              isPopup: true,
              isInputTypeNum: true,
              isReadOnly: model.rEADONLY == "Y",
            ).paddingOnly(bottom: 12),
            itemBuilder: (_) => <PopupMenuItem<int>>[
                  if (model.rEADONLY != "Y")
                    for (int i = 0; i < model.eSERVICESVS!.length; i++) PopupMenuItem<int>(child: Text(model.eSERVICESVS![i].vALUECOLUMNNAME!), value: i),
                ],
            onSelected: (int popipIndex) async {
              ESERVICESDV eservicesdv = ESERVICESDV(
                  pIDCOLUMNNAME: model.eSERVICESVS![popipIndex].iDCOLUMNNAME,
                  pRETURNMSG: "null",
                  pRETURNSTATUS: "null", //getabsenceDffStructureList![popipIndex].dEFAULTVALUE,
                  pVALUECOLUMNNAME: model.eSERVICESVS![popipIndex].vALUECOLUMNNAME);
              getabsenceDffStructureList![index].eSERVICESDV = eservicesdv;
              setState(() {});
              // if (model.cHILDSEGMENTSVSSplited?.isNotEmpty ?? false) {
              //   await calGetValueSetValues(model);
              // }
              // if (model.cHILDSEGMENTSDVSplited?.isNotEmpty ?? false) {
              //   await getDefaultValues(model);
              // }
            });
      }
    } else {
      return const SizedBox();
    }
    if (model.fORMATTYPE == "N") {
      if (model.eSERVICESVS?.isNotEmpty ?? false) {
        return PopupMenuButton(
            child: DynamicTextFieldWidget(
              (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
              model.eSERVICESDV?.pVALUECOLUMNNAME ?? "",
              isEnable: false,
              isPopup: true,
              isInputTypeNum: true,
              isReadOnly: model.rEADONLY == "Y",
            ).paddingOnly(bottom: 12),
            itemBuilder: (_) => <PopupMenuItem<int>>[
                  if (model.rEADONLY != "Y")
                    for (int i = 0; i < model.eSERVICESVS!.length; i++) PopupMenuItem<int>(value: i, child: Text(model.eSERVICESVS![i].vALUECOLUMNNAME!)),
                ],
            onSelected: (int popipIndex) async {
              ESERVICESDV eservicesdv =
                  ESERVICESDV(pIDCOLUMNNAME: model.eSERVICESVS![popipIndex].iDCOLUMNNAME, pRETURNMSG: "null", pRETURNSTATUS: "null", pVALUECOLUMNNAME: model.eSERVICESVS![popipIndex].vALUECOLUMNNAME);
              getabsenceDffStructureList![index].eSERVICESDV = eservicesdv;
              setState(() {});
              // if (model.cHILDSEGMENTSVSSplited?.isNotEmpty ?? false) {
              //   await calGetValueSetValues(model);
              // }
              // if (model.cHILDSEGMENTSDVSplited?.isNotEmpty ?? false) {
              //   await getDefaultValues(model);
              // }
            });
      }

      return DynamicTextFieldWidget(
        (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
        model.eSERVICESDV?.pIDCOLUMNNAME ?? "",
        isReadOnly: model.rEADONLY == "Y",
        onChange: (text) {
          //model.fieldAnswer = text;
        },
      ).paddingOnly(bottom: 12);
    } else if (model.fORMATTYPE == "X" || model.fORMATTYPE == "Y") {
      String displayText = model.eSERVICESDV?.pIDCOLUMNNAME ?? "";
      if (getabsenceDffStructureList![index].isDefaultTypeIsCDPS) {
        if (displayText.contains(" 00:00:00")) {
          displayText = displayText.replaceAll(" 00:00:00", "");
        }
        if (!displayText.contains("-")) {
          displayText = DateFormat('yyyy-MM-dd').format(DateFormat("yyyy/MM/dd").parse(displayText));
        }
      }
      return DynamicTextFieldWidget(
        (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
        displayText,
        suffixIconData: Icons.calendar_today,
        isEnable: false,
        onTap: () async {
          if ((getabsenceDffStructureList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
            if (getabsenceDffStructureList![index].isDefaultTypeIsCDPS) {
              selectedDate = DateFormat("yyyy/MM/dd").parse(getabsenceDffStructureList![index].eSERVICESDV!.pVALUECOLUMNNAME!.replaceAll('/"', '').replaceAll(" 00:00:00", ""));
            } else {
              selectedDate = DateTime.parse(getabsenceDffStructureList![index].eSERVICESDV!.pVALUECOLUMNNAME!);
            }
          }
          DateTime date = await _selectDate(context);
          String dateString = date.toString().split(' ').first;
          // getabsenceDffStructureList![index].fieldAnswer = date.toString();
          ESERVICESDV eservicesdv = ESERVICESDV(
              pIDCOLUMNNAME: dateString,
              pRETURNMSG: "null",
              pRETURNSTATUS: getabsenceDffStructureList![index].dEFAULTVALUE,
              pVALUECOLUMNNAME:
                  getabsenceDffStructureList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
          getabsenceDffStructureList![index].eSERVICESDV = eservicesdv;
          setState(() {});
          // if (model.cHILDSEGMENTSVSSplited?.isNotEmpty ?? false) {
          //   await calGetValueSetValues(model);
          // }
          // if (model.cHILDSEGMENTSDVSplited?.isNotEmpty ?? false) {
          //   await getDefaultValues(model);
          // }
        },
      ).paddingOnly(bottom: 12);
    } else if (model.fORMATTYPE == "I") {
      return DynamicTextFieldWidget(
        (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
        model.eSERVICESDV?.pIDCOLUMNNAME ?? "",
        suffixIconData: Icons.access_time_filled_rounded,
        isEnable: false,
        onTap: () async {
          if (getabsenceDffStructureList[index].mOBILEENABLED != "Y") return;

          if ((getabsenceDffStructureList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
            var timeString = getabsenceDffStructureList![index].eSERVICESDV!.pVALUECOLUMNNAME!.split(":");
            selectedDate = DateTime(0, 0, 0, int.parse(timeString[0]), int.parse(timeString[1]));

            //DateTime.parse(getabsenceDffStructureList![index].eSERVICESDV!.pVALUECOLUMNNAME!);
          }
          TimeOfDay _time = await _selectTime(context);
          DateTime tempTime = DateTime(0, 1, 1, _time.hour, _time.minute);
          String time = DateFormat('HH:mm').format(tempTime).trim();

          // DateTime date1 = DateTime(date.year, date.month, date.day);
          //  getabsenceDffStructureList![index].fieldAnswer = date.toString();
          ESERVICESDV eservicesdv = ESERVICESDV(pIDCOLUMNNAME: time, pRETURNMSG: "null", pRETURNSTATUS: getabsenceDffStructureList![index].dEFAULTVALUE, pVALUECOLUMNNAME: time);
          getabsenceDffStructureList![index].eSERVICESDV = eservicesdv;
          setState(() {});
          // if (model.cHILDSEGMENTSVSSplited?.isNotEmpty ?? false) {
          //   await calGetValueSetValues(model);
          // }
          // if (model.cHILDSEGMENTSDVSplited?.isNotEmpty ?? false) {
          //   await getDefaultValues(model);
          // }
        },
      ).paddingOnly(bottom: 12);
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [],
    ).objectContainerView();
  }

  Future<DateTime> _selectDate(BuildContext context) async {
    DateTime time = selectedDate;
    if (Platform.isIOS) {
      await showCupertinoModalPopup(
        context: context,
        builder: (cxt) => Container(
          height: 250,
          color: Colors.white,
          child: CupertinoDatePicker(
            backgroundColor: Colors.white,
            mode: CupertinoDatePickerMode.date,
            onDateTimeChanged: (value) {
              if (value != null && value != selectedDate) {
                time = value;
              }
            },
            initialDateTime: selectedDate,
          ),
        ),
      );
    } else {
      DateTime? picked = await showDatePicker(context: context, initialDate: selectedDate, initialEntryMode: DatePickerEntryMode.calendarOnly, firstDate: DateTime(2015, 8), lastDate: DateTime(2101));
      if (picked != null && picked != selectedDate) {
        time = picked;
      }
    }
    time = DateTime(time.year, time.month, time.day);
    return time;
  }

  Future<TimeOfDay> _selectTime(BuildContext context) async {
    TimeOfDay time = TimeOfDay(hour: selectedDate.hour, minute: selectedDate.minute);
    if (Platform.isIOS) {
      await showCupertinoModalPopup(
        context: context,
        builder: (cxt) => Container(
          height: 250,
          color: Colors.white,
          child: CupertinoDatePicker(
            backgroundColor: Colors.white,
            mode: CupertinoDatePickerMode.time,
            use24hFormat: true,
            onDateTimeChanged: (value) {
              if (value != null && value != selectedDate) {
                time = TimeOfDay(hour: value.hour, minute: value.minute);
              }
            },
            initialDateTime: selectedDate,
          ),
        ),
      );
    } else {
      TimeOfDay? picked = await showTimePicker(
          context: context,
          initialTime: time,
          builder: (cxt, child) {
            return MediaQuery(data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true), child: child ?? Container());
          });

      if (picked != null && picked != time) {
        time = picked;
      }
      // final DateTime? picked =
      // await showDatePicker(context: context, initialDate: selectedDate, initialEntryMode: DatePickerEntryMode.calendarOnly, firstDate: DateTime(2015, 8), lastDate: DateTime(2101));
      // if (picked != null && picked != selectedDate) {
      //   time = picked;
      // }
    }
    return time;
  }
}
