import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/validator/validator.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/helper/utils.dart';
import 'package:test_sa/models/device/asset.dart';
import 'package:test_sa/models/generic_attachment_model.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/new_models/building.dart';
import 'package:test_sa/models/new_models/floor.dart';
import 'package:test_sa/models/new_models/site.dart';
import 'package:test_sa/models/wo_by_asset_id_model.dart';
import 'package:test_sa/modules/cm_module/cm_request_utils.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/incident_module/incident_lookup_provider.dart';
import 'package:test_sa/modules/incident_module/incident_provider.dart';
import 'package:test_sa/modules/loan_module/models/medical_department_model.dart';
import 'package:test_sa/modules/loan_module/provider/medical_department_provider.dart';
import 'package:test_sa/modules/traf_module/asset_auto_complete_field.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/providers/gas_request_providers/site_provider.dart';
import 'package:test_sa/views/widgets/date_and_time/time_picker.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';
import 'package:test_sa/providers/lookups/yes_no_lookup_provider.dart';
import 'package:test_sa/views/widgets/auto_complete/wo_auto_complete_field.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';
import 'package:test_sa/views/widgets/equipment/asset_picker.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';

import '../../models/new_models/department.dart';
import '../../new_views/swipe_module/dialoge/info_dialog.dart';
import 'flow_medical_department_provider.dart';

class CreateIncidentRequestPage extends StatefulWidget {
  static const String id = "/create-incident";

  CreateIncidentRequestPage({Key? key}) : super(key: key);

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

class _CreateIncidentRequestPageState extends State<CreateIncidentRequestPage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  List<GenericAttachmentModel> attachments = [];

  MedicalDepartmentModel? _medicalDepartmentModel;
  Site? _empSite;
  Site? _selectedSite;
  Building? _selectedBuilding;
  Floor? _selectedFloor;
  Department? _selectedDepartment;

  Asset? device;
  WoByAssetIdModel? woByAssetId;

  Lookup? incidentType;
  Lookup? ovrSystem;
  Lookup? rootCause;
  Lookup? involvedPerson;
  Lookup? gender;
  DateTime? occurrenceDate;

  Map<String, dynamic> payload = {};

  Map<String, dynamic>? ovrDetails;

  bool get isOvrVerified => ovrDetails != null;

  bool ovrVerifying = false;
  String ovrTicketNumber = "";

  TextEditingController ovrTicketController = TextEditingController();

