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/api/my_attendance_api_client.dart';
import 'package:mohem_flutter_app/api/termination_dff_api_client.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/dyanmic_forms/get_set_values_request_model.dart';
import 'package:mohem_flutter_app/models/dyanmic_forms/validate_eit_transaction_model.dart';
import 'package:mohem_flutter_app/models/get_eit_dff_structure_list_model.dart' as dff;
import 'package:mohem_flutter_app/models/submit_term_transaction_list_model.dart';
import 'package:mohem_flutter_app/models/termination/get_term_cols_structure_list_model.dart';
import 'package:mohem_flutter_app/models/termination/get_term_dff_structure_list_model.dart';
import 'package:mohem_flutter_app/ui/misc/request_submit_screen.dart';
import 'package:mohem_flutter_app/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/dynamic_forms/dynamic_textfield_widget.dart';

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

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

class _EndEmploymentScreenState extends State<EndEmploymentScreen> {
  List<GetTermColsStructureList>? termColsList;
  List<GetTermDffStructureList>? termDffList;
  DynamicListViewParams? dynamicParams;

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

  void getTerminationDffStructure() async {
    try {
      Utils.showLoading(context);
      List results = await Future.wait([
        TerminationDffApiClient().getTermColsStructure(),
        TerminationDffApiClient().getTermDffStructure(dynamicParams!.dynamicId, null),
      ]);
      termColsList = results[0];
      termDffList = results[1];
      termColsList = termColsList?.where((element) => element.dISPLAYFLAG == 'Y').toList() ?? [];
      termDffList = termDffList?.where((element) => element.dISPLAYFLAG == 'Y').toList() ?? [];

      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void validateTransaction() {
    String errorMessage = "";
    for (var element in termColsList!) {
      if (element.rEQUIREDFLAG == "Y") {
        if (element.objectValuesList!.isEmpty) {
          if ((element.selectedValue ?? "").isEmpty) {
            errorMessage = element.sEGMENTPROMPT!;
            break;
          }
        } else {
          if (element.selectedObjectValue == null) {
            errorMessage = element.sEGMENTPROMPT!;
            break;
          }
        }
      }
    }
    if (errorMessage.isEmpty) {
      for (var element in termDffList!) {
        if (element.rEQUIREDFLAG == "Y") {
          if (element.eSERVICESDV?.pVALUECOLUMNNAME == null) {
            errorMessage = element.sEGMENTPROMPT!;
            break;
          }
        }
      }
    }
    if (errorMessage.isNotEmpty) {
      Utils.showToast(LocaleKeys.fieldIsEmpty.tr(namedArgs: {'data': errorMessage}));
    } else {
      submitTransaction();
    }
  }

  void submitTransaction() async {
    try {
      Utils.showLoading(context);
      List<Map<String, dynamic>> values = termDffList!.map((e) {
        String tempVar = e.eSERVICESDV?.pIDCOLUMNNAME ?? "";
        if (e.fORMATTYPE == "X") {
          // for date format type, date format is changed
          tempVar = e.eSERVICESDV?.pIDCOLUMNNAME ?? "";
          if (tempVar.isNotEmpty) {
            if (!tempVar.contains("/")) {
              DateTime date = DateFormat('yyyy-MM-dd').parse(tempVar);
              tempVar = DateFormat('yyyy/MM/dd HH:mm:ss').format(date);
            }
          }
        }
        return ValidateEitTransactionModel(dATEVALUE: null, nAME: e.aPPLICATIONCOLUMNNAME, nUMBERVALUE: null, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: tempVar.toString()).toJson();
      }).toList();
      termColsList!.forEach((element) {
        String? value = "";
        ValidateEitTransactionModel model = ValidateEitTransactionModel(nAME: element.aPPLICATIONCOLUMNNAME, nUMBERVALUE: null, tRANSACTIONNUMBER: 1);
        if (element.dATATYPE == "DATE") {
          value = element.selectedValue == null ? null : Utils.formatDate(DateTime.parse(element.selectedValue!).toString());
          model.dATEVALUE = value;
        } else if (element.dATATYPE == "VARCHAR2") {
          if (element.objectValuesList!.isEmpty) {
            value = element.selectedValue;
          } else {
            value = element.selectedObjectValue?.cODE;
          }
          model.vARCHAR2VALUE = value;
        }

        values.add(model.toJson());
      });

      SubmitTermTransactionList submitTermTransaction = await TerminationDffApiClient().submitTermTransaction(dynamicParams!.dynamicId, values);
      Utils.hideLoading(context);
      await Navigator.pushNamed(context, AppRoutes.requestSubmitScreen,
          arguments: RequestSubmitScreenParams(LocaleKeys.submit.tr(), submitTermTransaction.pTRANSACTIONID!, submitTermTransaction.pITEMKEY!, "endEmployment"));
      Utils.showLoading(context);
      await LeaveBalanceApiClient().cancelHrTransaction(submitTermTransaction.pTRANSACTIONID!);
      Utils.hideLoading(context);
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

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

  String dESCFLEXCONTEXTCODE = "";
  String descFlexConTextTitle = "";

  Future calGetValueSetValues(GetTermDffStructureList structureList) async {
    try {
      Utils.showLoading(context);
      String segmentId = structureList.cHILDSEGMENTSVS!;
      if (dESCFLEXCONTEXTCODE.isEmpty) dESCFLEXCONTEXTCODE = structureList.dESCFLEXCONTEXTCODE!;

      List<GetTermDffStructureList> filteredList = termDffList?.where((element) => element.cHILDSEGMENTSVS == segmentId).toList() ?? [];
      List<Map<String, dynamic>> values = filteredList
          .map((e) => GetSetValuesRequestModel(
                  sEGMENTNAME: e.sEGMENTNAME, vALUECOLUMNNAME: e.eSERVICESDV!.pVALUECOLUMNNAME, dESCRIPTION: "", iDCOLUMNNAME: e.eSERVICESDV!.pIDCOLUMNNAME, fLEXVALUESETNAME: e.fLEXVALUESETNAME)
              .toJson())
          .toList();

      List<dff.ESERVICESVS> eServicesResponseModel = await MyAttendanceApiClient().getValueSetValues(segmentId, structureList.dESCFLEXCONTEXTCODE!, structureList.dESCFLEXNAME!, values);
      List<GetTermDffStructureList> abc = termDffList ?? [];
      termDffList = abc;
      int index = termDffList!.indexWhere((element) => element.sEGMENTNAME == structureList.cHILDSEGMENTSVS);
      termDffList![index].eSERVICESVS!.clear();
      if (eServicesResponseModel.isNotEmpty) termDffList![index].eSERVICESVS!.addAll(eServicesResponseModel);
      //   getEitDffStructureList = genericResponseModel?.getEITDFFStructureList ?? [];
      //getEitDffStructureList = getEitDffStructureList!.where((element) => element.dISPLAYFLAG != "N").toList();
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  @override
  Widget build(BuildContext context) {
    if (dynamicParams == null) {
      dynamicParams = ModalRoute.of(context)!.settings.arguments as DynamicListViewParams;
      getTerminationDffStructure();
    }

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(context, title: dynamicParams!.title),
      body: Column(
        children: [
          (termColsList == null && termDffList == null
                  ? const SizedBox()
                  : (((termColsList?.length ?? 0) + (termDffList?.length ?? 0)) < 1
                      ? Utils.getNoDataWidget(context)
                      : ListView(
                          physics: const BouncingScrollPhysics(),
                          padding: const EdgeInsets.all(21),
                          children: [
                            ListView.separated(
                              shrinkWrap: true,
                              physics: const NeverScrollableScrollPhysics(),
                              itemBuilder: (cxt, int index) => termColWidget(termColsList![index]),
                              separatorBuilder: (cxt, index) => 12.height,
                              itemCount: termColsList!.length,
                            ),
                            12.height,
                            ListView.separated(
                              shrinkWrap: true,
                              physics: const NeverScrollableScrollPhysics(),
                              itemBuilder: (cxt, int index) => dffColWidget(termDffList![index], index),
                              separatorBuilder: (cxt, index) => 12.height,
                              itemCount: termDffList!.length,
                            ),
                          ],
                        )))
              .expanded,
          DefaultButton(
            LocaleKeys.next.tr(),
            (((termColsList?.length ?? 0) + (termDffList?.length ?? 0)) < 1)
                ? null
                : () {
                    validateTransaction();
                  },
          ).insideContainer,
        ],
      ),
    );
  }

  Widget termColWidget(GetTermColsStructureList termColObject) {
    if (termColObject.dATATYPE == "VARCHAR2") {
      if (termColObject.objectValuesList!.isEmpty) {
        return DynamicTextFieldWidget(
          (termColObject.sEGMENTPROMPT ?? "") + (termColObject.rEQUIREDFLAG == "Y" ? "*" : ""),
          termColObject.selectedValue ?? "",
          onChange: (text) {
            termColObject.selectedValue = text;
          },
        );
      }
      return PopupMenuButton(
          child: DynamicTextFieldWidget(
            (termColObject.sEGMENTPROMPT ?? "") + (termColObject.rEQUIREDFLAG == "Y" ? "*" : ""),
            termColObject.selectedObjectValue?.mEANING ?? LocaleKeys.pleaseSelect.tr(),
            isEnable: false,
            isPopup: true,
          ).paddingOnly(bottom: 12),
          itemBuilder: (_) => <PopupMenuItem<int>>[
                for (int i = 0; i < termColObject.objectValuesList!.length; i++) PopupMenuItem<int>(value: i, child: Text(termColObject.objectValuesList![i].mEANING ?? "")),
              ],
          onSelected: (int popipIndex) async {
            termColObject.selectedObjectValue = termColObject.objectValuesList![popipIndex];
            print(termColObject.selectedObjectValue?.toJson());
            setState(() {});
          });
    }
    if (termColObject.dATATYPE == "DATE") {
      return DynamicTextFieldWidget(
        (termColObject.sEGMENTPROMPT ?? "") + (termColObject.rEQUIREDFLAG == "Y" ? "*" : ""),
        (termColObject.selectedValue != null) ? Utils.getMonthNamedFormat(DateTime.parse(termColObject.selectedValue!)) : LocaleKeys.pleaseSelectDate.tr(),
        suffixIconData: Icons.calendar_today,
        isEnable: false,
        onTap: () async {
          DateTime? selectedDate;
          if (termColObject.selectedValue == null) {
            selectedDate = DateTime.now();
          } else {
            selectedDate = DateTime.parse(termColObject.selectedValue!);
          }
          DateTime date = await Utils.selectDate(context, selectedDate);
          termColObject.selectedValue = date.toString();
          setState(() {});
        },
      );
    }
    return const SizedBox();
  }

  Widget dffColWidget(GetTermDffStructureList 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 (termDffList![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 ((termDffList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
                if (termDffList![index].isDefaultTypeIsCDPS) {
                  selectedDate = DateFormat("yyyy/MM/dd").parse(termDffList![index].eSERVICESDV!.pVALUECOLUMNNAME!.replaceAll('/"', '').replaceAll(" 00:00:00", ""));
                } else {
                  selectedDate = DateTime.parse(termDffList![index].eSERVICESDV!.pVALUECOLUMNNAME!);
                }
              }
              DateTime date = await _selectDate(context);
              String dateString = date.toString().split(' ').first;
              // DateTime date1 = DateTime(date.year, date.month, date.day);
              // getEitDffStructureList![index].fieldAnswer = date.toString();
              ESERVICESDV eservicesdv;
              if (termDffList![index].isDefaultTypeIsCDPS) {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: Utils.formatDate(dateString),
                    pRETURNMSG: "null",
                    pRETURNSTATUS: termDffList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME: termDffList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              } else {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: dateString,
                    pRETURNMSG: "null",
                    pRETURNSTATUS: termDffList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME: termDffList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              }
              termDffList![index].eSERVICESDV = eservicesdv;
              setState(() {});
              if (model.cHILDSEGMENTSVSSplited?.isNotEmpty ?? false) {
                await calGetValueSetValues(model);
              }
            },
          ).paddingOnly(bottom: 12);
        } else if (model.fORMATTYPE == "Y") {
          String displayText = model.eSERVICESDV?.pIDCOLUMNNAME ?? "";
          // if (termDffList![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 ((termDffList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
                if (termDffList![index].isDefaultTypeIsCDPS) {
                  String tempDate = termDffList![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(termDffList![index].eSERVICESDV!.pVALUECOLUMNNAME!);
                }
              }
              DateTime date = await _selectDate(context);
              String dateString = date.toString().split(' ').first;
              // getEitDffStructureList![index].fieldAnswer = date.toString();
              ESERVICESDV eservicesdv;
              if (termDffList![index].isDefaultTypeIsCDPS) {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: Utils.formatDate(dateString),
                    pRETURNMSG: "null",
                    pRETURNSTATUS: termDffList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME: termDffList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              } else {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: dateString,
                    pRETURNMSG: "null",
                    pRETURNSTATUS: termDffList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME: termDffList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              }

              termDffList![index].eSERVICESDV = eservicesdv;
              setState(() {});
              if (model.cHILDSEGMENTSVSSplited?.isNotEmpty ?? false) {
                await calGetValueSetValues(model);
              }
            },
          ).paddingOnly(bottom: 12);
        }
      } else {
        return PopupMenuButton(
            child: DynamicTextFieldWidget(
              (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
              model.eSERVICESDV?.pVALUECOLUMNNAME ?? LocaleKeys.pleaseSelect.tr(),
              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", //getEitDffStructureList![popipIndex].dEFAULTVALUE,
                  pVALUECOLUMNNAME: model.eSERVICESVS![popipIndex].vALUECOLUMNNAME);
              termDffList![index].eSERVICESDV = eservicesdv;
              setState(() {});
              if (model.cHILDSEGMENTSVSSplited?.isNotEmpty ?? false) {
                await calGetValueSetValues(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);
              termDffList![index].eSERVICESDV = eservicesdv;
              setState(() {});
              if (model.cHILDSEGMENTSVSSplited?.isNotEmpty ?? false) {
                await calGetValueSetValues(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 (termDffList![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 ((termDffList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
            if (termDffList![index].isDefaultTypeIsCDPS) {
              selectedDate = DateFormat("yyyy/MM/dd").parse(termDffList![index].eSERVICESDV!.pVALUECOLUMNNAME!.replaceAll('/"', '').replaceAll(" 00:00:00", ""));
            } else {
              selectedDate = DateTime.parse(termDffList![index].eSERVICESDV!.pVALUECOLUMNNAME!);
            }
          }
          DateTime date = await _selectDate(context);
          String dateString = date.toString().split(' ').first;
          //  termDffList![index].fieldAnswer = date.toString();
          ESERVICESDV eservicesdv = ESERVICESDV(
              pIDCOLUMNNAME: dateString,
              pRETURNMSG: "null",
              pRETURNSTATUS: termDffList![index].dEFAULTVALUE,
              pVALUECOLUMNNAME: termDffList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
          termDffList![index].eSERVICESDV = eservicesdv;
          setState(() {});
          if (model.cHILDSEGMENTSVSSplited?.isNotEmpty ?? false) {
            await calGetValueSetValues(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 ((termDffList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
            var timeString = termDffList![index].eSERVICESDV!.pVALUECOLUMNNAME!.split(":");
            selectedDate = DateTime(0, 0, 0, int.parse(timeString[0]), int.parse(timeString[1]));

            //DateTime.parse(getEitDffStructureList![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);
          //  getEitDffStructureList![index].fieldAnswer = date.toString();
          ESERVICESDV eservicesdv = ESERVICESDV(pIDCOLUMNNAME: time, pRETURNMSG: "null", pRETURNSTATUS: termDffList![index].dEFAULTVALUE, pVALUECOLUMNNAME: time);
          termDffList![index].eSERVICESDV = eservicesdv;
          setState(() {});
          if (model.cHILDSEGMENTSVSSplited?.isNotEmpty ?? false) {
            await calGetValueSetValues(model);
          }
        },
      ).paddingOnly(bottom: 12);
    }

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

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

  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;
  }
}
