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/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/generic_response_model.dart';
import 'package:mohem_flutter_app/models/get_eit_dff_structure_list_model.dart';
import 'package:mohem_flutter_app/models/submit_eit_transaction_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 DynamicInputScreen extends StatefulWidget {
  DynamicInputScreen({Key? key}) : super(key: key);

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

class _DynamicInputScreenState extends State<DynamicInputScreen> {
  GenericResponseModel? genericResponseModel;
  List<GetEITDFFStructureList>? getEitDffStructureList;
  DynamicListViewParams? dynamicParams;

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

  void getTransactionsStructure() async {
    try {
      Utils.showLoading(context);
      genericResponseModel = await MyAttendanceApiClient().getEitDffStructure(dynamicParams!.dynamicId);
      dESCFLEXCONTEXTCODE = genericResponseModel!.pDESCFLEXCONTEXTCODE ?? "";
      descFlexConTextTitle = genericResponseModel!.pDESCFLEXCONTEXTNAME ?? "";
      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);
    }
  }

  void validateTransaction() async {
    try {
      Utils.showLoading(context);
      List<Map<String, dynamic>> values = getEitDffStructureList!.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);
            }
          }
        }
        // else if (e.fORMATTYPE == "N") {
        //   // for date format type, date format is changed
        //   tempVar = e.eSERVICESDV?.pIDCOLUMNNAME ?? "";
        //   print("------------------------sEGMENTNAME:${e.sEGMENTNAME}");
        //   print("------------------------tempVar:$tempVar");
        //   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();

      values.add(ValidateEitTransactionModel(dATEVALUE: null, nAME: "PEI_ACTION", nUMBERVALUE: null, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: "NEW_ROW").toJson());
      values.add(ValidateEitTransactionModel(dATEVALUE: null, nAME: "PEI_EXTRA_INFO_ID", nUMBERVALUE: -1, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: null).toJson());
      values.add(ValidateEitTransactionModel(dATEVALUE: null, nAME: "PEI_OBJECT_VERSION_NUMBER", nUMBERVALUE: 0, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: null).toJson());

      genericResponseModel = await MyAttendanceApiClient().validateEitTransaction(dESCFLEXCONTEXTCODE, dynamicParams!.dynamicId, values);
      SubmitEITTransactionList submitEITTransactionList = await MyAttendanceApiClient().submitEitTransaction(dESCFLEXCONTEXTCODE, dynamicParams!.dynamicId, values);
      Utils.hideLoading(context);
      await Navigator.pushNamed(context, AppRoutes.requestSubmitScreen,
          arguments: RequestSubmitScreenParams(LocaleKeys.submit.tr(), submitEITTransactionList.pTRANSACTIONID!, submitEITTransactionList.pITEMKEY!, 'eit'));
      Utils.showLoading(context);
      await LeaveBalanceApiClient().cancelHrTransaction(submitEITTransactionList.pTRANSACTIONID!);
      Utils.hideLoading(context);
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

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

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

      List<GetEITDFFStructureList> filteredList = getEitDffStructureList?.where((element) => element.cHILDSEGMENTSVSSplited!.contains(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<ESERVICESVS> eServicesResponseModel = await MyAttendanceApiClient().getValueSetValues(segmentId, structureList.dESCFLEXCONTEXTCODE!, structureList.dESCFLEXNAME!, values);
      List<GetEITDFFStructureList> abc = genericResponseModel?.getEITDFFStructureList ?? [];
      getEitDffStructureList = abc;
      int index = getEitDffStructureList!.indexWhere((element) => element.sEGMENTNAME == structureList.cHILDSEGMENTSVS);
      getEitDffStructureList![index].eSERVICESVS!.clear();
      if (eServicesResponseModel.isNotEmpty) getEitDffStructureList![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);
    }
  }

  Future getDefaultValues(GetEITDFFStructureList structureList) async {
    try {
      Utils.showLoading(context);
      for (int i = 0; i < (structureList.cHILDSEGMENTSDVSplited?.length ?? 0); i++) {
        String segmentId = structureList.cHILDSEGMENTSDVSplited![i];
        GetEITDFFStructureList? parent = getEitDffStructureList!.firstWhere((element) => element.sEGMENTNAME == segmentId);
        List<PARENTSEGMENTSDVSplited> parentDvRequired = parent.pARENTSEGMENTSDVSplited ?? [];
        List<PARENTSEGMENTSVSSplitedVS> parentVsRequired = parent.pARENTSEGMENTSVSSplitedVS ?? [];

        List<GetEITDFFStructureList> filteredList =
            getEitDffStructureList!.where((outerElement) => parentDvRequired.any((element) => outerElement.sEGMENTNAME == element.name && element.isRequired == "REQUIRED")).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<Map<String, dynamic>> getSetList = getDefaultValuesIonicLogic(parent);
        if (getSetList.isNotEmpty) {
          ESERVICESDV defaultValue = await MyAttendanceApiClient().getDefaultValue(segmentId, structureList.dESCFLEXCONTEXTCODE!, structureList.dESCFLEXNAME!, getSetList);
          int index = getEitDffStructureList!.indexWhere((element) => element.sEGMENTNAME == segmentId);
          getEitDffStructureList![index].eSERVICESDV = defaultValue;
        }
      }
      await Future.delayed(const Duration(seconds: 1));
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  // List<Map<String, dynamic>> calGetValueSetValuesIonicLogic(GetEITDFFStructureList structureElement) {
  //   let descFlexName: any = "";
  //   let descFlexContextCode: any = "";
  //   let parentValue: any = [];
  //   let ParentsList: any = [];
  //   let parentVal: any = null;
  //   let dependenciesList: any = [];
  //   let validationType: string = "";
  // }

  List<Map<String, dynamic>> getDefaultValuesIonicLogic(GetEITDFFStructureList structureElement) {
    try {
      List<PARENTSEGMENTSVSSplitedVS> parentValue = structureElement.pARENTSEGMENTSVSSplitedVS ?? [];
      List<PARENTSEGMENTSDVSplited> parentsList = structureElement.pARENTSEGMENTSDVSplited ?? [];

      List<Map<String, dynamic>> dependenciesList = [];
      String? parentVal;
      bool isStandardDate = false;
      bool isStandardTimeDate = false;
      bool isStandardTime = false;
      bool isHidden = false;
      bool isReadOnlyList = false;
      bool isSelectElement = false;

      // isStandardDate = this.isStandardDate(obj);
      // isStandardTimeDate = this.isStandardDateTime(obj);
      // isStandardTime = this.isStandardTime(obj);
      if (structureElement.dISPLAYFLAG == "N") isHidden = true;
      if (structureElement.vALIDATIONTYPE != "N" && structureElement.rEADONLY == "Y") {
        isReadOnlyList = true;
      }
      if (structureElement.vALIDATIONTYPE != "N" && structureElement.rEADONLY == "N") {
        isSelectElement = true;
      }

      if (parentValue.isNotEmpty && (structureElement.vALIDATIONTYPE == "D" || structureElement.vALIDATIONTYPE == "Y")) {
        List parValue = getDependenciesParams(parentValue);

        if (parValue.isNotEmpty) {
          parentVal = parValue.first.ID_COLUMN_NAME;
        }

        if (parentVal == null) {
          return [];
        }
      }
      if (parentsList.isNotEmpty) {
        if (parentValue.isNotEmpty) {
          parentsList = parentsList + parentValue.map((e) => PARENTSEGMENTSDVSplited.fromJson(e.toJson())).toList();
          //  parentsList.addAll(parentValue.map((e) => PARENTSEGMENTSDVSplited.fromJson(e.toJson())));
          // parentsList.concat(parentValue);
        }
        dependenciesList = getDependenciesParams(parentsList);
      }
      return dependenciesList;
      // for (int i = 0; i < (structureList.cHILDSEGMENTSDVSplited?.length ?? 0); i++) {
      //   String segmentId = structureList.cHILDSEGMENTSDVSplited![i];
      //   print("segmentId:$segmentId");
      //   print("segmentName:${structureList.sEGMENTNAME}");
      //   GetEITDFFStructureList? parent = getEitDffStructureList!.firstWhere((element) => element.sEGMENTNAME == segmentId);
      //   List<PARENTSEGMENTSDVSplited> parentDvRequired = parent.pARENTSEGMENTSDVSplited ?? [];
      //   List<PARENTSEGMENTSVSSplitedVS> parentVsRequired = parent.pARENTSEGMENTSVSSplitedVS ?? [];
      //
      //   List<GetEITDFFStructureList> filteredList =
      //       getEitDffStructureList!.where((outerElement) => parentDvRequired.any((element) => outerElement.sEGMENTNAME == element.name && element.isRequired == "REQUIRED")).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();
      //   print("values:$values");
      //
      //   ESERVICESDV defaultValue = await MyAttendanceApiClient().getDefaultValue(segmentId, structureList.dESCFLEXCONTEXTCODE!, structureList.dESCFLEXNAME!, values);
      //   int index = getEitDffStructureList!.indexWhere((element) => element.sEGMENTNAME == segmentId);
      //   getEitDffStructureList![index].eSERVICESDV = defaultValue;
      // }
      //   Utils.hideLoading(context);
      //   setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
      return [];
    }
  }

  List<Map<String, dynamic>> getDependenciesParams(parentsList) {
    List<Map<String, dynamic>> parentArr = [];

    for (int i = 0; i < parentsList.length; i++) {
      for (int j = 0; j < (getEitDffStructureList?.length ?? 0); j++) {
        if (getEitDffStructureList![j].sEGMENTNAME == parentsList[i].opt1) {
          if (getEitDffStructureList![j].dISPLAYFLAG != "N") {
            if (getEitDffStructureList![j].vALIDATIONTYPE == "N") {
              String? idColName;
              String? val;
              if (getEitDffStructureList![j].fORMATTYPE == "Y" || getEitDffStructureList![j].fORMATTYPE == "I") {
                //standard date time or //time
                val = getEitDffStructureList![j].eSERVICESDV?.pVALUECOLUMNNAME;
                //  val = getEitDffStructureList![j].eSERVICESDV?.pVALUECOLUMNNAME;
                //  var elem = document.getElementById(getEitDffStructureList![j].aPPLICATIONCOLUMNNAME) as HTMLDivElement;

                if ((val ?? "").isEmpty && parentsList[i].isRequired == "REQUIRED") {
                  //alert(parentsList[i].Name +" Is required");
                  return [];
                  //   return false;
                }
                idColName = val;
                if (getEitDffStructureList![j].fORMATTYPE == "Y") {
                  // if (idColName!.contains("/")) {
                  //   DateTime date = DateFormat('yyyy/MM/dd').parse(idColName);
                  //   idColName = DateFormat('yyyy/MM/dd HH:mm:ss').format(DateTime(date.year, date.month, date.day));
                  // } else {
                  //   DateTime date = DateFormat('yyyy-MM-dd').parse(idColName);
                  //   idColName = DateFormat('yyyy/MM/dd HH:mm:ss').format(DateTime(date.year, date.month, date.day));
                  // }

                  idColName = Utils.formatStandardDate(idColName!);
                }
              } else {
                val = getEitDffStructureList![j].eSERVICESDV?.pVALUECOLUMNNAME;
                //   val = (document.getElementById(getEitDffStructureList![j].aPPLICATIONCOLUMNNAME) as HTMLInputElement).value;
                if ((val ?? "").isEmpty && parentsList[i].isRequired == "REQUIRED") {
                  //alert(parentsList[i].Name +" Is required");
                  return [];
                }
                idColName = val;

                if (getEitDffStructureList![j].fORMATTYPE == "X") {
                  idColName = Utils.formatDateNew(idColName!);
                  // commenting to test
                  // DateTime date = DateFormat('yyyy-MM-dd').parse(idColName!);
                  // idColName = DateFormat('yyyy-MM-dd HH:mm:ss').format(date);
                }
              }

              parentArr.add(GetSetValuesRequestModel(
                sEGMENTNAME: getEitDffStructureList![j].sEGMENTNAME,
                vALUECOLUMNNAME: val,
                dESCRIPTION: "",
                iDCOLUMNNAME: idColName,
                fLEXVALUESETNAME: getEitDffStructureList![j].fLEXVALUESETNAME,
              ).toJson());
              break;
            } else {
              if (getEitDffStructureList![j].rEADONLY != "Y") {
                var data = getEitDffStructureList![j].eSERVICESDV;

                //           let x = document.getElementById(getEitDffStructureList![j].aPPLICATIONCOLUMNNAME) as HTMLSelectElement;
                String? text = data?.pIDCOLUMNNAME; //x.options[x.selectedIndex] ? x.options[x.selectedIndex].text : "";
                String? val = data?.pVALUECOLUMNNAME; //x.options[x.selectedIndex] ? x.options[x.selectedIndex].value : null;
                if ((val ?? "").isEmpty && parentsList[i].isRequired == "REQUIRED") {
                  //alert(parentsList[i].Name +" Is required");
                  return [];
                } else {}

                text ??= "";

                parentArr.add(GetSetValuesRequestModel(
                  sEGMENTNAME: getEitDffStructureList![j].sEGMENTNAME,
                  vALUECOLUMNNAME: val,
                  dESCRIPTION: "",
                  iDCOLUMNNAME: text,
                  fLEXVALUESETNAME: getEitDffStructureList![j].fLEXVALUESETNAME,
                ).toJson());
                break;
              } else {
                var data = getEitDffStructureList![j].eSERVICESDV;

                String? text = data?.pVALUECOLUMNNAME;
                String? val = data?.pIDCOLUMNNAME;
                if ((val ?? "").isEmpty && parentsList[i].IsRequired == "REQUIRED") {
                  //alert(parentsList[i].Name +" Is required");
                  return [];
                } else {}
                text ??= "";

                parentArr.add(GetSetValuesRequestModel(
                  sEGMENTNAME: getEitDffStructureList![j].sEGMENTNAME,
                  vALUECOLUMNNAME: text,
                  dESCRIPTION: "",
                  iDCOLUMNNAME: val,
                  fLEXVALUESETNAME: getEitDffStructureList![j].fLEXVALUESETNAME,
                ).toJson());

                //break;
              }
            }
          } else {
            var data = getEitDffStructureList![j].eSERVICESDV;

            String? text = data?.pVALUECOLUMNNAME;
            String? val = data?.pIDCOLUMNNAME;
            if ((val ?? "").isEmpty && parentsList[i].IsRequired == "REQUIRED") {
              //alert(parentsList[i].Name +" Is required");
              return [];
            } else {}
            text ??= "";

            parentArr.add(GetSetValuesRequestModel(
              sEGMENTNAME: getEitDffStructureList![j].sEGMENTNAME,
              vALUECOLUMNNAME: text,
              dESCRIPTION: "",
              iDCOLUMNNAME: val,
              fLEXVALUESETNAME: getEitDffStructureList![j].fLEXVALUESETNAME,
            ).toJson());
            // break;
          }
        }
      }
    }
    return parentArr;
  }

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

  @override
  Widget build(BuildContext context) {
    if (dynamicParams == null) {
      dynamicParams = ModalRoute.of(context)!.settings.arguments as DynamicListViewParams;
      getTransactionsStructure();
    }
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(
        context,
        title: dynamicParams!.title,
      ),
      body: Column(
        children: [
          (getEitDffStructureList == null
                  ? const SizedBox()
                  : (getEitDffStructureList!.isEmpty
                      ? Utils.getNoDataWidget(context)
                      : ListView.separated(
                          physics: const BouncingScrollPhysics(),
                          padding: const EdgeInsets.all(21),
                          itemBuilder: (cxt, int parentIndex) => parseDynamicFormatType(getEitDffStructureList![parentIndex], parentIndex),
                          separatorBuilder: (cxt, index) => 0.height,
                          itemCount: getEitDffStructureList!.length,
                        )))
              .expanded,
          // 12.height,
          DefaultButton(
            LocaleKeys.next.tr(),
            (getEitDffStructureList ?? []).isEmpty
                ? null
                : () {
                    validateTransaction();

                    //Navigator.of(context).pushNamed(LOGIN_TYPE)
                  },
          ).insideContainer,
        ],
      ),
    );
  }

  Widget parseDynamicFormatType(GetEITDFFStructureList 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.fieldAnswer = 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.fieldAnswer = text;
              model.eSERVICESDV ??= ESERVICESDV();
              model.eSERVICESDV!.pIDCOLUMNNAME = text;
            },
          ).paddingOnly(bottom: 12);
        } else if (model.fORMATTYPE == "X") {
          String displayText = model.eSERVICESDV?.pIDCOLUMNNAME ?? (getEitDffStructureList![index].fieldAnswer ?? "");

          if (getEitDffStructureList![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 ((getEitDffStructureList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
                if (getEitDffStructureList![index].isDefaultTypeIsCDPS) {
                  selectedDate = DateFormat("yyyy/MM/dd").parse(getEitDffStructureList![index].eSERVICESDV!.pVALUECOLUMNNAME!.replaceAll('/"', '').replaceAll(" 00:00:00", ""));
                } else {
                  selectedDate = DateTime.parse(getEitDffStructureList![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 (getEitDffStructureList![index].isDefaultTypeIsCDPS) {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: Utils.formatDate(dateString),
                    pRETURNMSG: "null",
                    pRETURNSTATUS: getEitDffStructureList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME:
                        getEitDffStructureList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              } else {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: dateString,
                    pRETURNMSG: "null",
                    pRETURNSTATUS: getEitDffStructureList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME:
                        getEitDffStructureList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              }
              getEitDffStructureList![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 ?? (getEitDffStructureList![index].fieldAnswer ?? "");
          if (getEitDffStructureList![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 ((getEitDffStructureList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
                if (getEitDffStructureList![index].isDefaultTypeIsCDPS) {
                  String tempDate = getEitDffStructureList![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(getEitDffStructureList![index].eSERVICESDV!.pVALUECOLUMNNAME!);
                }
              }
              DateTime date = await _selectDate(context);
              String dateString = date.toString().split(' ').first;
              // getEitDffStructureList![index].fieldAnswer = date.toString();
              ESERVICESDV eservicesdv;
              if (getEitDffStructureList![index].isDefaultTypeIsCDPS) {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: Utils.formatDate(dateString),
                    pRETURNMSG: "null",
                    pRETURNSTATUS: getEitDffStructureList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME:
                        getEitDffStructureList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              } else {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: dateString,
                    pRETURNMSG: "null",
                    pRETURNSTATUS: getEitDffStructureList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME:
                        getEitDffStructureList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              }

              getEitDffStructureList![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", //getEitDffStructureList![popipIndex].dEFAULTVALUE,
                  pVALUECOLUMNNAME: model.eSERVICESVS![popipIndex].vALUECOLUMNNAME);
              getEitDffStructureList![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);
              getEitDffStructureList![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 ?? (getEitDffStructureList![index].fieldAnswer ?? "");
      if (getEitDffStructureList![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 ((getEitDffStructureList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
            if (getEitDffStructureList![index].isDefaultTypeIsCDPS) {
              selectedDate = DateFormat("yyyy/MM/dd").parse(getEitDffStructureList![index].eSERVICESDV!.pVALUECOLUMNNAME!.replaceAll('/"', '').replaceAll(" 00:00:00", ""));
            } else {
              selectedDate = DateTime.parse(getEitDffStructureList![index].eSERVICESDV!.pVALUECOLUMNNAME!);
            }
          }
          DateTime date = await _selectDate(context);
          String dateString = date.toString().split(' ').first;
          getEitDffStructureList![index].fieldAnswer = date.toString();
          ESERVICESDV eservicesdv = ESERVICESDV(
              pIDCOLUMNNAME: dateString,
              pRETURNMSG: "null",
              pRETURNSTATUS: getEitDffStructureList![index].dEFAULTVALUE,
              pVALUECOLUMNNAME: getEitDffStructureList![index].isDefaultTypeIsCDPS ? Utils.reverseFormatStandardDate(Utils.formatDate(dateString)) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
          getEitDffStructureList![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 ?? (getEitDffStructureList![index].fieldAnswer ?? ""),
        suffixIconData: Icons.access_time_filled_rounded,
        isEnable: false,
        onTap: () async {
          if ((getEitDffStructureList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
            var timeString = getEitDffStructureList![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: getEitDffStructureList![index].dEFAULTVALUE, pVALUECOLUMNNAME: time);
          getEitDffStructureList![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();
  }

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