  @override
  void initState() {
    super.initState();
    ovrSystem = Lookup(id: 81, name: "No", value: 0);
    payload["id"] = 0;
    payload["isFromMobile"] = true;
    payload["requestorUserId"] = context.userProvider.user!.userID;
    payload["requestorSiteId"] = context.userProvider.user!.clientId;
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: 'Incident'.addTranslation),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  ...empSiteSection(),
                  16.height,
                  ...incidentInfoSection(),
                  if (incidentType?.value == 1) ...[
                    16.height,
                    "Asset Details".bodyText(context).custom(color: AppColor.textStyleColor(context)),
                    8.height,
                    AssetPicker(
                      device: device,
                      overWriteStyle: true,
                      showLoading: false,
                      borderColor: AppColor.black20,
                      showBorder: true,
                      onPick: (asset) async {
                        device = asset;
                        payload["assetId"] = asset?.id;
                        payload["oracleCode"] = (asset.modelDefinition?.oracleCodes?.isNotEmpty ?? false) ? asset.modelDefinition?.oracleCodes?.first.codeValue : null;
                        payload["model"] = asset.modelDefinition?.modelName;
                        payload["manufacturer"] = asset.modelDefinition?.manufacturerName;
                        payload["assetOrigin"] = asset.modelDefinition?.assetName;
                        payload["siteId"] = asset.site?.id;
                        payload["buildingId"] = asset.building?.id;
                        payload["floorId"] = asset.floor?.id;
                        payload["departmentId"] = asset.department?.id;
                        setState(() {});
                      },
                    ),
                    12.height,
                    WoAutoCompleteField(
                      clearAfterPick: false,
                      byName: true,
                      enabled: device != null,
                      assetId: device?.id?.toInt(),
                      initialValue: "",
                      onPick: (asset) {
                        woByAssetId = asset;
                        setState(() {});
                      },
                    ),
                  ],
                  if (incidentType?.value != null && incidentType?.value != 1) ...[
                    16.height,
                    ...siteSection(),
                  ],
                  16.height,
                  ...detailsSection(),
                  16.height,
                  ...optionQuestions(),
                  16.height,
                  "Attachments".bodyText(context).custom(color: AppColor.textStyleColor(context)),
                  8.height,
                  AttachmentPicker(
                    label: context.translation.attachments,
                    attachment: attachments,
                    buttonColor: AppColor.black10,
                    onlyImages: false,
                    showAsListView: true,
                    buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10),
                    onChange: (_attachments) {
                      attachments = _attachments;
                      setState(() {});
                    },
                  ),
                ],
              ).toShadowContainer(context, borderRadius: 20),
            ).expanded,
            FooterActionButton.footerContainer(
              context: context,
              child: AppFilledButton(
                buttonColor: AppColor.primary10,
                label: context.translation.submitRequest,
                onPressed: _submit,
                // buttonColor: AppColor.primary10,
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<Widget> optionQuestions() {
    return [
      'Additional Information & Comments'.addTranslation.bodyText(context).custom(color: AppColor.textStyleColor(context)),
      8.height,
      AppTextFormField(
        initialValue: "",
        labelText: "Some Comments",
        style: TextStyle(fontWeight: FontWeight.w500, fontSize: context.isTablet() ? 16 : 12, color: context.isDark ? Colors.white : const Color(0xff3B3D4A)),
        labelStyle: TextStyle(fontWeight: FontWeight.w500, fontSize: context.isTablet() ? 16 : 12, color: context.isDark ? Colors.white : const Color(0xff767676)),
        floatingLabelStyle: TextStyle(fontWeight: FontWeight.w500, fontSize: context.isTablet() ? 16 : 12, color: context.isDark ? Colors.white : const Color(0xff3B3D4A)),
        backgroundColor: AppColor.fieldBgColor(context),
        showShadow: false,
        textInputType: TextInputType.multiline,
        makeMultiLinesNull: false,
        onChange: (value) {
          payload["comments"] = value;
        },
      ),
    ];
  }

  List<Widget> siteSection() {
    return [
      'Site Details'.addTranslation.bodyText(context).custom(color: AppColor.textStyleColor(context)),
      8.height,
      SingleItemDropDownMenu<Site, SiteProvider>(
        context: context,
        title: context.translation.site,
        initialValue: _selectedSite,
        showShadow: false,
        validator: (value) {
          if (value == null) return "Please select a site";
          return null;
        },
        backgroundColor: AppColor.fieldBgColor(context),
        showAsBottomSheet: true,
        onSelect: (value) {
          _selectedSite = value;
          payload["siteId"] = value?.id;
          setState(() {});
        },
      ),
      8.height,
      SingleItemDropDownMenu<Building, NullableLoadingProvider>(
        context: context,
        title: context.translation.building,
        initialValue: _selectedBuilding,
        showShadow: false,
        showAsBottomSheet: true,
        validator: (value) {
          if (value == null) return "Please select a building";
          return null;
        },
        backgroundColor: AppColor.fieldBgColor(context),
        enabled: _selectedSite?.buildings?.isNotEmpty ?? false,
        staticData: _selectedSite?.buildings ?? [],
        onSelect: (value) {
          _selectedBuilding = value;
          _selectedFloor = null;
          _selectedDepartment = null;
          payload["buildingId"] = value?.id;
          setState(() {});
        },
      ),
      8.height,
      SingleItemDropDownMenu<Floor, NullableLoadingProvider>(
        context: context,
        title: context.translation.floor,
        showShadow: false,
        showAsBottomSheet: true,
        initialValue: _selectedFloor,
        backgroundColor: AppColor.fieldBgColor(context),
        enabled: _selectedBuilding?.floors?.isNotEmpty ?? false,
        staticData: _selectedBuilding?.floors ?? [],
        validator: (value) {
          if (value == null) return "Please select a floor";
          return null;
        },
        onSelect: (value) {
          _selectedFloor = value;
          _selectedDepartment = null;
          payload["floorId"] = value?.id;
          setState(() {});
        },
      ),
      8.height,
      SingleItemDropDownMenu<Department, NullableLoadingProvider>(
        context: context,
        title: context.translation.department,
        showShadow: false,
        showAsBottomSheet: true,
        initialValue: _selectedDepartment,
        backgroundColor: AppColor.fieldBgColor(context),
        enabled: _selectedFloor?.departments?.isNotEmpty ?? false,
        staticData: _selectedFloor?.departments ?? [],
        validator: (value) {
          if (value == null) return "Please select a department";
          return null;
        },
        onSelect: (value) {
          _selectedDepartment = value;
          payload["departmentId"] = value?.id;
          setState(() {});
        },
      ),
    ];
  }

  List<Widget> empSiteSection() {
    return [
      SingleItemDropDownMenu<Site, SiteProvider>(
        context: context,
        title: "Employee Site",
        initialValue: _empSite,
        showShadow: false,
        validator: (value) {
          if (value == null) return "Please select a site";
          return null;
        },
        backgroundColor: AppColor.fieldBgColor(context),
        showAsBottomSheet: true,
        onSelect: (value) {
          _empSite = value;
          payload["requestorSiteId"] = value?.id;
          setState(() {});
        },
      ),
      8.height,
      SingleItemDropDownMenu<MedicalDepartmentModel, FlowMedicalDepartmentProvider>(
        context: context,
        title: "Employee Department",
        showShadow: false,
        validator: (value) {
          if (value == null) return "Please select a department";
          return null;
        },
        showAsBottomSheet: true,
        initialValue: _medicalDepartmentModel,
        requestById: context.userProvider.user?.clientId,
        backgroundColor: AppColor.fieldBgColor(context),
        onSelect: (value) {
          _medicalDepartmentModel = value;
          payload["requestorFlowDepartmentId"] = value?.id;
          setState(() {});
        },
      ),
    ];
  }

  List<Widget> incidentInfoSection() {
    return [
      "Incident Details".bodyText(context).custom(color: AppColor.textStyleColor(context)),
      8.height,
      SingleItemDropDownMenu<Lookup, IncidentTypeLookupProvider>(
        context: context,
        height: 56.toScreenHeight,
        title: "Incident Type",
        initialValue: incidentType,
        showShadow: false,
        validator: (value) {
          if (value == null) return "Mandatory";
          return null;
        },
        infoCallback: () {
          context.showInfoDialog("Select the category that best describes the incident:", content: [
            InfoContent(title: "Medical Equipment", message: "Malfunction, failure, or issue involving a device."),
            InfoContent(title: "EHS (Environment, Health, Safety)", message: "Incidents related to safety hazards, spills, injuries."),
            InfoContent(title: "Late Delivery", message: "Delayed receipt of medical equipment, materials, or supplies."),
            InfoContent(title: "Mis-conduct", message: "FLOW staff behavior that violates rules, ethics, or procedures."),
          ]);
        },
        backgroundColor: AppColor.fieldBgColor(context),
        showAsBottomSheet: true,
        onSelect: (value) {
          incidentType = value;
          payload["incidentClassificationId"] = value?.id;
          payload["workOrderId"] = null;
          setState(() {});
        },
      ),
      8.height,
      SingleItemDropDownMenu<Lookup, YesNoLookupProvider>(
        context: context,
        height: 56.toScreenHeight,
        title: "Is there any existing OVR System?",
        initialValue: ovrSystem,
        showShadow: false,
        validator: (value) {
          if (value == null) return "Mandatory";
          return null;
        },
        backgroundColor: AppColor.fieldBgColor(context),
        showAsBottomSheet: true,
        onSelect: (value) {
          ovrSystem = value;
          payload["existingOvrTicketId"] = value?.id;
          setState(() {});
        },
      ),
      if (ovrSystem?.value == 1) ...[
        8.height,
        AppTextFormField(
          initialValue: "",
          controller: ovrTicketController,
          labelText: "OVR Ticket Number",
          validator: (value) {
            if ((value ?? "").isEmpty) return "Mandatory";
            return null;
          },
          style: Theme.of(context).textTheme.titleMedium,
          backgroundColor: AppColor.fieldBgColor(context),
          labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
          showShadow: false,
          suffixIcon: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextButton(
                onPressed: () {
                  if (ovrVerifying || isOvrVerified) return;
                  if (ovrTicketNumber.isEmpty) {
                    "Please enter OVR ticket number".showToast;
                    return;
                  }
                  ovrVerifying = true;
                  setState(() {});
                  context.read<IncidentProvider>().getOvrTicketDetails(ovrTicketNumber).then((details) {
                    ovrDetails = details;
                    if (ovrDetails != null) {
                      payload["ovrTicketNumber"] = ovrTicketNumber;
                      "OVR Ticket verified successfully".showToast;
                    }
                  }).whenComplete(() {
                    ovrVerifying = false;
                    setState(() {});
                  });
                },
                child: ovrVerifying
                    ? SizedBox(
                        width: 16.toScreenHeight,
                        height: 16.toScreenHeight,
                        child: CircularProgressIndicator(color: AppColor.loadingColor(context), strokeWidth: 2),
                      )
                    : isOvrVerified
                        ? const Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [Icon(Icons.done), Text("Verified")],
                          )
                        : const Text("Verify"),
              ),
              if (isOvrVerified)
                const Icon(Icons.clear, color: AppColor.red30).paddingOnly(end: 8).onPress(() {
                  ovrDetails = null;
                  ovrTicketNumber = "";
                  ovrTicketController.clear();
                  payload.remove("ovrTicketNumber");
                  setState(() {});
                }),
            ],
          ),
          textInputType: TextInputType.name,
          textInputAction: TextInputAction.next,
          onChange: (value) {
            ovrTicketNumber = value;
          },
        ),
      ],
      8.height,
      AppTextFormField(
        initialValue: "",
        labelText: "Incident Title",
        validator: (value) {
          if ((value ?? "").isEmpty) return "Mandatory";
          return null;
        },
        suffixIcon: Icon(Icons.info_outline_rounded, color: AppColor.icon2Color(context)).paddingOnly(end: 8).onPress(() {
          context.showInfoDialog("Brief explanation of the incident, e.g., “Damaged patient monitor screen“");
        }),
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.name,
        textInputAction: TextInputAction.next,
        onChange: (value) {
          payload["incidentTitle"] = value;
        },
      ),
      8.height,
      AppTextFormField(
        initialValue: "",
        labelText: "Incident Description",
        validator: (value) {
          if ((value ?? "").isEmpty) return "Mandatory";
          return null;
        },
        suffixIcon: Icon(Icons.info_outline_rounded, color: AppColor.icon2Color(context)).paddingOnly(end: 8).onPress(() {
          context.showInfoDialog(
              "Provide a clear and factual description of the incident, including how the issue was identified. Ex. “The ECG cable connector was damaged due to continuos forcfull disconnetionnby end-users. Multiple bent pins were noted during inspection after repeated complains of poor signal quality“");
        }),
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.name,
        textInputAction: TextInputAction.next,
        onChange: (value) {
          payload["incidentDescription"] = value;
        },
      ),
    ];
  }

  List<Widget> detailsSection() {
    return [
      'Details'.addTranslation.bodyText(context).custom(color: AppColor.textStyleColor(context)),
      8.height,
      SingleItemDropDownMenu<Lookup, IncidentRootCauseLookupProvider>(
        context: context,
        height: 56.toScreenHeight,
        title: "Root Cause",
        initialValue: rootCause,
        showShadow: false,
        validator: (value) {
          if (value == null) return "Mandatory";
          return null;
        },
        infoCallback: () {
          context.showInfoDialog("Select the primary cause that best explains why the incident occurred. If “Other“ is selected, specify the details in the text box provided.", content: [
            InfoContent(
                title: "Misuse",
                message: "Clear, improper use of the device by the end-user despite available knowledge or instructions. Misuse implies that correct handling was possible but not followed."),
            InfoContent(title: "Lack of Awareness", message: "End-user was unaware of proper handling or procedures due to missing information or communication."),
            InfoContent(title: "Insufficient Training", message: "Formal training on the device was not provided, incomplete, or outdated, leading to misuse."),
            InfoContent(
                title: "Utility Failure",
                message: "A utility issue that disrupted the medical device operation, degrade, performance, or create unsafe conditions. such as (power outage, HVAC, or environment)."),
            InfoContent(title: "Other", message: "Any cause that does not fit into the categories above (please specify)."),
          ]);
        },
        backgroundColor: AppColor.fieldBgColor(context),
        showAsBottomSheet: true,
        onSelect: (value) {
          rootCause = value;
          payload["rootCauseId"] = value?.id;
          setState(() {});
        },
      ),
      if (rootCause?.value == 5) ...[
        8.height,
        AppTextFormField(
          initialValue: "",
          labelText: "Root Cause (Other)",
          validator: (value) {
            if ((value ?? "").isEmpty) return "Mandatory";
            return null;
          },
          style: Theme.of(context).textTheme.titleMedium,
          // backgroundColor: AppColor.fieldBgColor(context),
          labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
          showShadow: false,
          textInputType: TextInputType.name,
          textInputAction: TextInputAction.next,
          onChange: (value) {
            payload["otherRootCause"] = value;
          },
        ),
      ],
      8.height,
      SingleItemDropDownMenu<Lookup, IncidentPersonInvolvedLookupProvider>(
        context: context,
        height: 56.toScreenHeight,
        title: "Person Involved",
        initialValue: involvedPerson,
        showShadow: false,
        validator: (value) {
          if (value == null) return "Mandatory";
          return null;
        },
        infoCallback: () {
          context.showInfoDialog("Ensure to provide information of person in Charge (e.g., Charge Nurse, Unit Team Leader), not a general staff member.", content: []);
        },
        // backgroundColor: AppColor.fieldBgColor(context),
        showAsBottomSheet: true,
        onSelect: (value) {
          involvedPerson = value;
          payload["personInvolvedId"] = value?.id;
        },
      ),
      8.height,
      SingleItemDropDownMenu<Lookup, GenderLookupProvider>(
        context: context,
        height: 56.toScreenHeight,
        title: "Gender",
        initialValue: gender,
        showShadow: false,
        validator: (value) {
          if (value == null) return "Mandatory";
          return null;
        },
        backgroundColor: AppColor.fieldBgColor(context),
        showAsBottomSheet: true,
        onSelect: (value) {
          gender = value;
          payload["genderId"] = value?.id;
        },
      ),
      8.height,
      AppTextFormField(
        initialValue: "",
        labelText: "Person Involved ID",
        validator: (value) {
          if (involvedPerson?.value == 3 && (value ?? "").isEmpty) return "Mandatory";
          return null;
        },
        suffixIcon: Icon(Icons.info_outline_rounded, color: AppColor.icon2Color(context)).paddingOnly(end: 8).onPress(() {
          context.showInfoDialog(
              "Required if the person is an Employee. Ensure the correct Employee ID of the Person in Charge (e.g., Charge Nurse, Unit Team Leader) is provided, not a general staff member. (Ex. 34567)");
        }),
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.number,
        textInputAction: TextInputAction.next,
        onChange: (value) {
          payload["personInvolvedEmployeeId"] = value;
        },
      ),
      8.height,
      AppTextFormField(
        initialValue: "",
        labelText: "Person Involved Name",
        validator: (value) {
          if (involvedPerson?.value == 3 && (value ?? "").isEmpty) return "Mandatory";
          return null;
        },
        suffixIcon: Icon(Icons.info_outline_rounded, color: AppColor.icon2Color(context)).paddingOnly(end: 8).onPress(() {
          context.showInfoDialog("State the end-user Employee/Patient Full name. Required if the person is an Employee. (Ex. Mary-Anne Joseph)");
        }),
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.name,
        textInputAction: TextInputAction.next,
        onChange: (value) {
          payload["personInvolvedEmployeeName"] = value;
        },
      ),
      8.height,
      ADatePicker(
        label: "Occurrence Date & Time",
        hideShadow: true,
        backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral90,
        date: occurrenceDate,
        from: DateTime.now().subtract(const Duration(days: 365)),
        // enable: widget.enabled ? _tempPickerTimer == null : false,
        formatDateWithTime: true,
        onDatePicker: (selectedDate) {
          showThemedTimePicker(
            context: context,
            initialTime: TimeOfDay.now(),
          ).then((selectedTime) {
            if (selectedTime != null) {
              occurrenceDate = DateTime(selectedDate.year, selectedDate.month, selectedDate.day, selectedTime.hour, selectedTime.minute);
              setState(() {});
            }
          });
        },
      ),
    ];
  }

  Future<void> _submit() async {
    FocusScope.of(context).unfocus();
    if (_formKey.currentState!.validate()) {
      if (incidentType?.value == 1 && device == null) {
        "Please scan or pick asset".showToast;
        return;
      }
      if (incidentType?.value == 1 && device != null && woByAssetId?.id == null) {
        "Please choose CM Work Order".showToast;
        return;
      }
      if (ovrSystem?.value == 1 && isOvrVerified == false) {
        "Please verify OVR Ticket Number".showToast;
        return;
      }
      if (occurrenceDate == null) {
        "Please select occurrence Data".showToast;
        return;
      }
      payload["workOrderId"] = woByAssetId?.id;
      payload["occurrenceDate"] = occurrenceDate!.toIso8601String();
      _formKey.currentState!.save();

      List<GenericAttachmentModel> attachmentList = [];

      for (var item in attachments) {
        String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? '';
        attachmentList.add(GenericAttachmentModel(id: 0, name: fileName, moduleReferenceId: 0,documentType: item.documentType));
      }
      Utils.showLoading(context);
      IncidentProvider incidentProvider = Provider.of<IncidentProvider>(context, listen: false);

      payload["incidentAttachments"] = attachmentList.map((v) => v.toIncidentJson()).toList();
      bool isSuccess = await incidentProvider.addIncidentRequest(payload);
      Utils.hideLoading(context);
      if (isSuccess) {
        Navigator.pop(context);
      }
    }
  }
}
