// var Car_Workorder = client.getTable("Car_Workorder");
// var Car_Workorder_Status = client.getTable("Car_Workorder_Status");
// var Car_Workorder_Part = client.getTable("Car_Workorder_Part");
// var Car_Workorder_Remark = client.getTable("Car_Workorder_Remark");
// var Car_Workorder_Attachment = client.getTable("Car_Workorder_Attachment");

//REMOVE
// var Car_Workorder_Task = client.getTable("Car_Workorder_Task");
// var Car_Workorder_Cost = client.getTable("Car_Workorder_Cost");

var oBusyDialogWO = new sap.m.BusyDialog({
  text: oBundle.getText("WorkOrder_Generating"),
});

var oTablePartsItemWO = new sap.m.Table({
  noDataText: oBundle.getText("No_Data"),
  mode: "Delete",
  delete: function (oEvent) {
    var olist = oEvent.getParameter("listItem");
    var model = this.getModel();
    var path = olist.getBindingContext().getPath();
    var obj = model.getProperty(path);

    sap.m.MessageBox.show(
      oBundle.getText("Do_you_want_to_remove_item"),
      sap.m.MessageBox.Icon.ERROR,
      oBundle.getText("Alert"),
      [sap.m.MessageBox.Action.YES, sap.m.MessageBox.Action.NO],
      function (bConfirmed) {
        if (bConfirmed == "YES") {
          oTablePartsItemWO.setBusy(true);
          Car_Workorder_Part.del({ id: obj["id"] }).done(function () {
            funWorkorderParts();
            calculateTotalCost();
          }, failure);
        }
      }
    );
  },
  columns: [
    // new sap.m.Column({ header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Task Name"), design: sap.m.LabelDesign.Bold }),
    //  minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
    new sap.m.Column({
      header: new sap.m.Label({
        wrapping: true,
        text: oBundle.getText("Service_Type"),
        design: sap.m.LabelDesign.Bold,
      }),
      minScreenWidth: "Tablet",
      popinDisplay: "Inline",
      demandPopin: true,
    }),
    //  new sap.m.Column({ header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Vehicle Part"), design: sap.m.LabelDesign.Bold }) }),
    new sap.m.Column({
      header: new sap.m.Label({
        wrapping: true,
        text: oBundle.getText("Part_Name"),
        design: sap.m.LabelDesign.Bold,
      }),
      minScreenWidth: "Tablet",
      popinDisplay: "Inline",
      demandPopin: true,
    }),
    new sap.m.Column({
      header: new sap.m.Label({
        text: oBundle.getText("Quantity"),
        design: sap.m.LabelDesign.Bold,
      }),
      minScreenWidth: "Tablet",
      popinDisplay: "Inline",
      demandPopin: true,
    }),
    new sap.m.Column({
      header: new sap.m.Label({
        wrapping: true,
        text: oBundle.getText("Part_Cost"),
        design: sap.m.LabelDesign.Bold,
      }),
      minScreenWidth: "Tablet",
      popinDisplay: "Inline",
      demandPopin: true,
    }),
    new sap.m.Column({
      header: new sap.m.Label({
        wrapping: true,
        text: oBundle.getText("Labor_Cost"),
        design: sap.m.LabelDesign.Bold,
      }),
      minScreenWidth: "Tablet",
      popinDisplay: "Inline",
      demandPopin: true,
    }),
    new sap.m.Column({
      header: new sap.m.Label({
        text: oBundle.getText("Total_Cost"),
        design: sap.m.LabelDesign.Bold,
      }),
      minScreenWidth: "Tablet",
      popinDisplay: "Inline",
      demandPopin: true,
    }),
    new sap.m.Column({
      header: new sap.m.Label({
        text: oBundle.getText("Note"),
        design: sap.m.LabelDesign.Bold,
      }),
      minScreenWidth: "Tablet",
      popinDisplay: "Inline",
      demandPopin: true,
    }),
  ],
  infoToolbar: new sap.m.Toolbar({
    content: [
      new sap.m.Title({ text: oBundle.getText("Service_Needed"), level: "H2" }),
      new sap.m.ToolbarSpacer(),
      // new sap.m.Button({
      //   text: oBundle.getText("Add"),
      //   type: "Accept",
      //   icon: "sap-icon://add",
      //   press: function (e) {
      //     addUpdatePartsItem('add')
      //   },
      // }),
      // new sap.m.Button({text:oBundle.getText("Scan"),type: "Accept", icon: "sap-icon://bar-code",press:woPartsScanDialog}),
      // new sap.m.Button({text:oBundle.getText("Add"), icon: "sap-icon://add",type: "Accept",
      //  press:function (e) {

      //        var vehicle_number = oTFWOV1.getValue();
      //        if (vehicle_number.trim() == "") {
      //              sap.m.MessageBox.error(oBundle.getText("Please_select_vehicle"));
      //              return;
      //        }
      //         addPartsTableDialog();
      //     }})
    ],
  }),
});
var oTablePartsItemWOTemplate = new sap.m.ColumnListItem({
  type: "Detail",
  detailPress: function (e) {
    var model = this.getModel();
    var path = e.getSource().getBindingContext().getPath();
    var obj = model.getProperty(path);
    addUpdatePartsItem("update", obj);
  },
  cells: [
    // new sap.m.VBox({items:[
    //     new sap.m.Label({ text: "{parts_number}"}),
    //     new sap.m.Label({ text: "{part_number}"}).addStyleClass("sapUiTinyMarginTop"),
    // ]}),
    // new sap.m.Label({ wrapping: true, text: "{task_name}"}),
    new sap.m.Label({ wrapping: true, text: "{task_type}" }),
    // new sap.m.Label({ wrapping: true, text: "{vehicle_part_id}"}),
    new sap.m.Label({ wrapping: true, text: "{part_name}" }),
    new sap.m.HBox({
      items: [
        new sap.m.Label({ text: "{parts_qty}" }).addStyleClass(
          "sapUiTinyMarginBeginEnd"
        ),
        new sap.m.Label({ text: "{parts_unit}" }),
      ],
    }),
    new sap.m.Label({ wrapping: true, text: {
      path: "parts_cost",
      formatter: function (parts_cost) { return formatToIDR(parts_cost); }
    }}),
    new sap.m.Label({ wrapping: true, text: {
      path: "labor_item_cost",
      formatter: function (labor_item_cost) { return formatToIDR(labor_item_cost); }
    }}),
    new sap.m.Label({ wrapping: true, text: {
      path: "total_cost",
      formatter: function (total_cost) { return formatToIDR(total_cost); }
    }}),
    // new sap.m.Label({ wrapping: true, text: "{parts_cost}" }),
    // new sap.m.Label({ wrapping: true, text: "{labor_item_cost}" }),
    // new sap.m.Label({ wrapping: true, text: "{total_cost}" }),
    new sap.m.Label({ wrapping: true, text: "{note}" }),
  ],
});

var oTableWOAttachment = new sap.m.Table({
  width: "80%",
  noDataText: oBundle.getText("No_Data"),
  mode: "Delete",
  delete: function (oEvent) {
    var oContext = oEvent.getParameter("listItem").getBindingContext();
    var mid = oContext.getObject().id;
    sap.m.MessageBox.show(
      oBundle.getText("Do_you_want_to_remove_item"),
      sap.m.MessageBox.Icon.ERROR,
      oBundle.getText("Alert"),
      [sap.m.MessageBox.Action.YES, sap.m.MessageBox.Action.NO],
      function (bConfirmed) {
        if (bConfirmed == "YES") {
          oTableWOAttachment.setBusy(true);
          Car_Workorder_Attachment.del({ id: mid }).done(function () {
            funWorkorderAttachment();
            oTableWOAttachment.setBusy(false);
          }, failure);
        }
      }
    );
  },
  columns: [
    new sap.m.Column({
      header: new sap.m.Label({
        wrapping: true,
        text: oBundle.getText("Attachment_Type"),
        design: sap.m.LabelDesign.Bold,
      }),
    }),
    new sap.m.Column({
      header: new sap.m.Label({
        text: oBundle.getText("Description"),
        design: sap.m.LabelDesign.Bold,
      }),
    }),
    new sap.m.Column({
      header: new sap.m.Label({
        text: oBundle.getText("Download"),
        design: sap.m.LabelDesign.Bold,
      }),
      minScreenWidth: "Desktop",
      popinDisplay: "Inline",
      demandPopin: true,
    }),
  ],
  infoToolbar: new sap.m.Toolbar({
    content: [
      new sap.m.Title({ text: oBundle.getText("Attachment"), level: "H2" }),
      new sap.m.ToolbarSpacer(),
      new sap.m.Button({
        text: oBundle.getText("Add"),
        type: "Accept",
        icon: sap.ui.core.IconPool.getIconURI("add"),
        press: addUpdateAttachment,
      }),
    ],
  }),
});
var oTableAttachmentTemplate = new sap.m.ColumnListItem({
  type: "Active",
  cells: [
    new sap.m.Label({ wrapping: true, text: "{attachment_type}" }),
    new sap.m.Label({ wrapping: true, text: "{attachment_name}" }),
    new sap.m.Button({
      text: oBundle.getText("Download"),
      icon: "sap-icon://download",
      type: sap.m.ButtonType.Emphasized,
      press: function (e) {
        var model = this.getModel();
        var path = e.getSource().getBindingContext().getPath();
        var obj = model.getProperty(path);
        var blob_path = obj["attachment_url"];

        window.open(blob_path, "_blank");
      },
    }),
  ],
});





var oTableWORemark = new sap.m.Table({
  noDataText: oBundle.getText("No_Data"),
  mode: "Delete",
  delete: function (oEvent) {
    var olist = oEvent.getParameter("listItem");
    var model = this.getModel();
    var path = olist.getBindingContext().getPath();
    var obj = model.getProperty(path);

    sap.m.MessageBox.show(
      oBundle.getText("Do_you_want_to_remove_item"),
      sap.m.MessageBox.Icon.ERROR,
      oBundle.getText("Alert"),
      [sap.m.MessageBox.Action.YES, sap.m.MessageBox.Action.NO],
      function (bConfirmed) {
        if (bConfirmed == "YES") {
          oTableWORemark.setBusy(true);
          Car_Workorder_Remark.del({ id: obj["id"] }).done(function () {
            funWorkorderRemark();
          }, failure);
        }
      }
    );
  },
  columns: [
    new sap.m.Column({
      header: new sap.m.Label({
        text: oBundle.getText("Remark"),
        design: sap.m.LabelDesign.Bold,
      }),
    }),
    new sap.m.Column({
      header: new sap.m.Label({
        text: oBundle.getText("Date"),
        design: sap.m.LabelDesign.Bold,
      }),
    }),
    new sap.m.Column({
      header: new sap.m.Label({
        text: oBundle.getText("Remark_By"),
        design: sap.m.LabelDesign.Bold,
      }),
    }),
  ],
  infoToolbar: new sap.m.Toolbar({
    content: [
      new sap.m.Title({ text: oBundle.getText("Remarks"), level: "H2" }),
      new sap.m.ToolbarSpacer(),
      new sap.m.Button({
        text: oBundle.getText("Add"),
        type: "Accept",
        icon: sap.ui.core.IconPool.getIconURI("add"),
        press: addUpdateRemarkDialog,
      }),
    ],
  }),
});
var oTableWORemarkTemplate = new sap.m.ColumnListItem({
  type: "Detail",
  detailPress: function (e) {
    var model = this.getModel();
    var path = e.getSource().getBindingContext().getPath();
    var obj = model.getProperty(path);
    addUpdateRemarkDialog("update", obj);
  },
  cells: [
    new sap.m.Label({ wrapping: true, text: "{remark}" }),
    new sap.m.Label({ wrapping: true, text: "{added_date}" }),
    new sap.m.Label({ wrapping: true, text: "{added_by}" }),
  ],
});

var WOPriority = new sap.m.Select({
  width: "100%",
  items: [
    //new sap.ui.core.ListItem({key:"1",text:oBundle.getText("Normal")}),
    new sap.ui.core.ListItem({ key: "1", text: oBundle.getText("Low") }),
    new sap.ui.core.ListItem({ key: "2", text: oBundle.getText("Medium") }),
    new sap.ui.core.ListItem({ key: "3", text: oBundle.getText("High") }),
    new sap.ui.core.ListItem({ key: "4", text: oBundle.getText("Emergency") }),
  ],
});

var WOmeterUnit = meterUnit.clone();
WOmeterUnit.setEnabled(false);
var WOTypeDB = new sap.m.ComboBox({
  width: "100%",
  items: [
    new sap.ui.core.ListItem({ key: "1", text: oBundle.getText("PACKAGE") }),
    new sap.ui.core.ListItem({
      key: "2",
      text: oBundle.getText("NON_PACKAGE"),
    }),
    new sap.ui.core.ListItem({
      key: "3",
      text: oBundle.getText("POOL_ACTIVITY"),
    }),
    new sap.ui.core.ListItem({ key: "4", text: oBundle.getText("INSURANCE") }),
    new sap.ui.core.ListItem({
      key: "5",
      text: oBundle.getText("NON_INSURANCE"),
    }),
    new sap.ui.core.ListItem({ key: "6", text: oBundle.getText("RITASE") }),
    new sap.ui.core.ListItem({
      key: "7",
      text: oBundle.getText("DOCUMENT_EXPENSE"),
    }),
  ],
}).addEventDelegate({
  onAfterRendering: function (e) {
    WOTypeDB.$().find("input").attr("readonly", true);
  },
});

var cityTypeDB = cityCB.clone();
cityTypeDB.addEventDelegate({
  onAfterRendering: function (e) {
    cityTypeDB.$().find("input").attr("readonly", true);
  },
});
var oTFWOV0 = new sap.m.Input({ enabled: false });

var oTFWOV1 = new sap.m.Input({
    showValueHelp: true,
    showSuggestion: true, //valueHelpOnly: true,
    placeholder: oBundle.getText("Select_vehicle_from_inventry_list"),
    valueHelpRequest: function () {
      if(!vehicleTemp){
        selectVehiclArea = "workorder_create";
        pickVehicle();
      }else{
        sap.m.MessageBox.error(oBundle.getText("Please Wait while vehicles get loaded."));
        get4WVehicle();
        vehicleTemp = false;
        return;
      }
    },
    suggestionItemSelected: function (oEvent) {
      if(vehicleTemp){
        oTFWOV1.setValue("");
        sap.m.MessageBox.error(oBundle.getText("Please Wait while vehicles get loaded."));
        get4WVehicle();
        vehicleTemp = false;
        return;
      }
        let selectedVehicle = vehicle4WJSONData.filter(function (val, ind) {
        return val.license_number.toLowerCase() == oTFWOV1.getValue().toLowerCase();
        });
       
        if (selectedVehicle.length > 0) {
          oTFWOV1.setValue(selectedVehicle[0]["license_number"]);
          oTFWOV0.setValue(selectedVehicle[0]["id"]);
          oTFWOV8.setValue(selectedVehicle[0]["chassis_number"]);
          oTFWOV9.setValue(selectedVehicle[0]["engine_number"]);
          oTFWOV10.setValue(selectedVehicle[0]["make"]);
          oTFWOV3.setValue(selectedVehicle[0]["model"]);
          oTFWOV11.setValue(selectedVehicle[0]["vehicle_color"]);
          oTFWOV4.setValue(selectedVehicle[0]["odometer"] || 0);
          oTFWOV12.setValue(selectedVehicle[0]["rental_company_name"]);
          oTFWOV13.setValue(selectedVehicle[0]["leasing_company_name"]);
          oTFWOV14.setValue(selectedVehicle[0]["transmission"]);
        }else{
            oTFWOV0.setValue("");
            oTFWOV1.setValue("");
            oTFWOV3.setValue("");
            oTFWOV4.setValue("");
            oTFWOV8.setValue("");
            oTFWOV9.setValue("");
            oTFWOV10.setValue("");
            oTFWOV11.setValue("");
            oTFWOV12.setValue("");
            oTFWOV13.setValue("");
            oTFWOV14.setValue("");
          }
          filterWorkorderPartWorkshop();

        var selectedItem = oEvent.getParameter("selectedItem");
        if (selectedItem) {
          var vehicle_number = selectedItem.getKey();
          this.setValue(vehicle_number);
        }
    },
    change: function () {
      if(vehicleTemp){
        oTFWOV1.setValue("");
        sap.m.MessageBox.error(oBundle.getText("Please Wait while vehicles get loaded."));
        get4WVehicle();
        vehicleTemp = false;
        return;
      }
        let selectedVehicle = vehicle4WJSONData.filter(function (val, ind) {
          return val.license_number.toLowerCase() == oTFWOV1.getValue().toLowerCase();
          });
         
          if (selectedVehicle.length > 0) {
            oTFWOV1.setValue(selectedVehicle[0]["license_number"]);
            oTFWOV0.setValue(selectedVehicle[0]["id"]);
            oTFWOV8.setValue(selectedVehicle[0]["chassis_number"]);
            oTFWOV9.setValue(selectedVehicle[0]["engine_number"]);
            oTFWOV10.setValue(selectedVehicle[0]["make"]);
            oTFWOV3.setValue(selectedVehicle[0]["model"]);
            oTFWOV11.setValue(selectedVehicle[0]["vehicle_color"]);
            oTFWOV4.setValue(selectedVehicle[0]["odometer"] || 0);
            oTFWOV12.setValue(selectedVehicle[0]["rental_company_name"]);
            oTFWOV13.setValue(selectedVehicle[0]["leasing_company_name"]);
            oTFWOV14.setValue(selectedVehicle[0]["transmission"]);
          }else{
            oTFWOV0.setValue("");
            oTFWOV1.setValue("");
            oTFWOV3.setValue("");
            oTFWOV4.setValue("");
            oTFWOV8.setValue("");
            oTFWOV9.setValue("");
            oTFWOV10.setValue("");
            oTFWOV11.setValue("");
            oTFWOV12.setValue("");
            oTFWOV13.setValue("");
            oTFWOV14.setValue("");
          }
          filterWorkorderPartWorkshop();
        // Handle when the input value changes (manual typing)
        // let partServiceNeeded = workorderPartJSONArray.filter(function(val,ind){
        //     return val.part_name ==  oInputPartField1.getValue() && val.workshop_number == oxmaint_workshop_number;
        // });
        // if(partServiceNeeded.length > 0){
        //     oInputPartField3.setValue(partServiceNeeded[0]['part_cost']);
        //     oInputPartField4.setValue(partServiceNeeded[0]['labor_cost']);
        // }else{
        //     oInputPartField3.setValue(0);
        //     oInputPartField4.setValue(0);
        // }
    },
});
var oTFWOV2 = new sap.m.Input({ enabled: false });
var oTFWOV3 = new sap.m.Input({ enabled: false });
var oTFWOV4 = new sap.m.Input({ required: true, type: "Number" });

var oTFWOV5 = new sap.m.Input({ enabled: false });

var oTFWOV6 = new sap.m.MultiInput({
  enabled: false, showSuggestion: true, valueHelpOnly: true, fieldWidth: "100%",
  valueHelpRequest: function () {
    selectTeamWSGroup(oTFWOV6);
  },
});
var oTFWOV7 = new sap.m.MultiInput({
  enabled: false, showSuggestion: true, fieldWidth: "100%", valueHelpOnly: true,
  autocomplete: true,
  valueHelpRequest: function () {
    selectTeamWorkshop(3, oTFWOV7);
  },
  tokenUpdate: function (oEvent) {
    var aRemovedTokens = oEvent.getParameter("removedTokens");
    if (aRemovedTokens.length > 0) {
      workorderPartJSONArray = [];
            
      var oModel12 = new sap.ui.model.json.JSONModel();
      oModel12.setData({ modelData: workorderPartJSONArray }); // results is an array of suggestion data
      oInputPartField1.setModel(oModel12);

      var oModel = new sap.ui.model.json.JSONModel();
      oModel.setData({ modelData: workorderPartJSONArray });
      oTablePickPartWO.setModel(oModel);
      oTablePickPartWO.bindItems({ path: "/modelData", template : oTablePickPartTemplate });
    }
  }
});
if(allowedRoles.includes(oxmaint_role)){
    oTFWOV6.setEnabled(true);
    oTFWOV7.setEnabled(true);
}else{
    oTFWOV6.setEnabled(false);
    oTFWOV7.setEnabled(false);
}
var oTFWOV8 = new sap.m.Input({ enabled: false });
var oTFWOV9 = new sap.m.Input({ enabled: false });
var oTFWOV10 = new sap.m.Input({ enabled: false });
var oTFWOV11 = new sap.m.Input({ enabled: false });
var oTFWOV12 = new sap.m.Input({ enabled: false });
var oTFWOV13 = new sap.m.Input({ enabled: false });
var oTFWOV14 = new sap.m.Input({ enabled: false });

var oTFWOCost1 = new sap.m.Input({
  type: "Number",
  value: "0",
  width: "100%",
  enabled: false,
});
var oTFWOCost2 = new sap.m.Input({
  type: "Number",
  value: "0",
  width: "100%",
  enabled: false,
});
var oTFWOCost3 = new sap.m.Input({
  type: "Number",
  value: "0",
  width: "100%",
  enabled: false,
});
var oTFWOCost4 = new sap.m.Input({
  type: "Number",
  value: "0",
  width: "50px",
  enabled: false,
  liveChange: function (oEvent) {
    calculateTotalCost();
  },
});

var oTFWOCost5 = new sap.m.Input({
  type: "Number",
  value: "0",
  width: "100px",
  enabled: false,
});
var oTFWOCost6 = new sap.m.Input({
  type: "Number",
  value: "0",
  width: "200px",
  enabled: false,
});

var oTFWOCustom1 = new sap.m.Input({ visible: false });
var oTFWOCustom2 = new sap.m.Input({ visible: false });
var oTFWOCustom3 = new sap.m.Input({ visible: false });
var oTFWOCustom4 = new sap.m.Input({ visible: false });
var oTFWOCustom5 = new sap.m.Input({ visible: false });

var customWOText1 = new sap.m.Label({ visible: false });
var customWOText2 = new sap.m.Label({ visible: false });
var customWOText3 = new sap.m.Label({ visible: false });
var customWOText4 = new sap.m.Label({ visible: false });
var customWOText5 = new sap.m.Label({ visible: false });

var oDueDate = new sap.m.DateTimePicker({
  width: "100%",
  displayFormat: "dd-MMM-yyyy hh:mm a",
  valueFormat: "dd-MMM-yyyy hh:mm a",
});
var woStartDate = new sap.m.DateTimePicker({
  width: "100%",
  displayFormat: "dd-MMM-yyyy hh:mm a",
  valueFormat: "dd-MMM-yyyy hh:mm a",
});

var oTFWOPlannedCost = new sap.m.Input({
  type: "Number",
  value: "0",
  width: "100%",
  description: "USD",
});
var oTFWOPlannedTime = new sap.m.Input({
  type: "Number",
  value: "0",
  width: "100%",
  description: "Hours",
});

var oTFWOMemo = new sap.m.TextArea({
  width: "100%",
  height: "70px",
  rows: 2,
  wrapping: sap.ui.core.Wrapping.on,
}); //.addStyleClass("field");

var btnWO1 = new sap.m.Button({
  visible: true,
  icon: "sap-icon://create-form",
  type: sap.m.ButtonType.Emphasized,
  text: oBundle.getText("Create_WorkOrder"),
  width: "20%",
  press: function () {
    chekWOValidation();
  },
});

var btnWO2 = new sap.m.Button({
  visible: false,
  icon: "sap-icon://write-new-document",
  type: sap.m.ButtonType.Emphasized,
  text: oBundle.getText("Update_WorkOrder"),
  width: "20%",
  press: updateWorkOrderSubmit,
});

var woAssignedInput = new sap.m.MultiInput({
  showSuggestion: true,
  fieldWidth: "100%",
  valueHelpRequest: function () {
    assignedTeamDialog(1);
  },
  suggestionItemSelected: function (oEvent) {
    var tokenList = this.getTokens();
    var selectedItem = oEvent.getParameter("selectedItem");
    if (selectedItem) {
      var insertFlag = true;
      for (var i = 0; i < tokenList.length; i++) {
        if (tokenList[i].getKey() == selectedItem.getKey()) {
          insertFlag = false;
        }
      }
      if (tokenList.length == 0 || insertFlag) {
        woAssignedInput.addToken(
          new sap.m.Token({
            key: selectedItem.getKey(),
            text: selectedItem.getText(),
          })
        );
        // insetLaborTable(selectedItem.getKey(), selectedItem.getText());
      }
    }
  },
});

var inspectionLinkInput = new sap.m.MultiInput({
  id: "inspection_link",
  fieldWidth: "100%",
  valueHelpOnly:true,
  valueHelpRequest: function () {
    if(!inspectionTemp){
      var vehicle_number = oTFWOV1.getValue();
      if (vehicle_number.trim() == "") {
        sap.m.MessageBox.error(oBundle.getText("Please_select_vehicle"));
        return;
      }
      linkInspection(3, vehicle_number);
    }else{
      if(inspectionTemp){
        funGetInspection();
        inspectionTemp = false;
      }
      sap.m.MessageBox.error(oBundle.getText("Please Wait while inspections get loaded."));
      return;
    }
  },
});

var workorderLinkInput = new sap.m.MultiInput({
  id: "workorder_link",
  fieldWidth: "100%",
  valueHelpRequest: function () {
    var vehicle_number = oTFWOV1.getValue();
    if (vehicle_number.trim() == "") {
      sap.m.MessageBox.error(oBundle.getText("Please_select_vehicle"));
      return;
    }
    linkWorkorder();
  },
});

var wo_title_field = new sap.m.Input({ value: "", width: "100%" });

var serviceWoCB = new sap.m.ComboBox({
  value: oBundle.getText("No"),
  items: [
    new sap.ui.core.ListItem({ key: "1", text: oBundle.getText("Yes") }),
    new sap.ui.core.ListItem({ key: "2", text: oBundle.getText("No") }),
  ],
  change: function (oEvent) {
    let enteredValue = oEvent.getParameter("value");
    let isValid = serviceWoCB
      .getItems()
      .some((item) => item.getText() === enteredValue);

    if (serviceWoCB.getSelectedKey() == "1") {
      workorderForm1
        .getFormContainers()[0]
        .getFormElements()[5]
        .setVisible(true);
    } else {
      workorderForm1
        .getFormContainers()[0]
        .getFormElements()[5]
        .setVisible(false);
    }

    if (!isValid) {
      sap.m.MessageBox.error(
        oBundle.getText("Please_select_a_valid_value_from_the_list")
      );
      oIF4wWorkshop10.setValue(oBundle.getText("No"));
    }
  },
}).addEventDelegate({
  onAfterRendering: function (e) {
    serviceWoCB.$().find("input").attr("readonly", true);
  },
});
var serviceKm = new sap.m.Input({ type: "Number", value: "0" });

var workorderForm1 = new sap.ui.layout.form.Form({
  editable: true,
  layout: new sap.ui.layout.form.ResponsiveGridLayout(),
  formContainers: [
    new sap.ui.layout.form.FormContainer({
      formElements: [
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({
            required: true,
            text: oBundle.getText("Title"),
          }),
          fields: [wo_title_field],
        }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({ text: oBundle.getText("Memo") }),
          fields: [oTFWOMemo],
        }),
        // new sap.ui.layout.form.FormElement({
        //     label: new sap.m.Label({ text: oBundle.getText("Priority") }),
        //     fields: [WOPriority]
        // }), //TO Remove
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({
            required: true,
            text: oBundle.getText("City"),
          }),
          fields: [cityTypeDB],
        }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({ text: oBundle.getText("Assigned_to") }),
          fields: [woAssignedInput],
        }),

        // new sap.ui.layout.form.FormElement({
        //     label: new sap.m.Label({ text: oBundle.getText("Workorder_Type") }),
        //     fields: [WOTypeDB]
        // }),

        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({ text: oBundle.getText("Regular_Service") }),
          fields: [serviceWoCB],
        }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({ text: oBundle.getText("Service_KM") }),
          fields: [serviceKm],
        }),

        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({ text: oBundle.getText("Link_Inspection") }),
          fields: [inspectionLinkInput],
        }),
        // new sap.ui.layout.form.FormElement({
        //     label: new sap.m.Label({ text: oBundle.getText("Link_Workorder") }),
        //     fields: [workorderLinkInput]
        // })
        new sap.ui.layout.form.FormElement({
          fields: [new sap.m.Title({ text: oBundle.getText("Wokshop_Data") })],
        }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({
            text: oBundle.getText("Workshop_Group_Name"),
          }),
          fields: [oTFWOV6],
        }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({ text: oBundle.getText("Workshop_Name") }),
          fields: [oTFWOV7],
        }),
      ],
    }),
    new sap.ui.layout.form.FormContainer({
      formElements: [
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({
            required: true,
            text: oBundle.getText("License_Plate"),
          }),
          fields: [oTFWOV1],
        }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({
            required: true,
            text: oBundle.getText("Vehicle_Id"),
          }),
          fields: [oTFWOV0],
        }),
        // new sap.ui.layout.form.FormElement({
        //     label: new sap.m.Label({ required: true, text: oBundle.getText("Vehicle_Name") }),
        //     fields: [oTFWOV2]
        // }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({
            required: true,
            text: oBundle.getText("Chassis_Number"),
          }),
          fields: [oTFWOV8],
        }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({
            required: true,
            text: oBundle.getText("Engine_Number"),
          }),
          fields: [oTFWOV9],
        }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({
            required: true,
            text: oBundle.getText("Make"),
          }),
          fields: [oTFWOV10],
        }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({
            required: true,
            text: oBundle.getText("Model"),
          }),
          fields: [oTFWOV3],
        }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({
            required: true,
            text: oBundle.getText("Transmission"),
          }),
          fields: [oTFWOV14],
        }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({
            required: true,
            text: oBundle.getText("Color"),
          }),
          fields: [oTFWOV11],
        }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({ text: oBundle.getText("Odometer") }),
          fields: [oTFWOV4, WOmeterUnit],
        }),

        // new sap.ui.layout.form.FormElement({
        //     fields: [new sap.m.Title({ text: oBundle.getText("Lease/Rental Data") })]
        // }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({
            text: oBundle.getText("Rental_Company_Name"),
          }),
          fields: [oTFWOV12],
        }),
        new sap.ui.layout.form.FormElement({
          label: new sap.m.Label({
            text: oBundle.getText("Leasing_Company_Name"),
          }),
          fields: [oTFWOV13],
        }),
      ],
    }),
  ],
}).addStyleClass("sapUiNoContentPadding");
// workorderForm1.getFormContainers()[0].getFormElements()[5].setVisible(false);

var workorderForm2 = new sap.ui.layout.form.Form({
  editable: true,
  layout: new sap.ui.layout.form.ResponsiveGridLayout(),
  formContainers: [
    new sap.ui.layout.form.FormContainer({
      formElements: [
        new sap.ui.layout.form.FormElement({
          fields: [
            new sap.ui.layout.HorizontalLayout({
              content: [
                new sap.ui.layout.VerticalLayout({
                  content: [
                    new sap.m.Label({
                      text: oBundle.getText("Parts_Material_Cost"),
                    }).addStyleClass("sapUiTinyMargin"),
                    new sap.m.Label({
                      text: oBundle.getText("Total_Labor_Cost"),
                    }).addStyleClass("sapUiTinyMargin"),
                    // new sap.m.Label({ text: oBundle.getText("Additional_Cost") }).addStyleClass("sapUiTinyMargin"),
                    new sap.m.Label({
                      text: oBundle.getText("VAT"),
                    }).addStyleClass("sapUiTinyMargin"),
                    new sap.m.Label({
                      text: oBundle.getText("Total_WO_Cost") + "(IDR)",
                    }).addStyleClass("sapUiTinyMargin"),
                  ],
                }),
                new sap.ui.layout.VerticalLayout({
                  width: "150px",
                  content: [
                    oTFWOCost1,
                    oTFWOCost2, //oTFWOCost3,
                    new sap.ui.layout.HorizontalLayout({
                      content: [oTFWOCost4, oTFWOCost5],
                    }),
                    oTFWOCost6,
                  ],
                }),
              ],
            }),
          ],
        }),
      ],
    }),
    // new sap.ui.layout.form.FormContainer({
    //      formElements: [
    //         new sap.ui.layout.form.FormElement({
    //             fields: [new sap.m.Title({ id: "customWOHeader", visible :false, text: oBundle.getText("Custom_Business_Fields") })]
    //         }),
    //         new sap.ui.layout.form.FormElement({
    //             label: customWOText1,
    //             fields: [oTFWOCustom1]
    //         }),
    //         new sap.ui.layout.form.FormElement({
    //             label: customWOText2,
    //             fields: [oTFWOCustom2]
    //         }),
    //         new sap.ui.layout.form.FormElement({
    //             label: customWOText3,
    //             fields: [oTFWOCustom3]
    //         }),
    //         new sap.ui.layout.form.FormElement({
    //             label: customWOText4,
    //             fields: [oTFWOCustom4]
    //         }),
    //         new sap.ui.layout.form.FormElement({
    //             label: customWOText5,
    //             fields: [oTFWOCustom5]
    //         })
    // ]}),
  ],
});
var workorderPartJSONArray;
// var oInputPartField1 = new sap.m.Input({
//   showSuggestion: true,
//   suggestionItems: {
//     path: "/suggestions",
//     template: new sap.ui.core.Item({
//       text: "{part_name}",
//     }),
//   },
//   suggest: function (oEvent) {
//     var sValue = oEvent.getParameter("suggestValue");
//     var aSuggestions = workorderPartJSONArray;

//     var aFilteredSuggestions = aSuggestions.filter(function (item) {
//       return item.part_name.toLowerCase().indexOf(sValue.toLowerCase()) !== -1;
//     });

//     var oModel = oInputPartField1.getModel();
//     oModel.setProperty("/suggestions", aFilteredSuggestions);
//   },
//   suggestionItemSelected: function (oEvent) {
//     // Handle the selected item
//     var oSelectedItem = oEvent.getParameter("selectedItem");
//     // if (oSelectedItem) {
//     //     console.log("Selected:", oSelectedItem.getText()); // The selected item's text
//     // } else {
//     //     console.log("No item selected");
//     // }

//     let workshop_number = "";
//     let workshopWoTokenList = oTFWOV7.getTokens();

//     for (var j = 0; j < workshopWoTokenList.length; j++) {
//       if (workshop_number == "") {
//         workshop_number = workshopWoTokenList[j].getKey();
//       }
//     }

//     let partServiceNeeded1 = workorderPartJSONArray.filter(function (val, ind) {
//       return (
//         val.part_name == oSelectedItem.getText() &&
//         // val.workshop_number == oxmaint_workshop_number
//         val.workshop_number == workshop_number
//       );
//     });
//     if (partServiceNeeded1.length > 0) {
//       oInputPartField3.setValue(partServiceNeeded1[0]["part_cost"]);
//       oInputPartField4.setValue(partServiceNeeded1[0]["labor_cost"]);
//     } else {
//       oInputPartField3.setValue(0);
//       oInputPartField4.setValue(0);
//     }
//   },
//   change: function () {

//     let workshop_number = "";
//     let workshopWoTokenList = oTFWOV7.getTokens();

//     for (var j = 0; j < workshopWoTokenList.length; j++) {
//       if (workshop_number == "") {
//         workshop_number = workshopWoTokenList[j].getKey();
//       }
//     }

//     // Handle when the input value changes (manual typing)
//     let partServiceNeeded = workorderPartJSONArray.filter(function (val, ind) {
//       return (
//         val.part_name == oInputPartField1.getValue() &&
//         // val.workshop_number == oxmaint_workshop_number
//         val.workshop_number == workshop_number
//       );
//     });
//     if (partServiceNeeded.length > 0) {
//       oInputPartField3.setValue(partServiceNeeded[0]["part_cost"]);
//       oInputPartField4.setValue(partServiceNeeded[0]["labor_cost"]);
//     } else {
//       oInputPartField3.setValue(0);
//       oInputPartField4.setValue(0);
//     }
//   },
// });



var oInputPartField1 = new sap.m.Input({
  showValueHelp: true,
  showSuggestion: true, 
  // placeholder: oBundle.getText("Select_vehicle_from_inventry_list"),
  valueHelpRequest: function () {
    var vehicle_number = oTFWOV1.getValue();
    if (vehicle_number.trim() == "") {
        sap.m.MessageBox.error(oBundle.getText("Please_select_vehicle"));
        return;
    }
      getPickPartTable();
  },
  suggestionItems: {
    path: "/suggestions",
    template: new sap.ui.core.Item({
      text: "{part_name}",
    }),
  },
  suggest: function (oEvent) {
    var sValue = oEvent.getParameter("suggestValue");
    var aSuggestions = workorderPartJSONArray;

    var aFilteredSuggestions = aSuggestions.filter(function (item) {
      return item.part_name.toLowerCase().indexOf(sValue.toLowerCase()) !== -1;
    });

    var oModel = oInputPartField1.getModel();
    oModel.setProperty("/suggestions", aFilteredSuggestions);
  },
  suggestionItemSelected: function (oEvent) {
    var oSelectedItem = oEvent.getParameter("selectedItem");
    if (!oSelectedItem) return;

    let workshop_number = "";
    let workshopWoTokenList = oTFWOV7.getTokens();

    for (var j = 0; j < workshopWoTokenList.length; j++) {
      if (workshop_number === "") {
        workshop_number = workshopWoTokenList[j].getKey();
      }
    }

    let partServiceNeeded1 = workorderPartJSONArray.filter(function (val) {
      return (
        val.part_name === oSelectedItem.getText() &&
        val.workshop_number === workshop_number
      );
    });

    if (partServiceNeeded1.length > 0) {
      if(partServiceNeeded1[0]['part_type'] == 'Supplier'){
        oInputPartField3.setEnabled(false);
        oInputPartField4.setEnabled(false);
      }else{
        oInputPartField3.setEnabled(true);
        oInputPartField4.setEnabled(true);
      }
      oInputPartField3.setValue(partServiceNeeded1[0]["part_cost"]);
      oInputPartField4.setValue(partServiceNeeded1[0]["labor_cost"]);
    } else {
      oInputPartField3.setValue(0);
      oInputPartField4.setValue(0);
    }
    updatetotalCostWOPart();
  },
  change: function () {
    let workshop_number = "";
    let workshopWoTokenList = oTFWOV7.getTokens();

    for (var j = 0; j < workshopWoTokenList.length; j++) {
      if (workshop_number === "") {
        workshop_number = workshopWoTokenList[j].getKey();
      }
    }

    let partServiceNeeded = workorderPartJSONArray.filter(function (val) {
      return (
        val.part_name === oInputPartField1.getValue() &&
        val.workshop_number === workshop_number
      );
    });
   
    if (partServiceNeeded.length > 0) {
      if(partServiceNeeded[0]['part_type'] == 'Supplier'){
        oInputPartField3.setEnabled(false);
        oInputPartField4.setEnabled(false);
      }else{
        oInputPartField3.setEnabled(true);
        oInputPartField4.setEnabled(true);
      }
      oInputPartField3.setValue(partServiceNeeded[0]["part_cost"]);
      oInputPartField4.setValue(partServiceNeeded[0]["labor_cost"]);
    } else {
      oInputPartField3.setValue(0);
      oInputPartField4.setValue(0);
    }
    updatetotalCostWOPart();
  },
});


var oInputPartField0 = new sap.m.ComboBox({
  width: "100%",
  items: [
    new sap.ui.core.ListItem({ key: "1", text: oBundle.getText("PACKAGE") }),
    new sap.ui.core.ListItem({ key: "2", text: oBundle.getText("NON_PACKAGE")}),
    new sap.ui.core.ListItem({ key: "3", text: oBundle.getText("POOL_ACTIVITY")}),
    new sap.ui.core.ListItem({ key: "4", text: oBundle.getText("INSURANCE") }),
    new sap.ui.core.ListItem({ key: "5", text: oBundle.getText("NON_INSURANCE")}),
    new sap.ui.core.ListItem({ key: "6", text: oBundle.getText("RITASE") }),
    new sap.ui.core.ListItem({ key: "7", text: oBundle.getText("DOCUMENT_EXPENSE")}),
  ],
}).addEventDelegate({ onAfterRendering: function (e) {} });

//ADD 2 wheeler service types
if (portal_type_flag === '2W') {
  oInputPartField0.removeAllItems(); // Clear existing items

  oInputPartField0.addItem(new sap.ui.core.ListItem({ key: "1", text: oBundle.getText("Regular Service (Package)") }));
  oInputPartField0.addItem(new sap.ui.core.ListItem({ key: "2", text: oBundle.getText("Regular Service (Non Package)") }));
  oInputPartField0.addItem(new sap.ui.core.ListItem({ key: "3", text: oBundle.getText("Ad hoc Battery") }));
  oInputPartField0.addItem(new sap.ui.core.ListItem({ key: "4", text: oBundle.getText("Ad hoc Preparation - Unit Idle (Part Only)") }));
  oInputPartField0.addItem(new sap.ui.core.ListItem({ key: "5", text: oBundle.getText("Ad hoc Repo - Unit Idle") }));
  oInputPartField0.addItem(new sap.ui.core.ListItem({ key: "6", text: oBundle.getText("Ad hoc Tyre") }));
  oInputPartField0.addItem(new sap.ui.core.ListItem({ key: "7", text: oBundle.getText("Insurance") }));
  oInputPartField0.addItem(new sap.ui.core.ListItem({ key: "8", text: oBundle.getText("Vehicle Document Expense") }));
  oInputPartField0.addItem(new sap.ui.core.ListItem({ key: "9", text: oBundle.getText("Ritase") }));
}


oInputPartField0.attachChange(function (oEvent) {
  var sUserInput = oEvent.getSource().getValue().trim();
  var aItems = oEvent.getSource().getItems();
  var bIsMatchFound = false;

  // Loop through items to check if user input matches any item text
  for (var i = 0; i < aItems.length; i++) {
    if (aItems[i].getText() === sUserInput) {
      bIsMatchFound = true;
      break;
    }
  }

  if (bIsMatchFound) {
    // console.log("User selected or typed a valid option.");
    oEvent.getSource().setValueState("Success");
  } else {
    // console.log("User input does not match any dropdown option.");

    oEvent.getSource().setValue("");
    oEvent.getSource().setValueState("Error");
    oEvent.getSource().setValueStateText("Please select a valid option from the list.");
  }
});

var oInputPartField2 = new sap.m.Input({
  type: "Number",

  liveChange: function (oEvent) {
    let roundedValue = roundToInt(oInputPartField2.getValue());
    oEvent.getSource().setValue(roundedValue);
    updatetotalCostWOPart();
  },
});
var oInputPartField3 = new sap.m.Input({
  type: "Number",
  liveChange: function (oEvent) {
    let roundedValue = roundToInt(oInputPartField3.getValue());
    oEvent.getSource().setValue(roundedValue);
    updatetotalCostWOPart();
  },
});
var oInputPartField4 = new sap.m.Input({
  type: "Number",
  liveChange: function (oEvent) {
    let roundedValue = roundToInt(oInputPartField4.getValue());
    oEvent.getSource().setValue(roundedValue);
    updatetotalCostWOPart();
  },
});
var oInputPartField5 = new sap.m.Input({ type: "Number", enabled: false });
var oInputPartField6 = new sap.m.Input({});
var oInputPartField7 = new sap.m.Button({
  text: oBundle.getText("Add"),
  type: "Accept",
  icon: sap.ui.core.IconPool.getIconURI("add"),
  press: function () {
    var vehicle_number = oTFWOV1.getValue();
    if (vehicle_number.trim() == "") {
      sap.m.MessageBox.error(oBundle.getText("Please_select_vehicle"));
      return;
    }
    let task_type = oInputPartField0.getValue();
    let part_name = oInputPartField1.getValue();
    let quantity = oInputPartField2.getValue();
    let part_cost = oInputPartField3.getValue();
    let labor_cost = oInputPartField4.getValue();
    let total_cost = oInputPartField5.getValue();
    let note = oInputPartField6.getValue();
    var vehicle_number = oTFWOV1.getValue();

    if (validation(task_type, oBundle.getText("Service_Type"))) {
      return;
    }
    if (validation(part_name, oBundle.getText("Part_Name"))) {
      return;
    }
    if (validateNumber(quantity, oBundle.getText("Quantity"))) {
      return;
    }
    if (validateNumber(part_cost, oBundle.getText("Part_Cost"))) {
      return;
    }
    if (validateNumber(labor_cost, oBundle.getText("Labor_Cost"))) {
      return;
    }

    quantity = roundToInt(oInputPartField2.getValue());
    part_cost = roundToInt(oInputPartField3.getValue());
    labor_cost = roundToInt(oInputPartField4.getValue());
    total_cost = roundToInt(oInputPartField5.getValue());

    // if (part_name && (part_name.includes("Tyre") || part_name.includes("Battery"))) {
    //   if (!note || note.trim().length < 1) {
    //     sap.m.MessageBox.error("Please Enter Note");
    //     return;
    //   }
    // }
    if (part_name && (part_name.toLowerCase().includes("tyre") || part_name.toLowerCase().includes("battery"))) {
      if (!note || note.trim().length < 1) {
        sap.m.MessageBox.error("Please Enter Note");
        return;
      }
    }
    
    if(quantity == 0){
      sap.m.MessageBox.error("Enter Valid Quantity");
      return;
    }
    var workorder = HVICore.getElementById("wo_number").getText();
    if (workorder == "") {
      workorder = HVICore.getElementById("wo_number_execution").getText();
    }

    if (vehicle_number == "") {
      vehicle_number = HVICore.getElementById(
        "vehicle_number_execution"
      ).getText();
    }
    let partFilter = workorderPartJSONArray.filter(function (value, index) {
      return value.part_name == part_name;
    });

    let vehicle_part_id = "";
    let supplier_id = "";
    let supplier_name = "";
    let part_type = "Workshop";
    if (partFilter.length > 0) {
      vehicle_part_id = partFilter[0]["part_id"];
      supplier_id = partFilter[0]["supplier_id"];
      supplier_name = partFilter[0]["supplier_name"];
      part_type = partFilter[0]["part_type"];
    } else {
      sap.m.MessageBox.error(oBundle.getText("Select_Part_From_list"));
      return;
    }
    var added_date = getIndonesianTime();
    var added_by = operatedBy;

    let total_part_cost = parseFloat(quantity) * parseFloat(part_cost);
    let roundPartCost = Math.round(total_part_cost * 100) / 100;
    var tax = oTFWOCost4.getValue();
    if(nullCheckAll(supplier_id)){
        taxFilter = supplier4WJSONData.filter(function(ob,ev){
          return ob.supplier_number == supplier_id;
        });
        if(taxFilter.length > 0 ){
          tax = taxFilter[0]['tax_percentage'];
        }      
    }
 
    let taxCalculated = roundToInt((tax * total_cost) / 100);
   

    let roundTotalCost = roundToInt(total_cost + taxCalculated);

    let InsertParts = {
      master_email: emailUser,
      wo_id: workorderID,
      wo_number: workorder,
      license_number: vehicle_number,
      part_type: part_type,
      vehicle_part_id: vehicle_part_id,
      part_name: part_name,
      parts_qty: quantity,
      task_type: task_type,
      supplier_id: supplier_id,
      supplier_name: supplier_name,
      labor_item_cost: labor_cost + "",
      parts_cost: part_cost + "",
      total_parts_cost: roundPartCost + "",
      total_cost: roundTotalCost + "",
      tax_value: taxCalculated + "",
      added_date: added_date,
      added_by: added_by,
      note: note,
      workshop_name: oxmaint_workshop_name,
      workshop_number: oxmaint_workshop_number,
      ws_group_name: oxmaint_ws_group_name,
      ws_group_number: oxmaint_ws_group_number,
    };

    Car_Workorder_Part.insert(InsertParts).done(function () {
      funWorkorderParts();
      calculateTotalCost();
      clearInpetPartFields();
      sap.m.MessageToast.show("Parts Added successfully.");
      // oDialog.close();
    }, failure);
  },
});
var oPartInputs = new sap.ui.layout.HorizontalLayout({
  // width: "100%",
  content: [
    oInputPartField0,
    oInputPartField1,
    oInputPartField2,
    oInputPartField3,
    oInputPartField4,
    oInputPartField5,
    oInputPartField6,
    oInputPartField7,
  ],
}).addStyleClass("customHorizontalLayout");

function clearInpetPartFields() {
  oInputPartField0.setValue("");
  oInputPartField1.setValue("");
  oInputPartField2.setValue("");
  oInputPartField3.setValue("");
  oInputPartField4.setValue("");
  oInputPartField5.setValue("");
  oInputPartField6.setValue("");
}

function updatetotalCostWOPart() {
  let value0 = roundToInt(oInputPartField2.getValue() || 0);
  let value1 = roundToInt(oInputPartField3.getValue() || 0);
  let value2 = roundToInt(oInputPartField4.getValue() || 0);

  oInputPartField5.setValue;
  oInputPartField5.setValue(value0 * value1 + value2);
}
var objPageLayoutCreateWO = new sap.uxap.ObjectPageLayout({
  headerTitle: new sap.uxap.ObjectPageDynamicHeaderTitle({
    heading: [
      new sap.m.Title({
        id: "wo_number",
        text: "WO1000125",
        level: "H1",
        titleStyle: "H2",
      }),
    ],
    //content: [],
    actions: [btnWO1, btnWO2],
  }),
  sections: [
    new sap.uxap.ObjectPageSection({
      showTitle: false,
      title: oBundle.getText("WO_Details"),
      subSections: new sap.uxap.ObjectPageSubSection({
        blocks: workorderForm1,
      }),
    }),
    //  new sap.uxap.ObjectPageSection({showTitle: false,title:oBundle.getText("Task_Details"),
    //     subSections:new sap.uxap.ObjectPageSubSection({
    //         blocks:oTableWOTaskItem
    // })}),
    new sap.uxap.ObjectPageSection({
      showTitle: false,
      title: oBundle.getText("Service_Needed"),
      subSections: new sap.uxap.ObjectPageSubSection({
        blocks: [
          new sap.ui.layout.VerticalLayout({
            content: [oTablePartsItemWO, oPartInputs],
          }),
        ],
      }),
    }),
    // new sap.uxap.ObjectPageSection({showTitle: false,title:oBundle.getText("Labor_Details"),
    //     subSections:new sap.uxap.ObjectPageSubSection({
    //         blocks:oTableLaborItemWO
    // })}),//To Remove
    new sap.uxap.ObjectPageSection({
      showTitle: false,
      title: oBundle.getText("Remark_Attachments"),
      subSections: new sap.uxap.ObjectPageSubSection({
        blocks: [oTableWORemark],
      }),
    }),

    new sap.uxap.ObjectPageSection({
      showTitle: false,
      title: oBundle.getText("Cost"),
      subSections: new sap.uxap.ObjectPageSubSection({
        blocks: [
          // oTableWOAdditionalCost
          oTableWOAttachment,
          workorderForm2,
        ],
      }),
    }),
  ],
}); //.addStyleClass("objectPageLayoutPadding");

/*var workorderArchivePage = new sap.m.Page("wo_archive_page", {
        title:oBundle.getText("Archive_Workorder"),
        showHeader:true,
        enableScrolling:true,
        showNavButton: true,
        navButtonPress: function(){ oAppWorkOrder.backToTop(); },
        content : []
    });
*/
/*var workorderHeader = new sap.m.OverflowToolbar({width: 'auto',design: "Transparent",
     content: [
            new sap.m.Button({
                type: sap.m.ButtonType.Emphasized,
                icon: "sap-icon://add-equipment",
                text: oBundle.getText("Create_Workorder"),
                press: function () {
                    addPageSrc = "1";
                    oAppWoRequest.removePage(addWOPage);
                    oAppWorkOrder.addPage(addWOPage);
                    oAppWorkOrder.to("add_wo_page");
                    addWOPage.setTitle(oBundle.getText("Maintenance_Workorder"));
                    iniWorkOrder();
                    btnWO1.setText(oBundle.getText("Create_WorkOrder"));
                }
            }),
           new sap.m.ToolbarSpacer(),
		]
 });*/

/*var workorderPage = new sap.m.Page("wo_page",{
        title:oBundle.getText("Workorder_History"),showHeader:false,
        enableScrolling:true,content : [oTableWorkorder]
    });*/

var oAppWorkOrder = new sap.m.App({ height: "100%", initialPage: "wo_page" });

var addPageSrc = "1";

var addWOPage = new sap.m.Page("add_wo_page", {
  title: oBundle.getText("Create_WorkOrder"),
  showNavButton: true,
  navButtonPress: function () {
    if (addPageSrc == "2") {
      oAppWoRequest.backToTop();
    } else {
      clearWOfield();
      oAppWorkOrder.backToTop();
    }
  },
  content: [objPageLayoutCreateWO],
});


/*
var oTableCompletedWorkorder = oTableWorkorder.clone();

var workorderSearchComplted = new sap.m.SearchField({
  placeholder: oBundle.getText("Search"),
  width: "300px",
  selectOnFocus: false,
  layoutData: new sap.ui.layout.GridData({ span: "L4 M6 S12" }),
  search: function (event) {
    if (event.getParameter("clearButtonPressed")) {
      workorderSearchComplted.setValue("");
    } 
  },
  liveChange: function (event) {
    var oBinding = oTableCompletedWorkorder.getBinding("items");
    var searchStr = this.getValue();
    if (oBinding) {
      var oFilters = [
        new sap.ui.model.Filter( "wo_number",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter( "wo_title", sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("wo_memo",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("city",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("license_number",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("vehicle_name",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("chassis_number",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("engine_number",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("model",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("make",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("vehicle_color",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("rental_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("leasing_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("assigned_id",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("ws_group_name",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("ws_group_number",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("workshop_name",sap.ui.model.FilterOperator.Contains,searchStr),
        new sap.ui.model.Filter("workshop_number",sap.ui.model.FilterOperator.Contains,searchStr),
      ];
      filterObjWo = new sap.ui.model.Filter(oFilters, false);
      oBinding.filter(filterObjWo);
    } else {
      oBinding.filter([]);
    }
  },
});

oTableCompletedWorkorder.setHeaderToolbar(
  new sap.m.Toolbar({
    content: [
      new sap.m.Label({ text: oBundle.getText("Completed_Workorder") }),
      new sap.m.ToolbarSpacer(),
      workorderSearchComplted,
    ],
  })
);


var oTableWorkorderDue = oTableWorkorder.clone();

var workorderDueSearch = new sap.m.SearchField({
  placeholder: oBundle.getText("Search"),
  width: "300px",
  selectOnFocus: false,
  layoutData: new sap.ui.layout.GridData({ span: "L4 M6 S12" }),
  search: function (event) {
    if (event.getParameter("clearButtonPressed")) {
      workorderDueSearch.setValue("");
    } 
  },
  liveChange: function (event) {
    var oBinding = oTableWorkorderDue.getBinding("items");
    var searchStr = this.getValue();
    if (oBinding) {
      var oFilters = [
        new sap.ui.model.Filter(
          "wo_number",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "wo_title",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "wo_memo",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "city",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "license_number",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "vehicle_name",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "chassis_number",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "engine_number",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "assigned_name",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "model",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "make",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "vehicle_color",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "rental_company_name",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "leasing_company_name",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "assigned_id",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
        new sap.ui.model.Filter(
          "assigned_name",
          sap.ui.model.FilterOperator.Contains,
          searchStr
        ),
      ];
      filterObjWo = new sap.ui.model.Filter(oFilters, false);
      oBinding.filter(filterObjWo);
    } else {
      oBinding.filter([]);
    }
  },
});

oTableWorkorderDue.setHeaderToolbar(
  new sap.m.Toolbar({
    content: [
      new sap.m.Label({ text: oBundle.getText("Workorder_OverDue") }),
      new sap.m.ToolbarSpacer(),
      workorderDueSearch,
    ],
  })
);*/


//Need Verification WO
var oTable4WVerificationWO = oTableWorkorder.clone();
oTable4WVerificationWO.destroyHeaderToolbar();
oTable4WVerificationWO.setHeaderToolbar(
  new sap.m.Toolbar({
    content: [
      new sap.m.Button({
        id:"createWorkorderID2",
        type: sap.m.ButtonType.Emphasized,
        icon: "sap-icon://add-equipment",
        text: oBundle.getText("Create_Workorder"),
        press: function () {
                if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('create_work_order') != -1)){
                    if(workshop4WJSONData.length > 0){

                        addPageSrc = "1";
                        // oAppWoRequest.removePage(addWOPage);
                        oAppWorkOrder.addPage(addWOPage);
                        oAppWorkOrder.to("add_wo_page");
                        addWOPage.setTitle(oBundle.getText("Maintenance_Workorder"));
                        iniWorkOrder();
                        workorderForm1.getFormContainers()[0].getFormElements()[5].setVisible(false);
                        btnWO1.setText(oBundle.getText("Create_WorkOrder"));
                    }else{
                        sap.m.MessageBox.error("Please wait while the Workshop Data is loading.");
                    }
                }else{
                    sap.m.MessageToast.show("Create Access not provided.");
                }
           
        }
    }),
      new sap.m.ToolbarSpacer(),
      new sap.m.SearchField({
        placeholder: oBundle.getText("Search"),
        width: "300px",
        liveChange: function (event) {
          var oBinding = oTable4WVerificationWO.getBinding("items");
          var searchStr = this.getValue();
          if (oBinding) {
            var oFilters = [
              new sap.ui.model.Filter( "wo_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter( "wo_title", sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("wo_memo",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("city",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("license_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("chassis_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("engine_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("model",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("make",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_color",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("rental_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("leasing_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_id",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_number",sap.ui.model.FilterOperator.Contains,searchStr),
            ];
            var filterObj = new sap.ui.model.Filter(oFilters, false);
            oBinding.filter(filterObj);
          } else {
            oBinding.filter([]);
          }
        },
      }),
      new sap.m.Button({
        icon: "sap-icon://filter",
        press: function () {
          funMultiFilterOpenWO(
            1,
            grabVerificationWOJSONArray,
            oTable4WVerificationWO,
            workorderTemplate
          );
        },
      }),
      // new sap.m.Button({
      //     type: sap.m.ButtonType.Emphasized,
      //     text:oBundle.getText("Multi Filter"),
      //     icon: 'sap-icon://add-filter',
      //     press: function () {
      //         funMultiFilterOpenWO(grabRejectWOJSONArray, oTable4WRejectWO);
      //     }
      // }),
    ],
  })
);


//Reject WO
var oTable4WRejectWO = oTableWorkorder.clone();
oTable4WRejectWO.destroyHeaderToolbar();
oTable4WRejectWO.setHeaderToolbar(
  new sap.m.Toolbar({
    content: [
      new sap.m.ToolbarSpacer(),
      new sap.m.SearchField({
        placeholder: oBundle.getText("Search"),
        width: "300px",
        liveChange: function (event) {
          var oBinding = oTable4WRejectWO.getBinding("items");
          var searchStr = this.getValue();
          if (oBinding) {
            var oFilters = [
              new sap.ui.model.Filter( "wo_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter( "wo_title", sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("wo_memo",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("city",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("license_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("chassis_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("engine_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("model",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("make",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_color",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("rental_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("leasing_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_id",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_number",sap.ui.model.FilterOperator.Contains,searchStr),
            ];
            var filterObj = new sap.ui.model.Filter(oFilters, false);
            oBinding.filter(filterObj);
          } else {
            oBinding.filter([]);
          }
        },
      }),
      new sap.m.Button({
        icon: "sap-icon://filter",
        press: function () {
          funMultiFilterOpenWO(
            1,
            grabRejectWOJSONArray,
            oTable4WRejectWO,
            workorderTemplate
          );
        },
      }),
      // new sap.m.Button({
      //     type: sap.m.ButtonType.Emphasized,
      //     text:oBundle.getText("Multi Filter"),
      //     icon: 'sap-icon://add-filter',
      //     press: function () {
      //         funMultiFilterOpenWO(grabRejectWOJSONArray, oTable4WRejectWO);
      //     }
      // }),
    ],
  })
);

//Open WO
var oTable4WOpenWO = oTableWorkorder.clone();
oTable4WOpenWO.destroyHeaderToolbar();
oTable4WOpenWO.setHeaderToolbar(
  new sap.m.Toolbar({
    content: [
      new sap.m.ToolbarSpacer(),
      new sap.m.SearchField({
        placeholder: oBundle.getText("Search"),
        width: "300px",
        liveChange: function (event) {
          var oBinding = oTable4WOpenWO.getBinding("items");
          var searchStr = this.getValue();
          if (oBinding) {
            var oFilters = [
              new sap.ui.model.Filter( "wo_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter( "wo_title", sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("wo_memo",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("city",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("license_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("chassis_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("engine_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("model",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("make",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_color",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("rental_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("leasing_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_id",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_number",sap.ui.model.FilterOperator.Contains,searchStr),
            ];
            var filterObj = new sap.ui.model.Filter(oFilters, false);
            oBinding.filter(filterObj);
          } else {
            oBinding.filter([]);
          }
        },
      }),
      new sap.m.Button({
        icon: "sap-icon://filter",
        press: function () {
          funMultiFilterOpenWO(
            1,
            grabOpenWOJSONArray,
            oTable4WOpenWO,
            workorderTemplate
          );
        },
      }),
      // new sap.m.Button({
      //     type: sap.m.ButtonType.Emphasized,
      //     text:oBundle.getText("Multi Filter"),
      //     icon: 'sap-icon://add-filter',
      //     press: function () {
      //         funMultiFilterOpenWO(grabOpenWOJSONArray, oTable4WOpenWO);
      //     }
      // }),
    ],
  })
);

//Complete WO
var oTable4WCompletedWO = oTableWorkorder.clone();
oTable4WCompletedWO.destroyHeaderToolbar();
oTable4WCompletedWO.setHeaderToolbar(
  new sap.m.Toolbar({
    content: [
      new sap.m.Button({
        id: "createIdInvoiceBtn",
        text: "+ " + oBundle.getText("Create_Invoice"),
        type: sap.m.ButtonType.Emphasized,
        press: function () {
          createGrabInvoiceHeader(1);
          var oModel = new sap.ui.model.json.JSONModel();
          oModel.setData({ modelData: [] });
          oTablepartsInvoice.setModel(oModel);
          oTablepartsInvoice.bindItems({
            path: "/modelData",
            template: partsInvoiceTemplate,
          });
        },
      }),
      new sap.m.ToolbarSpacer(),
      new sap.m.SearchField({
        placeholder: oBundle.getText("Search"),
        width: "300px",
        liveChange: function (event) {
          var oBinding = oTable4WCompletedWO.getBinding("items");
          var searchStr = this.getValue();
          if (oBinding) {
            var oFilters = [
              new sap.ui.model.Filter( "wo_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter( "wo_title", sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("wo_memo",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("city",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("license_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("chassis_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("engine_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("model",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("make",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_color",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("rental_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("leasing_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_id",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_number",sap.ui.model.FilterOperator.Contains,searchStr),
            ];
            var filterObj = new sap.ui.model.Filter(oFilters, false);
            oBinding.filter(filterObj);
          } else {
            oBinding.filter([]);
          }
        },
      }),
      new sap.m.Button({
        icon: "sap-icon://filter",
        press: function () {
          funMultiFilterOpenWO(
            1,
            grabCompletedWOJSONArray,
            oTable4WCompletedWO,
            workorderTemplate
          );
        },
      }),
      // new sap.m.Button({
      //     type: sap.m.ButtonType.Emphasized,
      //     text:oBundle.getText("Multi Filter"),
      //     icon: 'sap-icon://add-filter',
      //     press: function () {
      //         funMultiFilterOpenWO(grabCompletedWOJSONArray, oTable4WCompletedWO);
      //     }
      // }),
    ],
  })
);

//Closed WO
var oSelectInvocieStatus = new sap.m.Select({
  width: "200px",
  change: function(oEvent) {
      var selectedKey = oEvent.getSource().getSelectedKey();
      applyClosedTableFilter(selectedKey);
  }
});

oSelectInvocieStatus.addItem(new sap.ui.core.Item({ key: "ALL", text: "All" }));
oSelectInvocieStatus.addItem(new sap.ui.core.Item({ key: "OPEN", text: "Open Invoice" }));
oSelectInvocieStatus.addItem(new sap.ui.core.Item({ key: "REVIEW", text: "Under Review" }));
function applyClosedTableFilter(key) {
  var oBinding = oTable4WClosedWO.getBinding("items");
  var aFilters = [];

  if (key === "OPEN") {
      // Filter where invoice_number is not empty
      aFilters.push(new sap.ui.model.Filter("invoice_number", sap.ui.model.FilterOperator.EQ, ""));
  } else if (key === "REVIEW") {
      aFilters.push(new sap.ui.model.Filter("invoice_number", sap.ui.model.FilterOperator.NE, ""));
  }

  oBinding.filter(aFilters);
}

var oTable4WClosedWO = oTableWorkorder.clone();
oTable4WClosedWO.destroyHeaderToolbar();
oTable4WClosedWO.setHeaderToolbar(
  new sap.m.Toolbar({
    content: [
      new sap.m.ToolbarSpacer(),
      oSelectInvocieStatus,
      new sap.m.SearchField({
        placeholder: oBundle.getText("Search"),
        width: "300px",
        liveChange: function (event) {
          var oBinding = oTable4WClosedWO.getBinding("items");
          var searchStr = this.getValue();
          if (oBinding) {
            var oFilters = [
              new sap.ui.model.Filter( "wo_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter( "wo_title", sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("wo_memo",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("city",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("license_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("chassis_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("engine_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("model",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("make",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_color",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("rental_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("leasing_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_id",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_number",sap.ui.model.FilterOperator.Contains,searchStr),
            ];
            var filterObj = new sap.ui.model.Filter(oFilters, false);
            oBinding.filter(filterObj);

             // Additional logic for external call
             if((searchStr.startsWith("4W2") || searchStr.startsWith("2W2")) && searchStr.length > 13) {
              setTimeout(function () {
                  var items = oTable4WClosedWO.getItems(); //For All table
                  var visibleItems = items.filter(function (item) {
                      return item.getVisible(); // Only visible items
                  });
                  // console.log("hello")
                  if (visibleItems.length === 0) {
                      busyDialog.open();
                      sap.m.MessageToast.show('Getting Data From DB.');
                      funGetWorkorderDetailsFromDb(searchStr, 'CLOSED');//grabGrnWOJSONArray, oTable4WGrnWO, workorderTemplate,
                  }
              }, 300); // Small delay to let filtering apply
            }
          } else {
            oBinding.filter([]);
          }
        },
      }),
      new sap.m.Button({
        icon: "sap-icon://filter",
        press: function () {
          funMultiFilterOpenWO(
            1,
            grabClosedWOJSONArray,
            oTable4WClosedWO,
            workorderTemplate
          );
        },
      }),
      // new sap.m.Button({
      //     type: sap.m.ButtonType.Emphasized,
      //     text:oBundle.getText("Multi Filter"),
      //     icon: 'sap-icon://add-filter',
      //     press: function () {
      //         funMultiFilterOpenWO(grabClosedWOJSONArray, oTable4WClosedWO);
      //     }
      // }),
    ],
  })
);

//GRN WO
var oTable4WGrnWO = oTableWorkorder.clone();
oTable4WGrnWO.destroyHeaderToolbar();
oTable4WGrnWO.setHeaderToolbar(
  new sap.m.Toolbar({
    content: [
      new sap.m.ToolbarSpacer(),
      new sap.m.SearchField({
        placeholder: oBundle.getText("Search"),
        width: "300px",
        liveChange: function (event) {
          var oBinding = oTable4WGrnWO.getBinding("items");
          var searchStr = this.getValue();
          if (oBinding) {
            var oFilters = [
              new sap.ui.model.Filter( "wo_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter( "wo_title", sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("wo_memo",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("city",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("license_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("chassis_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("engine_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("model",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("make",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_color",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("rental_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("leasing_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_id",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_number",sap.ui.model.FilterOperator.Contains,searchStr),
            ];
            var filterObj = new sap.ui.model.Filter(oFilters, false);
            oBinding.filter(filterObj);

            // Additional logic for external call
            if((searchStr.startsWith("4W2") || searchStr.startsWith("2W2")) && searchStr.length > 13) {
              setTimeout(function () {
                  var items = oTable4WGrnWO.getItems(); //For All table
                  var visibleItems = items.filter(function (item) {
                      return item.getVisible(); // Only visible items
                  });
                  // console.log("hello")
                  if (visibleItems.length === 0) {
                      busyDialog.open();
                      sap.m.MessageToast.show('Getting Data From DB.');
                      funGetWorkorderDetailsFromDb(searchStr, 'GRN');//grabGrnWOJSONArray, oTable4WGrnWO, workorderTemplate,
                  }
              }, 300); // Small delay to let filtering apply
            }


          } else {
            oBinding.filter([]);
          }
        },
      }),
      new sap.m.Button({
        icon: "sap-icon://filter",
        press: function () {
          funMultiFilterOpenWO(
            1,
            grabGrnWOJSONArray,
            oTable4WGrnWO,
            workorderTemplate
          );
        },
      }),
      // new sap.m.Button({
      //     type: sap.m.ButtonType.Emphasized,
      //     text:oBundle.getText("Multi Filter"),
      //     icon: 'sap-icon://add-filter',
      //     press: function () {
      //         funMultiFilterOpenWO(grabGrnWOJSONArray, oTable4WGrnWO);
      //     }
      // }),
    ],
  })
);

//Cancelled WO
var oTable4WCancelledWO = oTableWorkorder.clone();
oTable4WCancelledWO.destroyHeaderToolbar();
oTable4WCancelledWO.setHeaderToolbar(
  new sap.m.Toolbar({
    content: [
      new sap.m.ToolbarSpacer(),
      new sap.m.SearchField({
        placeholder: oBundle.getText("Search"),
        width: "300px",
        liveChange: function (event) {
          var oBinding = oTable4WCancelledWO.getBinding("items");
          var searchStr = this.getValue();
          if (oBinding) {
            var oFilters = [
              new sap.ui.model.Filter( "wo_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter( "wo_title", sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("wo_memo",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("city",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("license_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("chassis_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("engine_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("model",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("make",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_color",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("rental_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("leasing_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_id",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_number",sap.ui.model.FilterOperator.Contains,searchStr),
            ];
            var filterObj = new sap.ui.model.Filter(oFilters, false);
            oBinding.filter(filterObj);
          } else {
            oBinding.filter([]);
          }
        },
      }),
      new sap.m.Button({
        icon: "sap-icon://filter",
        press: function () {
          funMultiFilterOpenWO(
            1,
            grabCancelledWOJSONArray,
            oTable4WCancelledWO,
            workorderTemplate
          );
        },
      }),
      // new sap.m.Button({
      //     type: sap.m.ButtonType.Emphasized,
      //     text:oBundle.getText("Multi Filter"),
      //     icon: 'sap-icon://add-filter',
      //     press: function () {
      //         funMultiFilterOpenWO(grabCancelledWOJSONArray, oTable4WCancelledWO);
      //     }
      // }),
    ],
  })
);


//All Workorder
var oTable4WAllWO = oTableWorkorder.clone();
var oTable4WAllWOTemplate = workorderTemplate.clone()
// oTable4WAllWO.removeColumn(0);
oTable4WAllWOTemplate.removeCell(0);
oTable4WAllWOTemplate.insertCell(new sap.m.Button({
  type: "Emphasized",
  icon: "sap-icon://action",
  text: "",
  press: function (event) {
      var model = this.getModel();
      var path = event.getSource().getBindingContext().getPath();
      var obj = model.getProperty(path);
      displayMenuWorkOrder(event, obj);
  }
}), 0);
oTable4WAllWO.destroyHeaderToolbar();
oTable4WAllWO.setHeaderToolbar(
  new sap.m.Toolbar({
    content: [
      new sap.m.ToolbarSpacer(),
      new sap.m.SearchField({
        placeholder: oBundle.getText("Search"),
        width: "300px",
        liveChange: function (event) {
          var oBinding = oTable4WAllWO.getBinding("items");
          var searchStr = this.getValue();
          if (oBinding) {
            var oFilters = [
              new sap.ui.model.Filter( "wo_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter( "wo_title", sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("wo_memo",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("city",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("license_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("chassis_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("engine_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("model",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("make",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_color",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("rental_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("leasing_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_id",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("ws_group_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("workshop_number",sap.ui.model.FilterOperator.Contains,searchStr),
            ];
            var filterObj = new sap.ui.model.Filter(oFilters, false);
            oBinding.filter(filterObj);

              // Additional logic for external call
              if((searchStr.startsWith("4W2") || searchStr.startsWith("2W2")) && searchStr.length > 13) {
                setTimeout(function () {
                    var items = oTable4WAllWO.getItems(); //For All table
                    var visibleItems = items.filter(function (item) {
                        return item.getVisible(); // Only visible items
                    });
                    // console.log("hello")
                    if (visibleItems.length === 0) {
                        busyDialog.open();
                        sap.m.MessageToast.show('Getting Data From DB.');
                        funGetWorkorderDetailsFromDb(searchStr,'ALLWO');
                    }
                }, 300); // Small delay to let filtering apply
              }

          } else {
            oBinding.filter([]);
          }
        },
      }),
      new sap.m.Button({
        icon: "sap-icon://filter",
        press: function () {
          funMultiFilterOpenWO(
            2,
            // grabAllWOJSONArray,
            grab4WAllWoJSONArray,
            oTable4WAllWO,
            oTable4WAllWOTemplate
          );
        },
      }),
      // new sap.m.Button({
      //     type: sap.m.ButtonType.Emphasized,
      //     text:oBundle.getText("Multi Filter"),
      //     icon: 'sap-icon://add-filter',
      //     press: function () {
      //         funMultiFilterOpenWO(grabCancelledWOJSONArray, oTable4WCancelledWO);
      //     }
      // }),
    ],
  })
);






var oAppWorkOrderPageLayout = new sap.uxap.ObjectPageLayout({
  headerContentPinnable: false,
  preserveHeaderStateOnScroll: true,
  useIconTabBar: true,
  toggleHeaderOnTitleClick: true,
  headerTitle: new sap.uxap.ObjectPageDynamicHeaderTitle({
    heading: [
      new sap.m.Title({
        text: oBundle.getText("Workorders"),
        level: "H1",
        titleStyle: "H2",
      }),
    ],
    actions: [
      // new sap.m.Input({
      //     placeholder: "Search Work Order for Status",
      //     width: "300px",
      //     id: "searchInput" // Assign an ID to access it later
      // }),
      // new sap.m.Button({
      //     text: oBundle.getText("Search"),
      //     type: sap.m.ButtonType.Emphasized,
      //     icon: "sap-icon://search",
      //     press: function () {
      //         var oInput = sap.ui.getCore().byId("searchInput");
      //         var oStatusText = sap.ui.getCore().byId("statusText");
      //         var workOrderID = oInput.getValue().trim();
              
             
      //         if (workOrderID) {
      //           var foundOrder = grab4WAllWoJSONArray.filter(order => order.wo_number == workOrderID);
                
      //           if (foundOrder) {
      //               oStatusText.setText("Status: " + foundOrder[0].wo_status);
      //           } else {
      //               oStatusText.setText("Work Order Not Found");
      //           }
      //           oStatusText.setVisible(true);
      //         } else {
      //             oStatusText.setText("");
      //             oStatusText.setVisible(true);
      //         }
      //     }
      // }),
      // new sap.m.Text({
      //     text: "",
      //     visible: false, // Initially hidden
      //     id: "statusText" // Assign an ID to update dynamically
      // })
  ]
  
  }),
  sections: [
    new sap.uxap.ObjectPageSection({
      id: "GW10", showTitle: true, title: oBundle.getText("All"), subSections: new sap.uxap.ObjectPageSubSection({
        blocks: [oTable4WAllWO],
      }),
    }),
    new sap.uxap.ObjectPageSection({
      id: "GWO11", showTitle: true, title: oBundle.getText("Need_Verification"), subSections: new sap.uxap.ObjectPageSubSection({
        blocks: [oTable4WVerificationWO],
      }),
    }),
    new sap.uxap.ObjectPageSection({
      id: "GWO1", showTitle: true, title: oBundle.getText("Pending_Approval"), subSections: new sap.uxap.ObjectPageSubSection({
        blocks: [oTableWorkorder],
      }),
    }),
    new sap.uxap.ObjectPageSection({
      id: "GWO2", showTitle: true, title: oBundle.getText("Open"), subSections: new sap.uxap.ObjectPageSubSection({
        blocks: [oTable4WOpenWO],
      }),
    }),
    new sap.uxap.ObjectPageSection({
      id: "GWO3", showTitle: true, title: oBundle.getText("Completed"), subSections: new sap.uxap.ObjectPageSubSection({
        blocks: [oTable4WCompletedWO],
      }),
    }),
    new sap.uxap.ObjectPageSection({
      id: "GWO4", showTitle: true, title: oBundle.getText("Closed"), subSections: new sap.uxap.ObjectPageSubSection({
        blocks: [oTable4WClosedWO],
      }),
    }),
    new sap.uxap.ObjectPageSection({
      id: "GWO5", showTitle: true, title: oBundle.getText("GRN"), subSections: new sap.uxap.ObjectPageSubSection({
        blocks: [oTable4WGrnWO],
      }),
    }),
    new sap.uxap.ObjectPageSection({
      id: "GWO6", showTitle: true, title: oBundle.getText("Reject"), subSections: new sap.uxap.ObjectPageSubSection({
        blocks: [oTable4WRejectWO],
      }),
    }),
    new sap.uxap.ObjectPageSection({
      id: "GWO7", showTitle: true, title: oBundle.getText("Cancelled"), subSections: new sap.uxap.ObjectPageSubSection({
        blocks: [oTable4WCancelledWO],
      }),
    }),
    new sap.uxap.ObjectPageSection({
      id: "GWO8", showTitle: true, title: oBundle.getText("Archive"), subSections: new sap.uxap.ObjectPageSubSection({
        blocks: [ArchiveWOTable],
      }),
    }),
    new sap.uxap.ObjectPageSection({
      id: "GWO9",showTitle: true,title: oBundle.getText("Open_Invoice"),subSections: new sap.uxap.ObjectPageSubSection({
        blocks: [oTable4WInvoiceOpen],
      }),
    }),
    // new sap.uxap.ObjectPageSection({id:"GW10", showTitle: true, title: oBundle.getText("Reopen Invoice"),
    //     subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTable4WInvoiceReopen]})
    // }),

    // new sap.uxap.ObjectPageSection({id:"wo4", showTitle: true, title: oBundle.getText("Overdue"),
    //     subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTableWorkorderDue]})}),

    // new sap.uxap.ObjectPageSection({id:"wo2", showTitle: true, title: oBundle.getText("Completed"),
    //     subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTableCompletedWorkorder]})
    // }),
  ],

  navigate: function (event) {
    var mID = event.getParameter("section").getId();

    if (mID == "GWO1") {
      getPendingWorkorder(); // Pending
    } else if (mID == "GWO2") {
      getOpenWorkorder();//Open 
    } else if (mID == "GWO3") {
      getCompletedWorkorder(); //Completed
    } else if (mID == "GWO4") {
      getClosedWorkorder();      //Closed
    } else if (mID == "GWO5") {
      getGrnWorkorder();//GRN
    } else if (mID == "GWO6") {
      getRejectWorkorder();//Reject
    } else if (mID == "GWO7") {
      getCancelledWorkorder();//Cancelled
    } else if (mID == "GWO8") {
      funGetArchiveWO();//Archive
    } else if (mID == "GWO9") {
      get4WOpenInvoice(); //Open Invoice
      if(completeClosedTemp){
        getCompletedWorkorder();
        getClosedWorkorder();
      }
    } else if (mID == "GW10") {
      getAllWorkorderDetails();
      //Reopen Invoice
      // get4WReopenInvoice();
    } else if(mID == "GWO11"){
      getVerificationWorkorder();
    }
  },
});

oAppWorkOrder.addPage(oAppWorkOrderPageLayout);
/*
function funGetCompletedWO() {
  oTableCompletedWorkorder.setBusy(true);

  if (hvi_location_id == "Default-001") {
    HVI_Workorder.where(filterQueryWorkorderCompleted1, emailUser)
      .take(1000)
      .orderByDescending("createdAt")
      .read()
      .done(function (result) {
        var results = funFilterJsonByVehicleAnsUser(result);

        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        oTableCompletedWorkorder.setModel(oModel);
        oTableCompletedWorkorder.bindItems({
          path: "/modelData",
          template: workorderTemplate,
        });
        oTableCompletedWorkorder.setBusy(false);
      });
  } else {
    HVI_Workorder.where(
      filterQueryWorkorderCompleted2,
      emailUser,
      hvi_location_id
    )
      .take(1000)
      .orderByDescending("createdAt")
      .read()
      .done(function (result) {
        var results = funFilterJsonByVehicleAnsUser(result);

        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        oTableCompletedWorkorder.setModel(oModel);
        oTableCompletedWorkorder.bindItems({
          path: "/modelData",
          template: workorderTemplate,
        });
        oTableCompletedWorkorder.setBusy(false);
      });
  }

  // HVI_Workorder.where(queryWorkorder(5)).includeTotalCount().take(1000).orderByDescending("__createdAt").read().done(function (result) {

  //});
}
*/
function chekWOValidation() {
  var wo_number = HVICore.getElementById("wo_number").getText();
  var wo_title = wo_title_field.getValue();
  let license_number = oTFWOV1.getValue();

  if (wo_number.trim() == "") {
    sap.m.MessageBox.error(
      oBundle.getText("Workorder_number_field_can_not_be_empty")
    );
    return;
  }

  if (validation(wo_title, oBundle.getText("Workorder_Title"))) {
    return;
  }

  if (license_number.trim() == "") {
    sap.m.MessageBox.error(oBundle.getText("Please_select_vehicle"));
    return;
  }

  if (!nullCheck(oTFWOV4.getValue()) || minusCheck(oTFWOV4.getValue())) {
    sap.m.MessageBox.error(oBundle.getText("Enter_valid_odometer_reading"));
    return;
  }
  if (oTFWOV4.getValue() < 1) {
    sap.m.MessageBox.error(oBundle.getText("Enter_valid_odometer_reading"));
    return;
  }

  var regular_service = serviceWoCB.getValue();
  var city = cityTypeDB.getValue();
  var service_km = serviceKm.getValue();

  if (city == "Select City") {
    sap.m.MessageBox.error(oBundle.getText("Please_Select_City"));
    return;
  }

  if (regular_service == "Yes") {
    if (validateNumber(service_km, oBundle.getText("Service_Km"))) {
      return;
    }
    if(service_km < 1){
      sap.m.MessageBox.error("Enter valid Service KM");
      return;
    }
  }

  var ws_group_number = "";
  var ws_group_name = "";
  var ws_group_woTokenList = oTFWOV6.getTokens();

  for (var j = 0; j < ws_group_woTokenList.length; j++) {
    if (ws_group_number == "") {
      ws_group_number = ws_group_woTokenList[j].getKey();
      ws_group_name = ws_group_woTokenList[j].getText();
    }
  }

  let workshop_number = "";
  let workshop_name = "";
  let workshopWoTokenList = oTFWOV7.getTokens();

  for (var j = 0; j < workshopWoTokenList.length; j++) {
    if (workshop_number == "") {
      workshop_number = workshopWoTokenList[j].getKey();
      workshop_name = workshopWoTokenList[j].getText();
    }
  }


  if(ws_group_number == ""){
      sap.m.MessageBox.error("Select Workshop Group Name");
      return;
  }
  if(workshop_number == ""){
      sap.m.MessageBox.error("Select Workshop Name");
      return;
  }

  /* var getVehicle = vehicleJSONArray.filter(function(obj, index){
            return (obj.vehicle_serial === vehicle_number);
        });
    
          var meterReading = getVehicle[0]['odometer'];

         if (!nullCheck(oTFWOV4.getValue()) || minusCheck(oTFWOV4.getValue())) {
            sap.m.MessageBox.error(oBundle.getText("Enter valid meter reading"));
            return;
         }
         if (parseFloat(oTFWOV4.getValue()) < parseFloat(meterReading[0])) {
            sap.m.MessageBox.error(oBundle.getText("Meter reading can not be less than previous reading"));
            return;
         }*/

  var objPart = oTablePartsItemWO.getItems();
  if (objPart.length < 1) {
    sap.m.MessageBox.error(oBundle.getText("Add_at_least_one_service_needed"));
    return;
  }

  oBusyDialogWO.open();

  getFinalWorkorderNumber();
  // $.ajax({
  //     type: "POST",
  //     url: "https://grab-api.azurewebsites.net/V01/Grab_index.asmx/get_and_update_wo_index",
  //     data: {
  //         "master_email": emailUser
  //     },
  //     success: function (data) {

  //         console.log("avd:", data['wo_number']);

  //        var index = "000000"+(parseInt(data['wo_number']));
  //        var index1 = index.substr(-6);

  //         var wo_number = "4W"+getIndexDate()+index1;

  //         console.log(wo_number)

  //         createWorkOrderSubmit(wo_number);

  //     }, error: function (xhr, status, error) {
  //         oBusyDialogWO.close();
  //         sap.m.MessageBox.error("Operation failed -index error");
  //     }
  // });
}

var workorderID = "";
var inspectionOBJ = [];
var scheduleOBJ = [];
var inspectionWO = false;
var scheduleWO = false;

function iniWorkOrder(createSrc, obj) {
  workorderID = "WO" + new Date().getTime() + "";
  clearWOfield();

  oTFWOV1.setEditable(true);
  inspectionOBJ = [];
  scheduleOBJ = [];
  inspectionWO = false;
  scheduleWO = false;
  inspectionLinkInput.setEnabled(true);
  //chekWOValidation(1,workorderID);
  getWOIndex(HVICore.getElementById("wo_number"));
  if (nullCheckAll(oxmaint_ws_group_number)) {
    oTFWOV6.addToken(
      new sap.m.Token({
        key: oxmaint_ws_group_number,
        text: oxmaint_ws_group_name,
      })
    );
  }
  if (nullCheckAll(oxmaint_workshop_number)) {
    oTFWOV7.addToken(
      new sap.m.Token({
        key: oxmaint_workshop_number,
        text: oxmaint_workshop_name,
      })
    );

    var wsFilter = workshop4WJSONData.filter(function (a, b) {
      return a.workshop_number == oxmaint_workshop_number;
    });

    oTFWOCost4.setValue(wsFilter[0]["tax_percentage"]);
  }
  
  if (allowedRoles.includes(oxmaint_role)) {
    oTFWOV6.setEnabled(true);
    oTFWOV7.setEnabled(true);
  }else{
    oTFWOV6.setEnabled(false);
    oTFWOV7.setEnabled(false);
  }
  if (createSrc == "Dashboard") {
    oTFWOV1.setEditable(false);
    inspectionWO = true;
    inspectionOBJ = obj;
    inspectionLinkInput.addToken(
      new sap.m.Token({
        key: obj["inspection_date"],
        text: obj["report_number"],
      })
    );

    getVehicleByLicenseNumberWO(obj["license_number"]);

    // var getVehicle = vehicle4WJSONData.filter(function (vObj, index) {
    //   return vObj.license_number === obj["license_number"];
    // });

    // if (getVehicle.length > 0) {
    //   oTFWOV0.setValue(getVehicle[0]["id"]);
    //   oTFWOV1.setValue(getVehicle[0]["license_number"]);
    //   oTFWOV8.setValue(getVehicle[0]["chassis_number"]);
    //   oTFWOV9.setValue(getVehicle[0]["engine_number"]);
    //   oTFWOV10.setValue(getVehicle[0]["make"]);
    //   oTFWOV3.setValue(getVehicle[0]["model"]);
    //   oTFWOV11.setValue(getVehicle[0]["vehicle_color"]);
    //   oTFWOV12.setValue(getVehicle[0]["rental_company_name"]);
    //   oTFWOV13.setValue(getVehicle[0]["leasing_company_name"]);
    //   oTFWOV14.setValue(getVehicle[0]["transmission"]);
    //   filterWorkorderPartWorkshop();

    // }
    Car_Inspection_Item.where({
      master_email: emailUser,
      inspection_id: obj["id"],
    })
      .read()
      .done(function (results) {
        if (results.length > 0) {
          results.forEach(function (item, index) {
            var newItem = new sap.ui.core.ListItem({
              key: item.task_name, // Use array index + 1 as key
              text: item.task_name, // Use array value as text
            });
            oInputPartField0.addItem(newItem);
          });
        }
      });

    // oTFWOV0.setValue(obj['id']);
    // oTFWOV1.setValue(obj['vehicle_serial']);
    // oTFWOV2.setValue(obj['vehicle_name']);
    // oTFWOV3.setValue(obj['vehicle_model']);
    // WOTypeDB.setSelectedKey('11');
    var meterReading = obj["meter_reading"];
    var meterReading = meterReading.split(" ");

    // oTFWOV4.setValue(meterReading[0]);
    oTFWOV4.setValue("0");
    // WOmeterUnit.setValue(meterReading[1]);

    // var added_date = getIndonesianTime();
    // var added_by = operatedBy;

    // Car_Workorder_Task.where({master_email:emailUser,wo_id:obj['id']}).read().done(function (results) {
    //     for (var i = 0; i < results.length; i++) {
    //         Car_Workorder_Task.update({ id: results[i]['id'], wo_id: workorderID,added_date: added_date,
    //         added_by: added_by, assigned_id:"",assigned_name:"",workorder_note:results[i]['inspection_note'],task_status:"1"
    //         }).done(function () {
    //             if (i == (results.length)) {
    //                 funWorkorderTask();
    //             }
    //         });
    //     }
    // });
    
  } else if (createSrc == "Schedule") {
    oTFWOV1.setEditable(false);
    wo_title_field.setValue(obj["schedule_title"]);
    scheduleWO = true;
    scheduleOBJ = obj;

    getVehicleByLicenseNumberWO(obj["license_number"]);
    // inspectionLinkInput.addToken(new sap.m.Token({ key: obj['inspection_date'], text: obj['report_number'] }));

    // var getVehicle = vehicle4WJSONData.filter(function (vObj, index) {
    //   return vObj.license_number === obj["license_number"];
    // });

    // if (getVehicle.length > 0) {
    //   oTFWOV0.setValue(getVehicle[0]["id"]);
    //   oTFWOV1.setValue(getVehicle[0]["license_number"]);
    //   oTFWOV8.setValue(getVehicle[0]["chassis_number"]);
    //   oTFWOV9.setValue(getVehicle[0]["engine_number"]);
    //   oTFWOV10.setValue(getVehicle[0]["make"]);
    //   oTFWOV3.setValue(getVehicle[0]["model"]);
    //   oTFWOV11.setValue(getVehicle[0]["vehicle_color"]);
    //   oTFWOV12.setValue(getVehicle[0]["rental_company_name"]);
    //   oTFWOV13.setValue(getVehicle[0]["leasing_company_name"]);
    //   oTFWOV14.setValue(getVehicle[0]["transmission"]);
    //   oTFWOV4.setValue("0");
    //   filterWorkorderPartWorkshop();
      
    // }
    var task_list = obj["task_list"].split("^");

    task_list.forEach(function (item, index) {
      var newItem = new sap.ui.core.ListItem({
        key: item, // Use array index + 1 as key
        text: item, // Use array value as text
      });
      oInputPartField0.addItem(newItem);
    });
  } else {
    inspectionWO = false;
    scheduleWO = false;
  }

  // if(addPageSrc == '1' && obj && obj['wo_status'] != 'Reject'){

  //     if (createSrc == "Schedule" || createSrc == "Dashboard"){
  //         oInputPartField7.setVisible(true);
  //     }else{
  //         oInputPartField7.setVisible(false);
  //     }
  //     // let infoToolbarparts = oTablePartsItemWO.getInfoToolbar();
  //     oTablePartsItemWOTemplate.setType("Active");
  //     oTablePartsItemWO.setMode(sap.m.ListMode.None);
  //     // let partItem1 = infoToolbarparts.getContent()[2];
  //     // partItem1.setVisible(false);

  //     let infoToolbarRemark = oTableWORemark.getInfoToolbar();
  //     oTableWORemarkTemplate.setType("Active");
  //     oTableWORemark.setMode(sap.m.ListMode.None);
  //     let remarkItem1 = infoToolbarRemark.getContent()[2];
  //     remarkItem1.setVisible(false);

  //     let infoToolbarAttachment = oTableWOAttachment.getInfoToolbar();
  //     oTableAttachmentTemplate.setType("Active");
  //     oTableWOAttachment.setMode(sap.m.ListMode.None);
  //     let attachmentItem1 = infoToolbarAttachment.getContent()[2];
  //     attachmentItem1.setVisible(false);

  // }else{
  oTablePartsItemWO.setMode(sap.m.ListMode.Delete);
  oTablePartsItemWOTemplate.setType("Detail");
  oInputPartField7.setVisible(true);

  oTableWORemarkTemplate.setType("Detail");
  oTableWORemark.setMode(sap.m.ListMode.Delete);
  let infoToolbarRemark = oTableWORemark.getInfoToolbar();
  let remarkItem1 = infoToolbarRemark.getContent()[2];
  remarkItem1.setVisible(true);

  // oTableAttachmentTemplate.setType("Detail");
  oTableWOAttachment.setMode(sap.m.ListMode.Delete);
  let infoToolbarAttachment = oTableWOAttachment.getInfoToolbar();
  let attachmentItem1 = infoToolbarAttachment.getContent()[2];
  attachmentItem1.setVisible(true);

  // }
  if(portal_type_flag == '2W'){
    workorderForm1.getFormContainers()[0].getFormElements()[3].setVisible(false);
    workorderForm1.getFormContainers()[0].getFormElements()[4].setVisible(false);
  }
  
}

function createWorkOrderSubmit(newWOnumber) {
  var current_date = getIndonesianTime();

  var wo_number = newWOnumber;
  var wo_title = wo_title_field.getValue();
  var wo_status = "1";
  var wo_priority = WOPriority.getSelectedKey();
  var wo_type = WOTypeDB.getValue();
  var wo_memo = oTFWOMemo.getValue();

  var approval_request = "0";
  var approved = "1";
  if (addPageSrc == "2") {
    approval_request = "1";
    approved = "0";
  }

  var assigned_id = "";
  var assigned_name = "";
  var link_inspection = "";
  var link_workorder = "";

  var assignedTokenList = woAssignedInput.getTokens();
  var inspectionTokenList = inspectionLinkInput.getTokens();
  var workorderTokenList = workorderLinkInput.getTokens();

  for (var j = 0; j < assignedTokenList.length; j++) {
    if (assigned_id == "") {
      assigned_id = assignedTokenList[j].getKey();
      assigned_name = assignedTokenList[j].getText();
    } else {
      assigned_id = assigned_id + "^" + assignedTokenList[j].getKey();
      assigned_name = assigned_name + "^" + assignedTokenList[j].getText();
    }
  }
  for (var j = 0; j < inspectionTokenList.length; j++) {
    if (link_inspection == "") {
      link_inspection = inspectionTokenList[j].getText();
    } else {
      link_inspection =
        link_inspection + "^" + inspectionTokenList[j].getText();
    }
  }
  for (var j = 0; j < workorderTokenList.length; j++) {
    if (link_workorder == "") {
      link_workorder = workorderTokenList[j].getText();
    } else {
      link_workorder = link_workorder + "^" + workorderTokenList[j].getText();
    }
  }

  // updateWoPartsNumber(workorderID, wo_number);

  var vehicle_id = oTFWOV0.getValue();
  var vehicle_number = oTFWOV1.getValue();
  var vehicle_name = oTFWOV2.getValue();
  var vehicle_model = oTFWOV3.getValue();
  var meter_reading = oTFWOV4.getValue() + " " + WOmeterUnit.getValue();

  var start_date = woStartDate.getValue();
  var due_date = oDueDate.getValue();
  var estimated_cost = oTFWOPlannedCost.getValue();
  var estimated_time = oTFWOPlannedTime.getValue();

  var total_time = 0;

  // var obj = oTableLaborItemWO.getItems();
  // for (var i = 0; i < obj.length; i++) {
  //     var oContext = obj[i].getBindingContext().getObject();
  //     if (nullCheck(oContext.labor_time)) {
  //         total_time = parseFloat(total_time) + parseFloat( oContext.labor_time);
  //     }
  // }

  var total_parts_cost = roundToInt(oTFWOCost1.getValue());
  var total_labor_cost = roundToInt(oTFWOCost2.getValue());

  var additional_cost = roundToInt(oTFWOCost3.getValue());

  var tax = roundToInt(oTFWOCost4.getValue());
  var tax_value = roundToInt(oTFWOCost5.getValue());
  var total_wo_cost = roundToInt(oTFWOCost6.getValue());

  var created_date = current_date;
  var created_by = operatedBy;

  // var custom1 = oTFWOCustom1.getValue();
  // var custom2 = oTFWOCustom2.getValue();
  // var custom3 = oTFWOCustom3.getValue();
  // var custom4 = oTFWOCustom4.getValue();
  // var custom5 = oTFWOCustom5.getValue();

  var tsLong = new Date().getTime();
  var userFolder = emailUser.replace(/[@.]/g, "");
  var wo_number_trim = wo_number.replace(/[^.,a-zA-Z0-9]/g, "");
  var pdf_name = wo_number_trim + "_" + tsLong + "";
  var pdf_url = "";
    // "https://oxmaint.com/pdf/workorder/" + userFolder + "/" + pdf_name + ".pdf";

  if (oTFWOV4.getValue().trim() == "") {
    meter_reading = "";
  }

  // if (!nullCheck(oTFWOV4.getValue()) || minusCheck(oTFWOV4.getValue())) {
  //     sap.m.MessageBox.error(oBundle.getText("Enter_valid_odometer_reading"));
  //     return;
  //  }

  // if (total_parts_cost.trim() == "") {
  //     total_parts_cost = "0";
  // }
  // if (total_labor_cost.trim() == "") {
  //     total_labor_cost = "0";
  // }
  // if (tax.trim() == "") {
  //     tax = "0";
  // }
  // if (total_wo_cost.trim() == "") {
  //     total_wo_cost = "0";
  // }

  var wo_status = "1";
  if (addPageSrc == "2") {
    wo_status = "0";
  }

  var link_inspection_date = "";
  if (nullCheckAll(link_inspection)) {
    link_inspection_date = current_date;
  }

  // var ws_group_name = oTFWOV6.getValue();
  // var workshop_name = oTFWOV7.getValue();
  var license_number = oTFWOV1.getValue();
  var chassis_number = oTFWOV8.getValue();
  var engine_number = oTFWOV9.getValue();
  var make = oTFWOV10.getValue();
  var vehicle_color = oTFWOV11.getValue();
  var rental_company_name = oTFWOV12.getValue();
  var leasing_company_name = oTFWOV13.getValue();
  var transmission = oTFWOV14.getValue();
  var service_km = serviceKm.getValue();
  var regular_service = serviceWoCB.getValue();
  var city = cityTypeDB.getValue();

  var ws_group_number = "";
  var ws_group_name = "";
  var ws_group_woTokenList = oTFWOV6.getTokens();

  for (var j = 0; j < ws_group_woTokenList.length; j++) {
    if (ws_group_number == "") {
      ws_group_number = ws_group_woTokenList[j].getKey();
      ws_group_name = ws_group_woTokenList[j].getText();
    }
  }

  let workshop_number = "";
  let workshop_name = "";
  let workshopWoTokenList = oTFWOV7.getTokens();

  for (var j = 0; j < workshopWoTokenList.length; j++) {
    if (workshop_number == "") {
      workshop_number = workshopWoTokenList[j].getKey();
      workshop_name = workshopWoTokenList[j].getText();
    }
  }

  
  // var link_schedule = "";
  // if (inspectionWO) {
  //   Car_Workorder_Status.insert({
  //     master_email: emailUser,
  //     wo_number: wo_number,
  //     wo_id: "" + workorderID,
  //     wo_status: "Inspected",
  //     changed_date: created_date,
  //     changed_by: created_by,
  //   }).done(function () {});
  // } else if (scheduleWO) {
  //   wo_status = "11";
  //   link_schedule = scheduleOBJ["id"];

  //   Car_Schedule.update({
  //     id: scheduleOBJ["id"],
  //     workorder_id: workorderID + "",
  //     workorder_number: wo_number,
  //   }).done(function () {
  //     getScheduleDetails();
  //   });

  //   Car_Workorder_Status.insert({
  //     master_email: emailUser,
  //     wo_number: wo_number,
  //     wo_id: "" + workorderID,
  //     wo_status: "Scheduled",
  //     changed_date: created_date,
  //     changed_by: created_by,
  //   }).done(function () {});
  // } else {
  //   Car_Workorder_Status.insert({
  //     master_email: emailUser,
  //     wo_number: wo_number,
  //     wo_id: "" + workorderID,
  //     wo_status: "Pending Approval",
  //     changed_date: created_date,
  //     changed_by: created_by,
  //   }).done(function () {});
  // }
  var link_schedule = "";
  if (scheduleWO) {
    link_schedule = scheduleOBJ["id"];

  }

  var itemsInsertWO = {
    master_email: emailUser,
    // id: workorderID,
    id: wo_number,
    wo_number: wo_number,
    wo_title: wo_title,
    wo_memo: wo_memo,
    city: city,
    assigned_id: assigned_id,
    assigned_name: assigned_name,
    // wo_type:wo_type,
    link_schedule: link_schedule,
    link_inspection: link_inspection,
    link_inspection_date: link_inspection_date,
    regular_service: regular_service,
    service_km: service_km,
    supplier_cost: supplier_wo_cost + "",
    workshop_cost: workshop_wo_cost + "",
    supplier_wo_flag: supplier_wo_flag,
    supplier_id: supplier_wo_id,
    total_parts_cost: total_parts_cost,
    total_labor_cost: total_labor_cost,
    additional_cost: additional_cost,
    tax: tax,
    tax_value: tax_value,
    total_wo_cost: total_wo_cost,
    ws_group_number: ws_group_number,
    ws_group_name: ws_group_name,
    workshop_name: workshop_name,
    workshop_number: workshop_number,
    vehicle_id: vehicle_id,
    license_number: license_number,
    chassis_number: chassis_number,
    engine_number: engine_number,
    model: vehicle_model,
    make: make,
    transmission:transmission,
    meter_reading: meter_reading,
    vehicle_color: vehicle_color,
    // wo_status: "Pending Approval",
    wo_status: "Need Verification",
    source: "Portal",
    rental_company_name: rental_company_name,
    pdf_url: pdf_url,
    leasing_company_name: leasing_company_name,
    created_by: operatedID,
    created_date: current_date,
    archive: "0",
    supplier_inv_pick:""
  };

  //oBusyDialogWO.open();

  Car_Workorder.insert(itemsInsertWO).done(function () {
    updateWoPartsNumber(workorderID, wo_number);
    getVerificationWorkorder();
    addWorkorderStatus(itemsInsertWO,scheduleOBJ);
    setLinkInspection(itemsInsertWO);
    // getAllWorkorderDetails();

    clearWOfield(1);
    oAppWorkOrder.backToTop();
    oBusyDialogWO.close();
  }, workorderfailure1);
};

function addWorkorderStatus(itemsInsertWO, scheduleOBJ){
  let schedule_obj = scheduleOBJ
  let current_date = getIndonesianTime();
  wo_status_Value = "Need Verification";

  if (inspectionWO) {
    wo_status_Value = "Inspected";
  } else if (scheduleWO) {
    Car_Schedule.update({ id: schedule_obj["id"], workorder_id: itemsInsertWO['wo_number'] + "", 
      workorder_number: itemsInsertWO['wo_number'],
    }).done(function () {
      getScheduleDetails();
    });

    wo_status_Value = "Scheduled";
  } else {
    wo_status_Value = "Need Verification";
  };

  Car_Workorder_Status.insert({ master_email: emailUser, wo_number: itemsInsertWO['wo_number'], 
    wo_id: "" + itemsInsertWO['wo_number'],
    wo_status: wo_status_Value, changed_date: current_date,changed_by: operatedID,
  }).done(function () {});
}


function setLinkInspection(obj) {
  var link_inspection = obj["link_inspection"];

  if (link_inspection != null && link_inspection != "") {
    var link_inspectionArray = link_inspection.split("^");

    for (var i = 0; i < link_inspectionArray.length; i++) {
      var report_number = link_inspectionArray[i];

      var result = inspectionJSONArray.filter(function (objInsp, index) {
        return objInsp.report_number == report_number;
      });

      if (result.length > 0) {
        var refrenceWo = obj["wo_number"];
        if (result[0]["workorder"] != null) {
          refrenceWo = result[0]["workorder"] + "^" + obj["wo_number"];
        }

        Car_Inspection.update({
          id: result[0]["id"],
          workorder: refrenceWo,
          action_source: "2",
        }).done(function () {
          funGetInspection();
        });
      }
    }
  }
}

/*
function funcSendNotification(item) {
  for (var i = 0; i < notificationEmailArray.length; i++) {
    if (notificationEmailArray[i].wo_status_email == "1") {
      sendMailStatusChange(item, notificationEmailArray[i].notification_email);
    }
  }
  var assignedTokenList = woAssignedInput.getTokens();

  for (var j = 0; j < assignedTokenList.length; j++) {
    var team = teamJSONArray.filter(function (obj, index) {
      return obj.emailid === assignedTokenList[j].getKey();
    });
    var mEmail = team[0]["notification_email"];
    var user_id = team[0]["emailid"];
    if (regEmail.test(mEmail)) {
      sendMailAssignWO(item, mEmail, user_id);
    }
  }
}*/

var workorderOBJ = "";
function iniUpdateWorkOrder(obj) {
  clearWOfield();
  btnWO1.setVisible(false);
  btnWO2.setVisible(true);
  oTFWOV1.setEditable(false);
  inspectionLinkInput.setEnabled(false);
  if (obj["approved"] == "0" && obj["approval_request"] == "1") {
    oTFWOV1.setEditable(true);
  }
  
  workorderID = obj["id"];
  workorderOBJ = obj;
  HVICore.getElementById("wo_number").setText(obj["wo_number"]);
  
  if (obj["assigned_id"] != null && obj["assigned_id"] != "") {
    var assigned_id = obj["assigned_id"].split("^");
    var assigned_name = obj["assigned_name"].split("^");
    for (var i = 0; i < assigned_id.length; i++) {
      woAssignedInput.addToken(
        new sap.m.Token({ key: assigned_id[i], text: assigned_name[i] })
      );
    }
  }
  wo_title_field.setValue(obj["wo_title"]);
  // WOPriority.setSelectedKey(obj['wo_priority']);
  WOTypeDB.setValue(obj["wo_type"]);
  oTFWOMemo.setValue(obj["wo_memo"]);
  
  if (obj["link_inspection"] != null && obj["link_inspection"] != "") {
    var link_inspection = obj["link_inspection"].split("^");
    for (var i = 0; i < link_inspection.length; i++) {
      inspectionLinkInput.addToken(
        new sap.m.Token({ text: link_inspection[i] })
      );
    }
  }
  if (obj["link_workorder"] != null && obj["link_workorder"] != "") {
    var link_workorder = obj["link_workorder"].split("^");
    for (var i = 0; i < link_workorder.length; i++) {
      workorderLinkInput.addToken(new sap.m.Token({ text: link_workorder[i] }));
    }
  }
  

  oTFWOV0.setValue(obj["vehicle_id"]);
  oTFWOV1.setValue(obj["license_number"]);
  oTFWOV3.setValue(obj["model"]);
  if (nullCheckAll(obj["ws_group_number"])) {
    oTFWOV6.setEnabled(false);
    oTFWOV6.addToken(
      new sap.m.Token({
        key: obj["ws_group_number"],
        text: obj["ws_group_name"],
      })
    );
  }
  if (nullCheckAll(obj["workshop_number"])) {
    oTFWOV7.setEnabled(false);
    oTFWOV7.addToken(
      new sap.m.Token({
        key: obj["workshop_number"],
        text: obj["workshop_name"],
      })
    );
  }
  
  oTFWOV8.setValue(obj["chassis_number"]);
  oTFWOV9.setValue(obj["engine_number"]);
  oTFWOV10.setValue(obj["make"]);
  oTFWOV11.setValue(obj["vehicle_color"]);
  oTFWOV12.setValue(obj["rental_company_name"]);
  oTFWOV13.setValue(obj["leasing_company_name"]);
  
  cityTypeDB.setValue(obj["city"]);
  if (nullCheckAll(obj["regular_service"])) {
    if (obj["regular_service"] == "Yes") {
      serviceWoCB.setValue(obj["regular_service"]);
      workorderForm1
        .getFormContainers()[0]
        .getFormElements()[5]
        .setVisible(true);
      serviceKm.setValue(obj["service_km"]);
    } else {
      serviceWoCB.setValue("No");
      workorderForm1
        .getFormContainers()[0]
        .getFormElements()[5]
        .setVisible(false);
    }
  } else {
    serviceWoCB.setValue("No");
    workorderForm1
      .getFormContainers()[0]
      .getFormElements()[5]
      .setVisible(false);
  }



  oTablePartsItemWO.setMode(sap.m.ListMode.Delete);
  oTablePartsItemWOTemplate.setType("Detail");
  let infoToolbarparts = oTablePartsItemWO.getInfoToolbar();
  oInputPartField7.setVisible(true);
  // let partItem1 = infoToolbarparts.getContent()[2];
  // partItem1.setVisible(true);

  oTableWORemarkTemplate.setType("Detail");
  oTableWORemark.setMode(sap.m.ListMode.Delete);
  let infoToolbarRemark = oTableWORemark.getInfoToolbar();
  let remarkItem1 = infoToolbarRemark.getContent()[2];
  remarkItem1.setVisible(true);

  // oTableAttachmentTemplate.setType("Detail");
  oTableWOAttachment.setMode(sap.m.ListMode.Delete);
  let infoToolbarAttachment = oTableWOAttachment.getInfoToolbar();
  let attachmentItem1 = infoToolbarAttachment.getContent()[2];
  attachmentItem1.setVisible(true);

  // oTableWOAdditionalCostTemplate.setType("Detail");
  // oTableWOAdditionalCost.setMode(sap.m.ListMode.Delete);
  // let infoToolbarCost = oTableWOAdditionalCost.getInfoToolbar();
  // let costItem1 = infoToolbarCost.getContent()[2];
  // costItem1.setVisible(true);

  // }

  var meterReading = obj["meter_reading"];
  if (meterReading != null) {
    var meterReading = meterReading.split(" ");
    oTFWOV4.setValue(meterReading[0]);
    WOmeterUnit.setValue(meterReading[1]);
  }

  woStartDate.setValue(obj["start_date"]);
  oDueDate.setValue(obj["due_date"]);
  oTFWOPlannedCost.setValue(obj["estimated_cost"]);
  oTFWOPlannedTime.setValue(obj["estimated_time"]);

  oTFWOCost1.setValue(obj["total_parts_cost"]);
  oTFWOCost2.setValue(obj["total_labor_cost"]);

  oTFWOCost4.setValue(obj["tax"]);
  oTFWOCost6.setValue(obj["total_wo_cost"]);

  // var taxableValue = parseFloat(obj['total_parts_cost']) + parseFloat(obj['total_labor_cost']);
  // var taxCost = parseFloat(taxableValue) * parseFloat(obj['tax']) / 100;
  //oTFWOCost5.setValue((Math.round(taxCost * 100) / 100));

  oTFWOCustom1.setValue(obj["custom1"]);
  oTFWOCustom2.setValue(obj["custom2"]);
  oTFWOCustom3.setValue(obj["custom3"]);
  oTFWOCustom4.setValue(obj["custom4"]);
  oTFWOCustom5.setValue(obj["custom5"]);

  getVehicleByLicenseNumberWO(obj["license_number"]);
  funWorkorderParts();
  funWorkorderAttachment();
  funWorkorderRemark();
 

  if(nullCheckAll(obj['link_inspection'])){

    Car_Inspection_Item.where({
      master_email: emailUser,
      inspection_number: obj["link_inspection"],
    }).read()
      .done(function (results) {
        if (results.length > 0) {
          results.forEach(function (item, index) {
            var newItem = new sap.ui.core.ListItem({
              key: item.task_name, // Use array index + 1 as key
              text: item.task_name, // Use array value as text
            });
            oInputPartField0.addItem(newItem);
          });
        }
      });
  };

  if(nullCheckAll(obj['link_schedule'])){
    Car_Schedule.where({
      master_email: emailUser,
      id: obj["link_schedule"],
    }).read()
    .done(function (results) {
      if (results.length > 0) {

        var task_list = results[0]["task_list"].split("^");

        task_list.forEach(function (item, index) {
          var newItem = new sap.ui.core.ListItem({
            key: item, // Use array index + 1 as key
            text: item, // Use array value as text
          });
          oInputPartField0.addItem(newItem);
        });

      }
    });
  }
  oTFWOV14.setValue(obj["transmission"]);

  if(portal_type_flag == '2W'){
    workorderForm1.getFormContainers()[0].getFormElements()[3].setVisible(false);
    workorderForm1.getFormContainers()[0].getFormElements()[4].setVisible(false);
  }
}

function updateWorkOrderSubmit() {
  
  var current_date = getIndonesianTime();

  var wo_number = HVICore.getElementById("wo_number").getText();
  var wo_title = wo_title_field.getValue();
  var wo_priority = WOPriority.getSelectedKey();
  var wo_type = WOTypeDB.getValue();
  var wo_memo = oTFWOMemo.getValue();

  var approval_request = "0";
  var approved = "1";
  if (addPageSrc == "2") {
    approval_request = "1";
    approved = "0";
  }

  var assigned_id = "";
  var assigned_name = "";
  var link_inspection = "";
  var link_workorder = "";

  var assignedTokenList = woAssignedInput.getTokens();
  var inspectionTokenList = inspectionLinkInput.getTokens();
  var workorderTokenList = workorderLinkInput.getTokens();

  for (var j = 0; j < assignedTokenList.length; j++) {
    if (assigned_id == "") {
      assigned_id = assignedTokenList[j].getKey();
      assigned_name = assignedTokenList[j].getText();
    } else {
      assigned_id = assigned_id + "^" + assignedTokenList[j].getKey();
      assigned_name = assigned_name + "^" + assignedTokenList[j].getText();
    }
  }
  for (var j = 0; j < inspectionTokenList.length; j++) {
    if (link_inspection == "") {
      link_inspection = inspectionTokenList[j].getText();
    } else {
      link_inspection =
        link_inspection + "^" + inspectionTokenList[j].getText();
    }
  }
  for (var j = 0; j < workorderTokenList.length; j++) {
    if (link_workorder == "") {
      link_workorder = workorderTokenList[j].getText();
    } else {
      link_workorder = link_workorder + "^" + workorderTokenList[j].getText();
    }
  }

  var vehicle_number = oTFWOV1.getValue();
  var vehicle_name = oTFWOV2.getValue();
  var vehicle_model = oTFWOV3.getValue();
  var meter_reading = oTFWOV4.getValue() + " " + WOmeterUnit.getValue();

  // var start_date = woStartDate.getValue();
  // var due_date = oDueDate.getValue();
  // var estimated_cost = oTFWOPlannedCost.getValue();
  // var estimated_time = oTFWOPlannedTime.getValue();

  // var total_time = 0;

  // var obj = oTableLaborItemWO.getItems();
  // for (var i = 0; i < obj.length; i++) {
  //         var oContext = obj[i].getBindingContext();
  //         var labor_time = oContext.getObject().labor_time;
  //         if(nullCheck(labor_time)){
  //             total_time = parseFloat(total_time) + parseFloat(labor_time);
  //         }
  // }

  var total_parts_cost = roundToInt(oTFWOCost1.getValue());
  var total_labor_cost = roundToInt(oTFWOCost2.getValue());

  var additional_cost = roundToInt(oTFWOCost3.getValue());

  var tax = roundToInt(oTFWOCost4.getValue());
  var tax_value = roundToInt(oTFWOCost5.getValue());
  var total_wo_cost = roundToInt(oTFWOCost6.getValue());

  // var updated_date = current_date;
  // var updated_by = operatedBy;

  // var custom1 = oTFWOCustom1.getValue();
  // var custom2 = oTFWOCustom2.getValue();
  // var custom3 = oTFWOCustom3.getValue();
  // var custom4 = oTFWOCustom4.getValue();
  // var custom5 = oTFWOCustom5.getValue();

  if (wo_number.trim() == "") {
    sap.m.MessageBox.error(
      oBundle.getText("Workorder_number_field_can_not_be_empty")
    );
    return;
  }

  if (vehicle_number.trim() == "") {
    sap.m.MessageBox.error(oBundle.getText("Please_select_vehicle"));
    return;
  }
  if (!nullCheck(oTFWOV4.getValue()) || minusCheck(oTFWOV4.getValue())) {
    sap.m.MessageBox.error(oBundle.getText("Enter_valid_odometer_reading"));
    return;
  }


  var objTask = oTablePartsItemWO.getItems();

  if (objTask.length < 1) {
    sap.m.MessageBox.error(oBundle.getText("Add_at_least_one_part"));
    return;
  }

  if (oTFWOV4.getValue().trim() == "") {
    meter_reading = "";
  }


  var userFolder = emailUser.replace(/[@.]/g, "");
  var pdf_name = workorderOBJ["pdf_name"];
  var pdf_url =
    "https://oxmaint.com/pdf/workorder/" + userFolder + "/" + pdf_name + ".pdf";

  var city = cityTypeDB.getValue();
  var rental_company_name = oTFWOV12.getValue();
  var leasing_company_name = oTFWOV13.getValue();

  if (city == "Select City") {
    sap.m.MessageBox.error(oBundle.getText("Please_Select_City"));
    return;
  }

  var regular_service = serviceWoCB.getValue();
  var service_km = serviceKm.getValue();
  if (regular_service == "Yes" && !nullCheckAll(service_km)) {
    sap.m.MessageBox.error(oBundle.getText("Add_Service_KM"));
    return;
  }

  var ws_group_number = "";
  var ws_group_name = "";
  var ws_group_woTokenList = oTFWOV6.getTokens();

  for (var j = 0; j < ws_group_woTokenList.length; j++) {
    if (ws_group_number == "") {
      ws_group_number = ws_group_woTokenList[j].getKey();
      ws_group_name = ws_group_woTokenList[j].getText();
    }
  }

  let workshop_number = "";
  let workshop_name = "";
  let workshopWoTokenList = oTFWOV7.getTokens();

  for (var j = 0; j < workshopWoTokenList.length; j++) {
    if (workshop_number == "") {
      workshop_number = workshopWoTokenList[j].getKey();
      workshop_name = workshopWoTokenList[j].getText();
    }
  };

  // var new_wo_status = 'Pending Approval';
  // let currentWOSection = oAppWorkOrderPageLayout.getSelectedSection();
  // if (currentWOSection == "GWO11") {
  //   new_wo_status = 'Need Verification';
  // }else if(currentWOSection == "GWO6" && !nullCheckAll(workorderOBJ['approval1'])){
  //   new_wo_status = 'Need Verification';
  // }
    var new_wo_status = 'Need Verification';


  var item = {
    id: workorderID + "",

    wo_title: wo_title,
    wo_memo: wo_memo,
    city: city,
    assigned_id: assigned_id,
    assigned_name: assigned_name,
    link_inspection: link_inspection,
    // wo_type:wo_type,
    regular_service: regular_service,
    service_km: service_km,
    ws_group_number: ws_group_number,
    ws_group_name: ws_group_name,
    workshop_name: workshop_name,
    workshop_number: workshop_number,
    meter_reading: meter_reading,
    source: "Portal",
    wo_status: new_wo_status,

    rental_company_name: rental_company_name,
    pdf_url: pdf_url,
    leasing_company_name: leasing_company_name,
    total_parts_cost: total_parts_cost,
    total_labor_cost: total_labor_cost,
    additional_cost: additional_cost,
    tax: tax,
    tax_value: tax_value,
    total_wo_cost: total_wo_cost,
    updated_by: operatedID,
    updated_date: current_date,
    approved: "",
    approval1: "",
    approver1: "",
    approval1_date:"",
    approval2: "",
    approver2: "",
    approval2_date:"",
    approval3: "",
    approver3: "",
    approval3_date:"",
    approval4: "",
    approver4: "",
    approval4_date:"",
    approval5: "",
    approver5: "",
    approval5_date:""
  };

  oBusyDialogWO.open();

  Car_Workorder_Status.insert({ master_email:emailUser, wo_number:wo_number, wo_id: workorderID, wo_status: new_wo_status, 
    changed_date: current_date, changed_by: operatedID
  }).done(function () { });

  Car_Workorder.update(item).done(function () {
    clearWOfield(1);
    getPendingWorkorder();
    oAppWorkOrder.backToTop();
    oBusyDialogWO.close();
    let currentWOSection = oAppWorkOrderPageLayout.getSelectedSection();
    if (currentWOSection == "GWO2") {
      getOpenWorkorder();
    } else if (currentWOSection == "GWO3") {
      getCompletedWorkorder();
    } else if (currentWOSection == "GWO4") {
      getClosedWorkorder();
    } else if (currentWOSection == "GWO5") {
      getGrnWorkorder();
    } else if (currentWOSection == "GWO6") {
      getRejectWorkorder();
    } else if (currentWOSection == "GWO7") {
      getCancelledWorkorder();
    } else if (currentWOSection == "GWO8") {
      funGetArchiveWO();
    } else if(currentWOSection == "GWO11"){
      getVerificationWorkorder();
    }
  }, failure);
}


function clearWOfield(src) {
  btnWO1.setVisible(true);
  btnWO2.setVisible(false);

  HVICore.getElementById("wo_number").setText("");
  wo_title_field.setValue("");
  woAssignedInput.removeAllTokens();
  //WOStatus.setSelectedKey("1");
  WOPriority.setSelectedKey("1");
  WOTypeDB.setSelectedKey("1");
  oTFWOMemo.setValue("");
  inspectionLinkInput.removeAllTokens();
  workorderLinkInput.removeAllTokens();
  oTFWOV6.removeAllTokens();
  oTFWOV7.removeAllTokens();
  cityTypeDB.setValue("Select City");
  oTFWOV0.setValue("");
  oTFWOV1.setValue("");
  oTFWOV2.setValue("");
  oTFWOV3.setValue("");
  oTFWOV4.setValue("");
  oTFWOV8.setValue("");
  oTFWOV9.setValue("");
  oTFWOV10.setValue("");
  oTFWOV11.setValue("");
  oTFWOV12.setValue("");
  oTFWOV13.setValue("");
  oTFWOV14.setValue("");
  serviceWoCB.setValue("No");
  serviceKm.setValue("0");
  workorderForm1.getFormContainers()[0].getFormElements()[5].setVisible(false);

  woStartDate.setValue("");
  oDueDate.setValue("");
  oTFWOPlannedCost.setValue("");
  oTFWOPlannedTime.setValue("");

  oTFWOCost1.setValue("0");
  oTFWOCost2.setValue("0");
  // oTFWOCost3.setValue("0");

  oTFWOCost5.setValue("0");
  oTFWOCost6.setValue("0");

  // oTFWOCustom1.setValue("");
  // oTFWOCustom2.setValue("");
  // oTFWOCustom3.setValue("");
  // oTFWOCustom4.setValue("");
  // oTFWOCustom5.setValue("");
  workorderPartJSONArray = [];
  oInputPartField1.setValue("");
  oInputPartField2.setValue("");
  oInputPartField3.setValue("");
  oInputPartField4.setValue("");
  oInputPartField5.setValue("");
  oInputPartField6.setValue("");

  var oModelBlank = new sap.ui.model.json.JSONModel({
    data: { modelData: [] },
  });

  // oTableWOTaskItem.setModel(oModelBlank);
  oTablePartsItemWO.setModel(oModelBlank);
  // oTableLaborItemWO.setModel(oModelBlank);
  oTableWOAttachment.setModel(oModelBlank);
  oTableWORemark.setModel(oModelBlank);
  // oTableWOAdditionalCost.setModel(oModelBlank);

  // oTableWOTaskItem.bindItems({path: "/modelData",template : oTableTaskItemTemplate});
  // oTablePartsItemWO.bindItems({path: "/modelData",template : oTablePartsItemWOTemplate});
  // oTableLaborItemWO.bindItems({path: "/modelData",template : oTableLaborItemWOTemplate});
  oTableWOAttachment.bindItems({
    path: "/modelData",
    template: oTableAttachmentTemplate,
  });
  oTableWORemark.bindItems({
    path: "/modelData",
    template: oTableWORemarkTemplate,
  });
  // oTableWOAdditionalCost.bindItems({
  //   path: "/modelData",
  //   template: oTableWOAdditionalCostTemplate,
  // });

  // oTableWOTaskItemExecution.bindItems({path: "/modelData",template : oTableTaskExecutionTemplate});
  // oTablePartsWOExecution.bindItems({path: "/modelData",template : oTablePartsWOExecutionTemplate});
  // oTableLaborWOExecute.bindItems({path: "/modelData",template : oTableLaborItemWOTemplate});
  // oTableAttachmentWOExecution.bindItems({path: "/modelData",template : oTableAttachmentTemplate});
  // oTableWORemarkExecution.bindItems({path: "/modelData",template : oTableWORemarkTemplate});
  // oTableWOAdditionalCostExecution.bindItems({path: "/modelData",template : oTableWOAdditionalCostTemplate});
  // oTableWOTimeLog.bindItems({path: "/modelData",template : oTableWOTimeLogTemplate});

  if (src == 1) {
    oTableWorkorder.getInfoToolbar().setVisible(false);

    oTableWorkorder
      .getColumns()[1]
      .setSortIndicator(sap.ui.core.SortOrder.None);
    oTableWorkorder
      .getColumns()[2]
      .setSortIndicator(sap.ui.core.SortOrder.None);
    oTableWorkorder
      .getColumns()[3]
      .setSortIndicator(sap.ui.core.SortOrder.None);
    oTableWorkorder
      .getColumns()[4]
      .setSortIndicator(sap.ui.core.SortOrder.None);
    oTableWorkorder
      .getColumns()[5]
      .setSortIndicator(sap.ui.core.SortOrder.None);
    oTableWorkorder
      .getColumns()[6]
      .setSortIndicator(sap.ui.core.SortOrder.None);
    oTableWorkorder
      .getColumns()[7]
      .setSortIndicator(sap.ui.core.SortOrder.None);

    oTableWorkorder
      .getColumns()[2]
      .setSortIndicator(sap.ui.core.SortOrder.Descending);
  }

  let allowedKeys = ["1", "2", "3", "4", "5", "6", "7"];

  var items = oInputPartField0.getItems(); // Get all items

  //ADD 2 wheeler service types Keys
  if(portal_type_flag == "2W"){
    allowedKeys = ["1","2","3","4","5","6","7","8","9"]
  }
  items.forEach(function (item) {
    if (!allowedKeys.includes(item.getKey())) {
      oInputPartField0.removeItem(item); // Remove the item if its key is not in the allowedKeys array
    }
  });

  //workorderID = "1";
  //funWorkorderTask();
  //funWorkorderParts();
  //funWorkorderLabor();
  //funWorkorderAttachment();
  //funWorkorderRemark();
  //funWorkorderAdditionalCost();
  //funWorkorderTimeLog();
}

//////////////////////////Start Task Details//////////////////////////

var taskAssignedInput = new sap.m.Input({
  width: "100%",
  showSuggestion: true,
  showValueHelp: true,
  valueHelpRequest: function () {
    assignedTeamDialog(2);
  },
  suggestionItemSelected: function (oEvent) {
    var selectedItem = oEvent.getParameter("selectedItem");
    if (selectedItem) {
      this.setValue(selectedItem.getAdditionalText());
    }
  },
});
//////////////////////////End Task Details//////////////////////////


function addUpdatePartsItem(src, obj) {
  var field0 = new sap.m.Input({ value: "", width: "100%" });
  var field1 = new sap.m.Input({ value: "", width: "100%" });
  // var field1 = oInputPartField1.clone();//new sap.m.Input({ value: "", width: "100%" });
  var field2 = new sap.m.Input({ type: "Number", value: "1", width: "100%" });
  var field3 = new sap.m.Input({ type: "Number", value: "", width: "100%" });
  var field4 = new sap.m.TextArea({
    width: "100%",
    height: "70px",
    rows: 2,
    wrapping: sap.ui.core.Wrapping.on,
  });
  var field5 = new sap.m.Input({ value: "", width: "100%" });
  var field6 = new sap.m.Input({ type: "Number", value: "", width: "100%" });

  var field7 = new sap.m.Input({ value: "", width: "100%" });
  var field8 = new sap.m.Input({ enabled: false, value: "", width: "100%" });
  // var field8 = new sap.m.ComboBox({width:"100%",
  //     items:[
  //             new sap.ui.core.ListItem({key:"1",text:oBundle.getText("PACKAGE")}),
  //             new sap.ui.core.ListItem({key:"2",text:oBundle.getText("NON PACKAGE")}),
  //             new sap.ui.core.ListItem({key:"3",text:oBundle.getText("POOL ACTIVITY")}),
  //             new sap.ui.core.ListItem({key:"4",text:oBundle.getText("INSURANCE")}),
  //             new sap.ui.core.ListItem({key:"5",text:oBundle.getText("NON INSURANCE")}),
  //             new sap.ui.core.ListItem({key:"6",text:oBundle.getText("RITASE")}),
  //             new sap.ui.core.ListItem({key:"7",text:oBundle.getText("DOCUMENT EXPENSE")})
  //      ]
  //  }).addEventDelegate({onAfterRendering: function(e) { field8.$().find("input").attr("readonly", true);}});

  var partsUnitWO = new sap.m.ComboBox({
    value: oBundle.getText("KG"),
    items: [
      new sap.ui.core.ListItem({ text: oBundle.getText("KG") }),
      new sap.ui.core.ListItem({ text: oBundle.getText("Gram") }),
      new sap.ui.core.ListItem({ text: oBundle.getText("Gallon") }),
      new sap.ui.core.ListItem({ text: oBundle.getText("Quart") }),
      new sap.ui.core.ListItem({ text: oBundle.getText("Ltr") }),
      new sap.ui.core.ListItem({ text: oBundle.getText("ML") }),
      new sap.ui.core.ListItem({ text: oBundle.getText("Meter") }),
    ],
  });

  partsUnitWO.setValue(oBundle.getText("KG"));
  // partsUnitWO.setLayoutData(new sap.ui.layout.GridData({ span: "L3 M6 S12" }));

  var oForm1 = new sap.ui.layout.form.Form({
    editable: true,
    layout: new sap.ui.layout.form.ResponsiveGridLayout(),
    formContainers: [
      new sap.ui.layout.form.FormContainer({
        formElements: [
          new sap.ui.layout.form.FormElement({
            label: new sap.m.Label({
              required: true,
              text: oBundle.getText("Service_Type"),
            }),
            fields: [field8],
          }),
          new sap.ui.layout.form.FormElement({
            label: new sap.m.Label({
              required: true,
              text: oBundle.getText("Vehicle_Part_Id"),
            }),
            fields: [field0],
          }),
          new sap.ui.layout.form.FormElement({
            label: new sap.m.Label({
              required: true,
              text: oBundle.getText("Part_Name"),
            }),
            fields: [field1],
          }),
          // new sap.ui.layout.form.FormElement({
          //     label: new sap.m.Label({ required: true, text: oBundle.getText("Part_Number") }),
          //     fields: [field5]
          // }),
          new sap.ui.layout.form.FormElement({
            label: new sap.m.Label({
              required: false,
              text: oBundle.getText("Quantity"),
            }),
            // fields: [field2,partsUnitWO]
            fields: [field2],
          }),
          new sap.ui.layout.form.FormElement({
            label: new sap.m.Label({
              required: true,
              text: oBundle.getText("Part_Cost"),
            }),
            fields: [field3],
          }),
          new sap.ui.layout.form.FormElement({
            label: new sap.m.Label({
              required: true,
              text: oBundle.getText("Labor_Cost"),
            }),
            fields: [field6],
          }),
          new sap.ui.layout.form.FormElement({
            label: new sap.m.Label({ text: oBundle.getText("Note") }),
            fields: [field4],
          }),
        ],
      }),
    ],
  });

  var oButton = new sap.m.Button({
    text: oBundle.getText("Add"),
    icon: "sap-icon://add",
    press: function () {
      // var parts_number = field0.getValue();
      let vehicle_part_id = field0.getValue();
      let parts_name = field1.getValue();
      let parts_qty = field2.getValue();
      let parts_cost = field3.getValue();
      let note = field4.getValue();
      // let parts_unit = partsUnitWO.getValue();
      let labor_item_cost = field6.getValue();
      // var part_number = field5.getValue();
      // var task_name = field7.getValue();
      var task_type = field8.getValue();

      var workorder = HVICore.getElementById("wo_number").getText();
      if (workorder == "") {
        workorder = HVICore.getElementById("wo_number_execution").getText();
      }

      var vehicle_number = oTFWOV1.getValue();

      if (vehicle_number == "") {
        vehicle_number = HVICore.getElementById(
          "vehicle_number_execution"
        ).getText();
      }

      var added_date = getIndonesianTime();
      var added_by = operatedBy;

      if (textFieldValidation(field0, vehicle_part_id)) {
        return;
      }
      if (textFieldValidation(field1, parts_name)) {
        return;
      }
      if (validateNumber(parts_qty, "Quantity")) {
        return;
      }
      if (validateNumber(parts_cost, "Part Cost")) {
        return;
      }
      if (validateNumber(labor_item_cost, "Labor Cost")) {
        return;
      }
      // if (textFieldValidation(field7, task_name)) { return; }
      if (textFieldValidation(field8, task_type)) {
        return;
      }
      if(parts_qty <= 0){
        sap.m.MessageBox.error("Enter Valid Quantity");
        return;
      }
      if (parts_name && (parts_name.includes("Tyre") || parts_name.includes("Battery"))) {
        if (!note || note.trim().length < 1) {
          sap.m.MessageBox.error("Please Enter Note");
          return;
        }
      }


      var total_part_cost = parseFloat(parts_qty) * parseFloat(parts_cost);
      var roundTotalCost = roundToInt(total_part_cost);
      var roundItemCost = roundToInt(parts_cost);
      let totalCost = parseFloat(roundTotalCost) + parseFloat(labor_item_cost);

      var tax = oTFWOCost4.getValue();
      
      if(nullCheckAll(obj['supplier_id'])){
        taxFilter = supplier4WJSONData.filter(function(ob,ev){
          return ob.supplier_number == obj['supplier_id'];
        });
        if(taxFilter.length > 0 ){
          tax = taxFilter[0]['tax_percentage'];
        }      
      }
      let taxCalculated = roundToInt((tax * totalCost) / 100);

      let totalCostRound = roundToInt(totalCost + taxCalculated);

      if (src == "update") {
        Car_Workorder_Part.update({
          id: obj["id"],
          parts_qty: parts_qty, //parts_unit: parts_unit,
          task_type: task_type,
          note: note,
          wo_id: workorderID,
          wo_number: workorder,
          tax_value: taxCalculated + "",
          labor_item_cost: labor_item_cost + "",
          parts_cost: roundItemCost + "",
          total_parts_cost: roundTotalCost + "",
          total_cost: totalCostRound + "",
          updated_date: added_date,
          updated_by: added_by,
        }).done(function () {
          funWorkorderParts();
          oDialog.close();
        }, failure);
      }
    },
  });

  var oDialog = new sap.m.Dialog({
    draggable: true,
    resizable: true,
    contentWidth: "50%",
    title: oBundle.getText("Add_Parts_Item"),
    content: [oForm1],
    buttons: [
      oButton,
      new sap.m.Button({
        text: oBundle.getText("Cancel"),
        icon: "sap-icon://decline",
        press: function () {
          oDialog.close();
        },
      }),
    ],
  }).open();

  if (src == "parts") {
    // field0.setEnabled(false);
    // field1.setEnabled(false);
    // field0.setValue(obj["vehicle_part_id"]);
    // field1.setValue(obj["part_name"]);
    
    // var oModel = new sap.ui.model.json.JSONModel();
    // oModel.setData({ modelData: workorderPartJSONArray }); // results is an array of suggestion data
    // field1.setModel(oModel);

  } else if (src == "update") {
    oDialog.setTitle(oBundle.getText("Update_Service_Needed"));
    oButton.setText(oBundle.getText("Update"));
    oButton.setIcon("sap-icon://edit");

    if(obj['part_type'] == 'Supplier'){
      field3.setEnabled(false);
      field6.setEnabled(false);
    }else{
      field3.setEnabled(true);
      field6.setEnabled(true);
    }
    field0.setEnabled(false);
    field1.setEnabled(false);
    field5.setEnabled(false);

    field0.setValue(obj["vehicle_part_id"]);
    field1.setValue(obj["part_name"]);
    field2.setValue(obj["parts_qty"]);
    field3.setValue(obj["parts_cost"]);
    field4.setValue(obj["note"]);
    field6.setValue(obj["labor_item_cost"]);
    field7.setValue(obj["task_name"]);
    field8.setValue(obj["task_type"]);
    partsUnitWO.setValue(obj["parts_unit"]);
  } 
}

function funWorkorderParts() {
  Car_Workorder_Part.where({ master_email: emailUser, wo_id: workorderID })
    .take(1000)
    .orderByDescending("task_type")
    .read()
    .done(function (results) {
      // console.log(results);
      var oModel = new sap.ui.model.json.JSONModel();
      oModel.setData({ modelData: results });
      oTablePartsItemWO.setModel(oModel);
      oTablePartsItemWO.bindItems({
        path: "/modelData",
        template: oTablePartsItemWOTemplate,
      });
      oTablePartsItemWO.setBusy(false);

      // oTablePartsWOExecution.setModel(oModel);
      // oTablePartsWOExecution.bindItems({path: "/modelData",
      //     template : oTablePartsWOExecutionTemplate
      // });

      calculatingPartsCost();
    });
}

//////////////////////////End Parts and Material Details//////////////////////////

//////////////////////////Start Attachment Details//////////////////////////
function addUpdateAttachment() {
  var oDialogAttachment = new sap.m.BusyDialog({
    text: oBundle.getText("Attachment_Uploading"),
  });
  var wo_number = HVICore.getElementById("wo_number").getText();

  var tsLong = new Date().getTime();
  var userFolder = emailUser.replace(/[@.]/g, "");

  var wo_number = wo_number.replace(/[^.,a-zA-Z0-9]/g, "");
  var blob_name =  "_" + tsLong + "";

  var oFileUploaderAttachment = new sap.ui.unified.FileUploader({
    name: "pdf",
    uploadUrl: "https://oxmaint.com/upload/attachment.php",
    sendXHR: true,
    maximumFileSize: 5,
    fileType: [
      "jpeg",
      "jpg",
      "JPG",
      "JPEG",
      "PNG",
      "png",
      "pdf",
      "ppt",
      "xls",
      "xlsx",
      "doc",
      "jpeg",
      "jpg",
      "png",
    ],
    width: "100%",
    placeholder: oBundle.getText("Choose_a_file_for_uploading"),
    parameters: [
      new sap.ui.unified.FileUploaderParameter({
        name: "name",
        value: blob_name,
      }),
      new sap.ui.unified.FileUploaderParameter({
        name: "email",
        value: userFolder,
      }),
    ],
    uploadProgress: function (oEvent) {
      var nLoaded, nTotal;
      if (oEvent.getParameter("lengthComputable")) {
        nLoaded = oEvent.getParameter("loaded");
        nTotal = oEvent.getParameter("total");
        oDialogAttachment.setText(Math.floor((nLoaded / nTotal) * 100) + "%");
      }
    },
    fileSizeExceed: function (oEvent) {
      oDialogAttachment.close();
      sap.m.MessageBox.error(oBundle.getText("file_size_warning"));
    },
    typeMissmatch: function (oEvent) {
      oDialogAttachment.close();
      sap.m.MessageBox.error(oBundle.getText("This_is_not_valid_file_type"));
    },
    uploadAborted: function (oEvent) {
      standartBusyDialog.close();
    },
    uploadComplete: function (oEvent) {
      var ext = oEvent.getParameter("responseRaw").replace(/"/g, "");
      var attachName = attachmentName.getValue();
      var attachment_type = attachedTypeDB.getValue();

      var attachment_url =
        "https://oxmaint.com/upload/workorder_attachment/" +
        userFolder +
        "/" +
        blob_name +
        "." +
        ext;

      var created_date = getIndonesianTime();
      Car_Workorder_Attachment.insert({
        master_email: emailUser,
        wo_id: workorderID,
        wo_number: workorderID,
        attachment_name: attachName,
        attached_by: operatedBy,
        attached_date: created_date,
        attachment_url: attachment_url,
        attachment_type: attachment_type,
      }).done(function () {
        funWorkorderAttachment();
        oDialogAttachment.close();
        oDialog.close();
      });
    },
  });

  var attachmentName = new sap.m.TextArea({
    width: "100%",
    height: "100px",
    rows: 3,
    wrapping: sap.ui.core.Wrapping.on,
  });

  var attachedTypeDB = new sap.m.ComboBox();
  attachedTypeDB.setWidth("100%");
  attachedTypeDB.addItem(
    new sap.ui.core.ListItem({ key: "1", text: oBundle.getText("Select_Type") })
  );
  attachedTypeDB.addItem(
    new sap.ui.core.ListItem({ key: "2", text: oBundle.getText("BROKEN_PART") })
  );
  attachedTypeDB.addItem(
    new sap.ui.core.ListItem({
      key: "3",
      text: oBundle.getText("EMERGENCY_ROAD_ASSITANCE_DOCUMENT"),
    })
  );
  attachedTypeDB.addItem(
    new sap.ui.core.ListItem({
      key: "4",
      text: oBundle.getText("ERA_DOCUMENT"),
    })
  );
  attachedTypeDB.addItem(
    new sap.ui.core.ListItem({
      key: "5",
      text: oBundle.getText("INSURANCE_DOCUMENT"),
    })
  );
  attachedTypeDB.addItem(
    new sap.ui.core.ListItem({
      key: "6",
      text: oBundle.getText("LICENSE_PLATE"),
    })
  );
  attachedTypeDB.addItem(
    new sap.ui.core.ListItem({
      key: "7",
      text: oBundle.getText("NON_INSURANCE_DOCUMENT"),
    })
  );
  attachedTypeDB.addItem(
    new sap.ui.core.ListItem({ key: "8", text: oBundle.getText("ODOMETER") })
  );
  attachedTypeDB.addItem(
    new sap.ui.core.ListItem({
      key: "9",
      text: oBundle.getText("REIMBURSEMENT"),
    })
  );
  attachedTypeDB.addItem(
    new sap.ui.core.ListItem({
      key: "10",
      text: oBundle.getText("TECHNICAL_SERVICE_REPORT_WORKSHOP"),
    })
  );
  attachedTypeDB.addItem(
    new sap.ui.core.ListItem({
      key: "11",
      text: oBundle.getText("WORKSHOP_INVOICE"),
    })
  );
  attachedTypeDB.setSelectedKey("1");
  attachedTypeDB.addEventDelegate({
    onAfterRendering: function (e) {
      attachedTypeDB.$().find("input").attr("readonly", true);
    },
  });

  var attachInspection = new sap.m.Input({
    showValueHelp: true,
    showSuggestion: true,
    valueHelpOnly: true,
    placeholder: oBundle.getText("Select_Inspection_Report"),
    valueHelpRequest: function () {
      var vehicle_number = oTFWOV1.getValue();
      var vehicle_number_ex = HVICore.getElementById(
        "vehicle_number_execution"
      ).getText();

      if (vehicle_number.trim() == "") {
        vehicle_number = vehicle_number_ex;
      }
      if (vehicle_number.trim() == "") {
        sap.m.MessageBox.error(oBundle.getText("Please_select_vehicle"));
        return;
      }
      linkInspection(2, vehicle_number, attachInspection);
    },
  });

  var file_element = new sap.ui.layout.form.FormElement({
    label: new sap.m.Label({
      required: true,
      text: oBundle.getText("Select_File"),
    }),
    fields: [oFileUploaderAttachment],
  });
  var inspection_element = new sap.ui.layout.form.FormElement({
    visible: false,
    label: new sap.m.Label({
      required: true,
      text: oBundle.getText("Select_Inspection_Report"),
    }),
    fields: [attachInspection],
  });

  var oLayoutForm = new sap.ui.layout.form.Form({
    editable: true,
    layout: new sap.ui.layout.form.ResponsiveGridLayout(),
    formContainers: [
      new sap.ui.layout.form.FormContainer({
        formElements: [
          new sap.ui.layout.form.FormElement({
            label: new sap.m.Label({
              required: true,
              text: oBundle.getText("Attachment_Type"),
            }),
            fields: [attachedTypeDB],
          }),
          new sap.ui.layout.form.FormElement({
            label: new sap.m.Label({
              text: oBundle.getText("Attachment_Description"),
            }),
            fields: [attachmentName],
          }),
          file_element,
          inspection_element,
        ],
      }),
    ],
  });

  // attachedTypeDB.attachSelectionChange(function () {
  //     var key = attachedTypeDB.getSelectedKey();
  //     if (key == "6") {
  //         file_element.setVisible(false);
  //         inspection_element.setVisible(true);
  //     }else {
  //         file_element.setVisible(true);
  //         inspection_element.setVisible(false);
  //     }
  // });

  var oDialog = new sap.m.Dialog({
    contentWidth: "50%",
    draggable: true,
    resizable: true,
    title: oBundle.getText("Upload_Work_Order_Attachment"),
    state: sap.ui.core.ValueState.Success,
    content: [oLayoutForm],
    buttons: [
      new sap.m.Button({
        text: oBundle.getText("Upload"),
        icon: "sap-icon://upload",
        press: function () {
          var attachName = attachmentName.getValue();
          var attachment_type = attachedTypeDB.getValue();
          var attachment_typeKey = attachedTypeDB.getSelectedKey();
          if (attachment_typeKey == "1") {
            sap.m.MessageBox.error(oBundle.getText("Select_attachment_type"));
            return;
          }

          // if (attachment_typeKey == "6") {

          //     var attachment_inspection_value = attachInspection.getValue();
          //     var attachment_inspection_url = attachInspection.getName();
          //     if(textFieldValidation(attachInspection,attachment_inspection_value)){return;}

          //     var created_date = getIndonesianTime();
          //     Car_Workorder_Attachment.insert({master_email:emailUser, wo_number:workorderID, wo_id: workorderID, attachment_name: attachName,
          //         attached_by: operatedBy, attached_date: created_date, attachment_type: attachment_type,attachment_url: attachment_inspection_url,
          //     }).done(function () {
          //         funWorkorderAttachment();
          //         oDialogAttachment.close();
          //         oDialog.close();

          //     });
          // }else{
          if (oFileUploaderAttachment.getValue() != "") {
            oDialogAttachment.open();
            oFileUploaderAttachment.upload();
          } else {
            sap.m.MessageBox.error(oBundle.getText("Select_file_for_upload"));
          }
          // }
        },
      }),
      new sap.m.Button({
        text: oBundle.getText("Cancel"),
        icon: "sap-icon://decline",
        press: function () {
          oDialog.close();
        },
      }),
    ],
  }).open();
}

function funWorkorderAttachment() {
  Car_Workorder_Attachment.where({
    master_email: emailUser,
    wo_id: workorderID,
  })
    .take(1000)
    .read()
    .done(function (results) {
      //alert( JSON.stringify(results));

      var oModel = new sap.ui.model.json.JSONModel();
      oModel.setData({ modelData: results });

      oTableWOAttachment.setModel(oModel);
      oTableWOAttachment.bindItems({
        path: "/modelData",
        template: oTableAttachmentTemplate,
      });

      // oTableAttachmentWOExecution.setModel(oModel);
      // oTableAttachmentWOExecution.bindItems({path: "/modelData",template : oTableAttachmentTemplate});
    });
}

//////////////////////////End Attachment Details//////////////////////////

function addUpdateRemarkDialog(src, obj) {
  var field1 = new sap.m.TextArea({
    width: "100%",
    height: "100px",
    rows: 2,
    wrapping: sap.ui.core.Wrapping.on,
  });

  var oForm1 = new sap.ui.layout.form.Form({
    editable: true,
    layout: new sap.ui.layout.form.ResponsiveGridLayout(),
    formContainers: [
      new sap.ui.layout.form.FormContainer({
        formElements: [
          new sap.ui.layout.form.FormElement({
            label: new sap.m.Label({
              required: true,
              text: oBundle.getText("Remark"),
            }),
            fields: [field1],
          }),
        ],
      }),
    ],
  });

  var oButton = new sap.m.Button({
    text: oBundle.getText("Add"),
    icon: "sap-icon://add",
    press: function () {
      var remark = field1.getValue();

      var added_date = getIndonesianTime();
      var added_by = operatedBy;

      if (textFieldValidation(field1, remark)) {
        return;
      }

      oButton.setEnabled(false);

      oTableWORemark.setBusy(true);
      oDialog.close();
      if (src == "update") {
        Car_Workorder_Remark.update({ id: obj["id"], remark: remark }).done(
          function () {
            funWorkorderRemark();
          },
          failure
        );
      } else {
        Car_Workorder_Remark.insert({
          master_email: emailUser,
          wo_number: workorderID,
          wo_id: workorderID,
          remark: remark,
          added_date: added_date,
          added_by: added_by,
        }).done(function () {
          funWorkorderRemark();
        }, failure);
      }
    },
  });

  var oDialog = new sap.m.Dialog({
    draggable: true,
    resizable: true,
    contentWidth: "30%",
    title: oBundle.getText("Add_Remark"),
    content: [oForm1],
    buttons: [
      oButton,
      new sap.m.Button({
        text: oBundle.getText("Cancel"),
        icon: "sap-icon://decline",
        press: function () {
          oDialog.close();
        },
      }),
    ],
  }).open();

  if (src == "update") {
    oDialog.setTitle(oBundle.getText("Update_Remark"));
    oButton.setText(oBundle.getText("Update"));
    oButton.setIcon("sap-icon://edit");
    field1.setValue(obj["remark"]);
  }
}

function funWorkorderRemark() {
  Car_Workorder_Remark.where({ master_email: emailUser, wo_id: workorderID })
    .take(1000)
    .read()
    .done(function (results) {
      var oModel = new sap.ui.model.json.JSONModel();
      oModel.setData({ modelData: results });

      oTableWORemark.setModel(oModel);
      oTableWORemark.bindItems({
        path: "/modelData",
        template: oTableWORemarkTemplate,
      });
      oTableWORemark.setBusy(false);
      //var tabItems =  woIconTab.getItems();
      //tabItems[5].setCount(results.length);

      // oTableWORemarkExecution.setModel(oModel);
      // oTableWORemarkExecution.bindItems({ path: "/modelData",
      //     template: oTableWORemarkTemplate
      // });

      var temp = new sap.suite.ui.commons.TimelineItem({
        dateTime: "{added_date}",
        userNameClickable: true,
        title: {
          path: "added_by",
          formatter: function (added_by) {
            if (added_by != null) {
              var teamList = teamJSONArray.filter(function (obj, index) {
                if (added_by == obj.emailid) {
                  return true;
                }
                return false;
              });

              if (teamList.length > 0) {
                var role = teamList[0]["role"];
                if (role == "1" || role == oBundle.getText("Operator")) {
                  return oBundle.getText("Operator");
                } else if (
                  role == "2" ||
                  role == oBundle.getText("Technician")
                ) {
                  return oBundle.getText("Technician");
                } else if (role == "3" || role == oBundle.getText("Employee")) {
                  return oBundle.getText("Employee");
                } else if (role == "4") {
                  return oBundle.getText("Sub_Admin");
                }
              }
            }
            return "";
          },
        },
        userPicture: "Images/icons/person.png",
        userName: "{added_by}",
        icon: "sap-icon://notes",
        text: "{remark}",
      });

      // woTimeLine.bindAggregation("content",{ path: "/modelData",
      //     template: temp
      // });

      // woTimeLine.setModel(oModel);
    });
}

/*
function addUpdateAdditionalCostDialog(src, obj) {
  var field1 = new sap.m.TextArea({
    width: "100%",
    height: "100px",
    rows: 2,
    wrapping: sap.ui.core.Wrapping.on,
  });
  var field2 = new sap.m.Input({ type: "Number", value: "", width: "100%" });

  var oForm1 = new sap.ui.layout.form.Form({
    editable: true,
    layout: new sap.ui.layout.form.ResponsiveGridLayout(),
    formContainers: [
      new sap.ui.layout.form.FormContainer({
        formElements: [
          new sap.ui.layout.form.FormElement({
            label: new sap.m.Label({
              required: true,
              text: oBundle.getText("Cost_Description"),
            }),
            fields: [field1],
          }),
          new sap.ui.layout.form.FormElement({
            label: new sap.m.Label({
              required: true,
              text: oBundle.getText("Cost"),
            }),
            fields: [field2],
          }),
        ],
      }),
    ],
  });

  var oButton = new sap.m.Button({
    text: oBundle.getText("Add"),
    icon: "sap-icon://add",
    press: function () {
      var description = field1.getValue();
      var cost = field2.getValue();

      var added_date = getIndonesianTime();
      var added_by = operatedBy;

      if (textFieldValidation(field1, description)) {
        return;
      }
      if (textFieldValidation(field2, cost)) {
        return;
      }

      if (minusCheck(cost)) {
        sap.m.MessageBox.error(oBundle.getText("Enter_valid_cost"));
        return;
      }
      oButton.setEnabled(false);
      oTableWOAdditionalCost.setBusy(true);
      oDialog.close();
      if (src == "update") {
        Car_Workorder_Cost.update({
          id: obj["id"],
          description: description,
          cost: cost,
        }).done(function () {
          funWorkorderAdditionalCost();
        }, failure);
      } else {
        Car_Workorder_Cost.insert({
          master_email: emailUser,
          wo_number: workorderID,
          wo_id: workorderID,
          description: description,
          cost: cost,
          added_date: added_date,
          added_by: added_by,
        }).done(function () {
          funWorkorderAdditionalCost();
        }, failure);
      }
    },
  });
  var oDialog = new sap.m.Dialog({
    draggable: true,
    resizable: true,
    contentWidth: "30%",
    title: oBundle.getText("Add_Additional_Cost"),
    content: [oForm1],
    buttons: [
      oButton,
      new sap.m.Button({
        text: oBundle.getText("Cancel"),
        icon: "sap-icon://decline",
        press: function () {
          oDialog.close();
        },
      }),
    ],
  }).open();

  if (src == "update") {
    oDialog.setTitle(oBundle.getText("Update_Cost"));
    oButton.setText(oBundle.getText("Update"));
    oButton.setIcon("sap-icon://edit");
    field1.setValue(obj["description"]);
    field2.setValue(obj["cost"]);
  }
}*/
/*
function funWorkorderAdditionalCost() {
  Car_Workorder_Cost.where({ master_email: emailUser, wo_id: workorderID })
    .take(1000)
    .read()
    .done(function (results) {
      var oModel = new sap.ui.model.json.JSONModel();
      oModel.setData({ modelData: results });

      oTableWOAdditionalCost.setModel(oModel);
      oTableWOAdditionalCost.bindItems({
        path: "/modelData",
        template: oTableWOAdditionalCostTemplate,
      });
      oTableWOAdditionalCost.setBusy(false);

      oTableWOAdditionalCostExecution.setModel(oModel);
      oTableWOAdditionalCostExecution.bindItems({
        path: "/modelData",
        template: oTableWOAdditionalCostTemplate,
      });

      calculatingAdditionalCost();
    });
}*/

function assignedTeamDialog(src, InputValue) {
  var oSelectDialog = new sap.m.SelectDialog({
    contentWidth: "50%",
    draggable: true,
    resizable: true,
    rememberSelections: true,
    multiSelect: true,
    noDataText: oBundle.getText("No_Data"),
    liveChange: function (oEvent) {
      (sSearchValue = oEvent.getParameter("value")),
        (oBinding = oEvent.getParameter("itemsBinding"));
      if (oBinding) {
        var oFilters = [
          new sap.ui.model.Filter(
            "name",
            sap.ui.model.FilterOperator.Contains,
            sSearchValue
          ),
          new sap.ui.model.Filter(
            "emailid",
            sap.ui.model.FilterOperator.Contains,
            sSearchValue
          ),
          new sap.ui.model.Filter(
            "role",
            sap.ui.model.FilterOperator.Contains,
            sSearchValue
          ),
        ];
        var filterObj = new sap.ui.model.Filter(oFilters, false);
        oBinding.filter(filterObj);
      } else {
        oBinding.filter([]);
      }
    },
    confirm: function (oEvent) {
      if (src == 2) {
        var selectedItem = oEvent.getParameter("selectedItem");
        taskAssignedInput.setValue(selectedItem.getDescription());
      } else if (src == 3) {
        var selectedItem = oEvent.getParameter("selectedItem");
        addLaborInput.setValue(selectedItem.getDescription());
      } else if (src == 4) {
        InputValue.removeAllTokens();
        var tokenList = InputValue.getTokens();
        var aContexts = oEvent.getParameter("selectedContexts");
        if (aContexts && aContexts.length) {
          aContexts.map(function (oContext) {
            var name = oContext.getObject()["name"];
            var emailId = oContext.getObject()["emailid"];

            var insertFlag = true;
            for (var j = 0; j < tokenList.length; j++) {
              if (tokenList[j].getKey() == emailId) {
                insertFlag = false;
              }
            }
            if (tokenList.length == 0 || insertFlag) {
              InputValue.addToken(
                new sap.m.Token({ key: emailId, text: name })
              );
            }
          });
        }
      } else {
        var tokenList = woAssignedInput.getTokens();
        var aContexts = oEvent.getParameter("selectedContexts");
        if (aContexts && aContexts.length) {
          aContexts.map(function (oContext) {
            var name = oContext.getObject()["user_name"];
            var user_id = oContext.getObject()["user_id"];

            var insertFlag = true;
            for (var j = 0; j < tokenList.length; j++) {
              if (tokenList[j].getKey() == user_id) {
                insertFlag = false;
              }
            }
            if (tokenList.length == 0 || insertFlag) {
              woAssignedInput.addToken(
                new sap.m.Token({ key: user_id, text: name })
              );
              // insetLaborTable(user_id, name);
            }
          });
        }
      }
    },
  });

  if (src == 2) {
    oSelectDialog.setMultiSelect(false);
    oSelectDialog.setRememberSelections(false);
    oSelectDialog.setTitle(oBundle.getText("Select_Team_Member"));
  } else if (src == 3) {
    oSelectDialog.setMultiSelect(false);
    oSelectDialog.setRememberSelections(false);
    oSelectDialog.setTitle(oBundle.getText("Select_Worker"));
  } else if (src == 4) {
    oSelectDialog.setMultiSelect(false);
  } else {
    oSelectDialog._getOkButton().setText(oBundle.getText("Select"));
    oSelectDialog.setTitle(oBundle.getText("Select_Team_Member"));
  }

  var oItemTemplate = new sap.m.StandardListItem({
    title: "{user_name}",
    description: "{user_id}",
    icon: "{image}",
    type: "Active",
    info: {
      path: "role",
      formatter: function (role) {
        if (role == oBundle.getText("Administrator")) {
          return oBundle.getText("Administrator");
        } else if (role == oBundle.getText("Account_Payable_Team")) {
          return oBundle.getText("Account_Payable_Team");
        } else if (role == oBundle.getText("Driver")) {
          return oBundle.getText("Driver");
        } else if (role == oBundle.getText("Maintenance_Team")) {
          return oBundle.getText("Maintenance_Team");
        } else if (role == oBundle.getText("Quality_Team")) {
          return oBundle.getText("Quality_Team");
        } else if (role == oBundle.getText("Supplier")) {
          return oBundle.getText("Supplier");
        } else if (role == oBundle.getText("Workshop")) {
          return oBundle.getText("Workshop");
        }
      },
    },
  });

  var result = [];

  if (src == 1) {
    var tokenList = woAssignedInput.getTokens();
    result = team4WJSONData.filter(function (obj, index) {
      for (var j = 0; j < tokenList.length; j++) {
        if (tokenList[j].getKey() == obj.emailid) {
          return false;
        }
      }
      return true;
    });
  } else if (src == 3) {
    var objLabor = oTableLaborItemWO.getItems();
    result = team4WJSONData.filter(function (obj, index) {
      for (var i = 0; i < objLabor.length; i++) {
        var user_id = objLabor[i].getBindingContext().getObject().user_id;
        if (user_id == obj.emailid) {
          return false;
        }
      }
      return true;
    });
  } else {
    result = team4WJSONData;
  }
  result.sort(function (a, b) {
    a = a.user_name.toLowerCase();
    b = b.user_name.toLowerCase();
    return a < b ? -1 : a > b ? 1 : 0;
  });

  var oModel = new sap.ui.model.json.JSONModel();
  oModel.setData({ modelData: result });
  oSelectDialog.setModel(oModel);
  oSelectDialog.bindAggregation("items", "/modelData", oItemTemplate);
  oSelectDialog.open();

  oSelectDialog._getCancelButton().setText(oBundle.getText("Cancel"));
}

// function insetLaborTable(user_id,labor_name){

//     var current_date = getIndonesianTime();
//     var item = { master_email: emailUser, wo_id: workorderID,
//         user_id: user_id, labor_name: labor_name,
//         added_date: current_date, added_by: operatedBy,
//         labor_time:"0",labor_cost:"0",labor_note:""
//     };

//     var insertFlag = true;
//      var objLabor = oTableLaborItemWO.getItems();
//      for (var i = 0; i < objLabor.length; i++) {
//          var oContext = objLabor[i].getBindingContext();
//          if(oContext.getObject().user_id == user_id){
//              insertFlag = false;
//          }
//      }
//      if(insertFlag){
//         oTableLaborItemWO.setBusy(true);
//         HVI_WO_Labor.insert(item).done(function () {
//                         funWorkorderLabor();
//                     }, failure);
//      }
// }


//Old Link Inspection
// function linkInspection(src, vehicle_number, attachInspection) {
//   var oSelectDialog = new sap.m.SelectDialog({
//     contentWidth: "50%",
//     draggable: true,
//     resizable: true,
//     rememberSelections: true,
//     multiSelect: true,
//     title: oBundle.getText("Select_Inspection_Report"),
//     noDataText: oBundle.getText("No_Data"),
//     liveChange: function (oEvent) {
//       (sSearchValue = oEvent.getParameter("value")),
//         (oBinding = oEvent.getParameter("itemsBinding"));
//       if (oBinding) {
//         var oFilters = [
//           new sap.ui.model.Filter(
//             "report_number",
//             sap.ui.model.FilterOperator.Contains,
//             sSearchValue
//           ),
//           new sap.ui.model.Filter(
//             "inspection_date",
//             sap.ui.model.FilterOperator.Contains,
//             sSearchValue
//           ),
//           new sap.ui.model.Filter(
//             "license_number",
//             sap.ui.model.FilterOperator.Contains,
//             sSearchValue
//           ),
//         ];
//         var filterObj = new sap.ui.model.Filter(oFilters, false);
//         oBinding.filter(filterObj);
//       } else {
//         oBinding.filter([]);
//       }
//     },
//     confirm: function (oEvent) {
//       if (src == 2) {
//         var selectedItem = oEvent.getParameter("selectedItem");
//         attachInspection.setValue(selectedItem.getTitle());
//         attachInspection.setName(selectedItem.getIcon());
//       } else if (src == 3) {
//         inspectionLinkInput.removeAllTokens();
//         let allowedKeys = ["1", "2", "3", "4", "5", "6", "7"];
//         var items = oInputPartField0.getItems(); // Get all items
//         items.forEach(function (item) {
//           if (!allowedKeys.includes(item.getKey())) {
//             oInputPartField0.removeItem(item); // Remove the item if its key is not in the allowedKeys array
//           }
//         });

//         var tokenList = inspectionLinkInput.getTokens();
//         var aContexts = oEvent.getParameter("selectedContexts");
//         if (aContexts && aContexts.length) {
//           aContexts.map(function (oContext) {
//             var inspection_date = oContext.getObject()["inspection_date"];
//             var inspection_id = oContext.getObject()["id"];
//             var report_no = oContext.getObject()["report_number"];

//             var insertFlag = true;
//             for (var j = 0; j < tokenList.length; j++) {
//               if (tokenList[j].getText() == report_no) {
//                 insertFlag = false;
//               }
//             }
//             if (tokenList.length == 0 || insertFlag) {
//               inspectionLinkInput.addToken(
//                 new sap.m.Token({ key: inspection_date, text: report_no })
//               );

//               Car_Inspection_Item.where({
//                 master_email: emailUser,
//                 inspection_id: inspection_id,
//               })
//                 .read()
//                 .done(function (results) {
//                   if (results.length > 0) {
//                     results.forEach(function (item, index) {
//                       var newItem = new sap.ui.core.ListItem({
//                         key: item.task_name, // Use array index + 1 as key
//                         text: item.task_name, // Use array value as text
//                       });
//                       oInputPartField0.addItem(newItem);
//                     });
//                   }
//                 });
//             }
//           });
//         }
//       } else {
//         var tokenList = inspectionLinkInput.getTokens();
//         var aContexts = oEvent.getParameter("selectedContexts");
//         if (aContexts && aContexts.length) {
//           aContexts.map(function (oContext) {
//             var inspection_date = oContext.getObject()["inspection_date"];
//             var report_no = oContext.getObject()["report_number"];

//             var insertFlag = true;
//             for (var j = 0; j < tokenList.length; j++) {
//               if (tokenList[j].getText() == report_no) {
//                 insertFlag = false;
//               }
//             }
//             if (tokenList.length == 0 || insertFlag) {
//               inspectionLinkInput.addToken(
//                 new sap.m.Token({ key: inspection_date, text: report_no })
//               );
//             }
//           });
//         }
//         // var tokenList = inspectionLinkInput.getTokens();
//         // var selectedItems = oEvent.getParameter("selectedItems");
//         // if (selectedItems) {

//         //     for (var i = 0; i < selectedItems.length; i++) {
//         //         var insertFlag = true;
//         //         for (var j = 0; j < tokenList.length; j++) {
//         //             if (tokenList[j].getText() == selectedItems[i].getTitle()) {insertFlag = false;}
//         //         }
//         //         if (tokenList.length == 0 || insertFlag) {
//         //             inspectionLinkInput.addToken(new sap.m.Token({ key: selectedItems[i].getDescription(), text: selectedItems[i].getTitle() }));
//         //         }
//         //     }
//         //   }
//       }
//     },
//   });

//   if (src == 2) {
//     oSelectDialog.setMultiSelect(false);
//     oSelectDialog.setRememberSelections(false);
//   }

//   var oItemTemplate = new sap.m.StandardListItem({
//     title: "{report_number}",
//     description: "{inspection_date}",
//     info: "{license_number}",
//     icon: "{pdf_url}",
//     type: "Active",
//   });
//   if (src == 2) {
//     var result = inspectionJSONArray.filter(function (obj, index) {
//       if (obj.license_number == vehicle_number) {
//         return true;
//       } else {
//         return false;
//       }
//     });

//     var oModel = new sap.ui.model.json.JSONModel();
//     oModel.setData({ modelData: result });
//     oSelectDialog.setModel(oModel);
//     oSelectDialog.bindAggregation("items", "/modelData", oItemTemplate);
//   } else if (src == 3) {
//     oSelectDialog.setMultiSelect(false);
//     var result = inspectionJSONArray.filter(function (obj, index) {
//       if (
//         obj.license_number == vehicle_number && !nullCheckAll(obj["workorder"]) && 
//         (nullCheckAll(obj["repair"]) || nullCheckAll(obj["replace"]))
//       ) {
//         return true;
//       } else {
//         return false;
//       }
//     });

//     var oModel = new sap.ui.model.json.JSONModel();
//     oModel.setData({ modelData: result });
//     oSelectDialog.setModel(oModel);
//     oSelectDialog.bindAggregation("items", "/modelData", oItemTemplate);
//   } else {
//     var tokenList = inspectionLinkInput.getTokens();
//     var result = inspectionJSONArray.filter(function (obj, index) {
//       if (obj.vehicle_serial == vehicle_number) {
//         for (var j = 0; j < tokenList.length; j++) {
//           if (tokenList[j].getText() == obj.report_no) {
//             return false;
//           }
//         }
//         return true;
//       } else {
//         return false;
//       }
//     });

//     var oModel = new sap.ui.model.json.JSONModel();
//     oModel.setData({ modelData: result });
//     oSelectDialog.setModel(oModel);
//     oSelectDialog.bindAggregation("items", "/modelData", oItemTemplate);
//   }

//   oSelectDialog.open();
// }

// function linkInspection(src, vehicle_number, attachInspection) {
//   // Filter and prepare data with 'isSelected' property
//   let filteredData = inspectionJSONArray.filter(obj => obj.license_number === vehicle_number && !nullCheckAll(obj.workorder));
//   filteredData = filteredData.map(obj => {
//     obj.isSelected = false;
//     return obj;
//   });

//   const oModel = new sap.ui.model.json.JSONModel({ modelData: filteredData });

//   const oDialog = new sap.m.Dialog({
//     title: oBundle.getText("Select_Inspection_Report"),
//     contentWidth: "80%",
//     draggable: true,
//     resizable: true,
//     horizontalScrolling: true,
//     verticalScrolling: true,
//     buttons: [
//       new sap.m.Button({
//         text: oBundle.getText("OK"),
//         press: function () {
//           const selectedItem = oTable.getItems().find(item =>
//             item.getBindingContext().getProperty("isSelected")
//           );

//           if (!selectedItem) {
//             sap.m.MessageToast.show("Please select a report.");
//             return;
//           }

//           const selectedData = selectedItem.getBindingContext().getObject();

//           attachInspection.setValue(selectedData.report_number);
//           attachInspection.setName(selectedData.pdf_url);
//           oDialog.close();
//         }
//       }),
//       new sap.m.Button({
//         text: oBundle.getText("Cancel"),
//         press: () => oDialog.close()
//       })
//     ]
//   });

//   const oTable = new sap.m.Table({
//     mode: "None",
//     columns: [
//       new sap.m.Column({ header: new sap.m.Label({ text: "" }) }),
//       new sap.m.Column({header: new sap.m.Label({wrapping:true,text: oBundle.getText("Report_No"),design: sap.m.LabelDesign.Bold})}),
//       new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Date"),design: sap.m.LabelDesign.Bold}),
//       minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
//       new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Vehicle_Details"), design: sap.m.LabelDesign.Bold}),
//       minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
     
//       new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Location"), design: sap.m.LabelDesign.Bold}),
//       minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),
//       new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Inspector"), design: sap.m.LabelDesign.Bold}),
//       minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),

//       new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Fault"), design: sap.m.LabelDesign.Bold}),
//       minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
//       new sap.m.Column({header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Linked_Wo"), design: sap.m.LabelDesign.Bold}),
//       minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),
//       new sap.m.Column({ header: TableHeader.clone().setText(oBundle.getText("Note")),
//       minScreenWidth : "2500px",popinDisplay : "Inline",demandPopin : true}),
//     ],
//     items: {
//       path: "/modelData",
//       template: new sap.m.ColumnListItem({
//         cells: [
//           new sap.m.CheckBox({
//             selected: "{isSelected}",
//             select: function (oEvent) {
//               const context = oEvent.getSource().getBindingContext();
//               const model = context.getModel();
//               const data = model.getProperty("/modelData");

//               // Uncheck all checkboxes first
//               data.forEach(item => item.isSelected = false);

//               // Set selected checkbox only
//               const path = context.getPath();
//               model.setProperty(path + "/isSelected", oEvent.getParameter("selected"));
//               model.refresh();
//             }
//           }),
//           new sap.m.VBox({
//             items:[new sap.m.Label({wrapping:true,text: "{report_number}"}),
//                    new sap.tnt.InfoLabel({colorScheme:3,
//                     text: { path: "vehicle_status",
//                     formatter: function (vehicle_status) {
//                         if (vehicle_status != null &&  vehicle_status != "") {
//                             if(vehicle_status=="Breakdown") {
//                                 this.setVisible(true);
//                             }else{
//                                 this.setVisible(false);
//                             }
//                         }else{
//                             this.setVisible(false);
//                         }
//                         return oBundle.getText("Breakdown");
//                     }
//                 }
//                 }).addStyleClass("sapUiTinyMarginTop"),
//           ]}).addStyleClass("sapUiTinyMargin"),
//           new sap.m.Label({ wrapping: true, text: "{inspection_date}" }),
//           new sap.m.VBox({
//             items:[new sap.m.Label({ wrapping: true, text: "{license_number}" }),
//                    new sap.m.Label({ wrapping: true, text: "{chassis_number}" }).addStyleClass("sapUiTinyMarginTop"),
//             ]
//           }).addStyleClass("sapUiTinyMargin"),
//           new sap.m.Label({ wrapping: true, text: "{location}" }),
//           new sap.m.Label({ wrapping: true, text: "{inspector_name}" }),
//           new sap.m.Button({
//             icon: "sap-icon://message-warning",
//             type: sap.m.ButtonType.Reject,
//             text: {
//                 parts: [{ path: "repair", type: new sap.ui.model.type.String() },
//                         { path: "replace", type: new sap.ui.model.type.String()}],
//                 formatter: function (repair, replace) {
//                     var repairArray = [];
//                     var replaceArray = [];
//                     if (repair != null) {
//                         var repairArray = repair.split("^");
//                     }
//                     if (replace != null) {
//                         var replaceArray = replace.split("^");
//                     }

//                     if (repairArray.length > 1 || replaceArray.length > 1) {
//                         this.setVisible(true);
//                         return (repairArray.length - 1) + (replaceArray.length - 1);
//                     } else {
//                         this.setVisible(false);
//                     }
//                 }
//             },
//             press: function (event) {
//                 var model = this.getModel();
//                 var path = event.getSource().getBindingContext().getPath();
//                 var obj = model.getProperty(path);
//                 viewDefect(obj['repair'], obj['replace']);
//             }
//           }),
//           new sap.m.Link({ emphasized: true,
//             text: {
//                 path: "workorder",
//                 formatter: function (ref_workorder) {
//                     var refArray = [];
//                     if (ref_workorder != null) {
//                         refArray = ref_workorder.split("^");
//                         if (refArray.length == 1) {
//                             return refArray[0];
//                         } else {
//                             return refArray[0]+"/...";
//                         }
//                     }
//                 }
//             },
//             press: function (event) {
//                 var model = this.getModel();
//                 var path = event.getSource().getBindingContext().getPath();
//                 var obj = model.getProperty(path);

//                 var ref_workorder = obj['workorder']
//                 var refArray = [];
//                 if (ref_workorder != null) {
//                     refArray = ref_workorder.split("^");
//                 }
//                 refrenceWorkorder(refArray, obj['license_number']);
//             }
//           }),
//           new sap.m.HBox({
//             items:[ new sap.m.Label({wrapping:true,text: "{group_name}"}).addStyleClass("sapUiTinyMarginEnd sapUiTinyMarginTop"),
//                     new sap.m.Button({
//                         icon: "sap-icon://pdf-attachment",
//                         type: sap.m.ButtonType.Transparent,
//                         text: { path: "uploaded",
//                             formatter: function (uploaded) {
//                                 if (uploaded != null && uploaded =="") {
//                                     this.setVisible(false);
//                                 } else {
//                                     this.setVisible(true);
//                                 }
//                         }},
//                         press: function (e) {
//                             var model = this.getModel();
//                             var path = e.getSource().getBindingContext().getPath();
//                             var obj = model.getProperty(path);
//                             var blob_path = obj['pdf_url'];
    
//                             window.open(blob_path, "_blank");
//                         }
//                     })
//           ]}),
//           new sap.m.Label({
//             text: {
//             parts: [{ path: "remark", type: new sap.ui.model.type.String() },
//                     { path: "repair_note", type: new sap.ui.model.type.String() },
//                     { path: "replace_note", type: new sap.ui.model.type.String()}],
//             formatter: function (remark, repair_note, replace_note) {
//                 var allNote ="";
//                 if (remark != null && remark != "") {
//                     allNote = remark+", ";
//                 }
//                 if (repair_note != null && repair_note != "") {
//                     allNote = allNote + repair_note+", ";
//                 }
//                 if (replace_note != null && replace_note != "") {
//                     allNote = allNote + replace_note;
//                 }

//                 return allNote.replace(/\^/g, ", ");
//             }}
//           }) 
//         ]
//       })
//     }
//   });

//   oTable.setModel(oModel);
//   oDialog.addContent(oTable);
//   oDialog.open();
// }

function linkInspection(src, vehicle_number, attachInspection) {
  var oDialog, oTable, oSearchField, selectedContext = null;

  var oModel = new sap.ui.model.json.JSONModel();
  var filteredData;

  if (src === 2) {
    filteredData = inspectionJSONArray.filter(obj => obj.license_number === vehicle_number);
  } else if (src === 3) {
    filteredData = inspectionJSONArray.filter(obj =>
      obj.license_number === vehicle_number &&
      !nullCheckAll(obj["workorder"]) &&
      (nullCheckAll(obj["repair"]) || nullCheckAll(obj["replace"]))
    );
  } else {
    const tokenList = inspectionLinkInput.getTokens();
    filteredData = inspectionJSONArray.filter(obj =>
      obj.vehicle_serial === vehicle_number &&
      !tokenList.some(t => t.getText() === obj.report_no)
    );
  }

  oModel.setData({ modelData: filteredData });

  var oTemplate = new sap.m.ColumnListItem({
    cells: [
      new sap.m.CheckBox({
        selected: false,
        select: function (oEvent) {
          var items = oTable.getItems();
          items.forEach(item => {
            var cb = item.getCells()[0];
            if (cb !== oEvent.getSource()) {
              cb.setSelected(false);
            }
          });
          selectedContext = oEvent.getSource().getBindingContext();
        }
      }),
      new sap.m.VBox({
        items:[new sap.m.Label({wrapping:true,text: "{report_number}"}),
                new sap.tnt.InfoLabel({colorScheme:3,
                text: { path: "vehicle_status",
                formatter: function (vehicle_status) {
                    if (vehicle_status != null &&  vehicle_status != "") {
                        if(vehicle_status=="Breakdown") {
                            this.setVisible(true);
                        }else{
                            this.setVisible(false);
                        }
                    }else{
                        this.setVisible(false);
                    }
                    return oBundle.getText("Breakdown");
                }
            }
            }).addStyleClass("sapUiTinyMarginTop"),
      ]}).addStyleClass("sapUiTinyMargin"),
      new sap.m.Label({ wrapping: true, text: "{inspection_date}" }),
      new sap.m.VBox({
        items:[new sap.m.Label({ wrapping: true, text: "{license_number}" }),
                new sap.m.Label({ wrapping: true, text: "{chassis_number}" }).addStyleClass("sapUiTinyMarginTop"),
        ]
      }).addStyleClass("sapUiTinyMargin"),
      new sap.m.Label({ wrapping: true, text: "{location}" }),
      new sap.m.Label({ wrapping: true, text: "{inspector_name}" }),
      new sap.m.Button({
        icon: "sap-icon://message-warning",
        type: sap.m.ButtonType.Reject,
        text: {
            parts: [{ path: "repair", type: new sap.ui.model.type.String() },
                    { path: "replace", type: new sap.ui.model.type.String()}],
            formatter: function (repair, replace) {
                var repairArray = [];
                var replaceArray = [];
                if (repair != null) {
                    var repairArray = repair.split("^");
                }
                if (replace != null) {
                    var replaceArray = replace.split("^");
                }

                if (repairArray.length > 1 || replaceArray.length > 1) {
                    this.setVisible(true);
                    return (repairArray.length - 1) + (replaceArray.length - 1);
                } else {
                    this.setVisible(false);
                }
            }
        },
        press: function (event) {
            var model = this.getModel();
            var path = event.getSource().getBindingContext().getPath();
            var obj = model.getProperty(path);
            viewDefect(obj['repair'], obj['replace']);
        }
      }),
      new sap.m.Link({ emphasized: true,
        text: {
            path: "workorder",
            formatter: function (ref_workorder) {
                var refArray = [];
                if (ref_workorder != null) {
                    refArray = ref_workorder.split("^");
                    if (refArray.length == 1) {
                        return refArray[0];
                    } else {
                        return refArray[0]+"/...";
                    }
                }
            }
        },
        press: function (event) {
            var model = this.getModel();
            var path = event.getSource().getBindingContext().getPath();
            var obj = model.getProperty(path);

            var ref_workorder = obj['workorder']
            var refArray = [];
            if (ref_workorder != null) {
                refArray = ref_workorder.split("^");
            }
            refrenceWorkorder(refArray, obj['license_number']);
        }
      }),
      new sap.m.HBox({
        items:[ new sap.m.Label({wrapping:true,text: "{group_name}"}).addStyleClass("sapUiTinyMarginEnd sapUiTinyMarginTop"),
                new sap.m.Button({
                    icon: "sap-icon://pdf-attachment",
                    type: sap.m.ButtonType.Transparent,
                    text: { path: "uploaded",
                        formatter: function (uploaded) {
                            if (uploaded != null && uploaded =="") {
                                this.setVisible(false);
                            } else {
                                this.setVisible(true);
                            }
                    }},
                    press: function (e) {
                        var model = this.getModel();
                        var path = e.getSource().getBindingContext().getPath();
                        var obj = model.getProperty(path);
                        var blob_path = obj['pdf_url'];

                        window.open(blob_path, "_blank");
                    }
                })
      ]}),
      new sap.m.Label({
        text: {
        parts: [{ path: "remark", type: new sap.ui.model.type.String() },
                { path: "repair_note", type: new sap.ui.model.type.String() },
                { path: "replace_note", type: new sap.ui.model.type.String()}],
        formatter: function (remark, repair_note, replace_note) {
            var allNote ="";
            if (remark != null && remark != "") {
                allNote = remark+", ";
            }
            if (repair_note != null && repair_note != "") {
                allNote = allNote + repair_note+", ";
            }
            if (replace_note != null && replace_note != "") {
                allNote = allNote + replace_note;
            }

            return allNote.replace(/\^/g, ", ");
        }}
      }) 
    ]
  });

  oTable = new sap.m.Table({
    growing: true,
    growingScrollToLoad: true,
    columns: [
      new sap.m.Column({ width: "5%" }),
      new sap.m.Column({header: new sap.m.Label({wrapping:true,text: oBundle.getText("Report_No"),design: sap.m.LabelDesign.Bold})}),
      new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Date"),design: sap.m.LabelDesign.Bold}),
      minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
      new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Vehicle_Details"), design: sap.m.LabelDesign.Bold}),
      minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
      
      new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Location"), design: sap.m.LabelDesign.Bold}),
      minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),
      new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Inspector"), design: sap.m.LabelDesign.Bold}),
      minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),

      new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Fault"), design: sap.m.LabelDesign.Bold}),
      minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
      new sap.m.Column({header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Linked_Wo"), design: sap.m.LabelDesign.Bold}),
      minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),
      new sap.m.Column({ header: TableHeader.clone().setText(oBundle.getText("Note")),
      minScreenWidth : "2500px",popinDisplay : "Inline",demandPopin : true}),
    
    ],
    items: {
      path: "/modelData",
      template: oTemplate
    }
  });

  oSearchField = new sap.m.SearchField({
    width: "100%",
    liveChange: function (oEvent) {
      var sQuery = oEvent.getSource().getValue().toLowerCase();
      var data = filteredData.filter(obj =>
        (obj.report_number || "").toLowerCase().includes(sQuery) ||
        (obj.inspection_date || "").toLowerCase().includes(sQuery) ||
        (obj.license_number || "").toLowerCase().includes(sQuery) ||
        (obj.group_name || "").toLowerCase().includes(sQuery) ||
        (obj.location || "").toLowerCase().includes(sQuery) ||
        (obj.inspector_name || "").toLowerCase().includes(sQuery) || 
        (obj.inspector_id || "").toLowerCase().includes(sQuery) 
      );
      oModel.setData({ modelData: data });
    }
  });

  oDialog = new sap.m.Dialog({
    title: oBundle.getText("Select_Inspection_Report"),
    contentWidth: "60%",
    contentHeight: "auto",
    draggable: true,
    resizable: true,
    content: [oSearchField, oTable],
    beginButton: new sap.m.Button({
      text: oBundle.getText("OK"),
      press: function () {
        if (!selectedContext) {
          sap.m.MessageToast.show("Please select a report");
          return;
        }

        var obj = selectedContext.getObject();
        var inspection_date = obj["inspection_date"];
        var inspection_id = obj["id"];
        var report_no = obj["report_number"];

        if (src === 2) {
          attachInspection.setValue(report_no);
          attachInspection.setName(obj["pdf_url"]);
        } else if (src === 3) {
          inspectionLinkInput.removeAllTokens();
          let allowedKeys = ["1", "2", "3", "4", "5", "6", "7"];
          var items = oInputPartField0.getItems();
          items.forEach(function (item) {
            if (!allowedKeys.includes(item.getKey())) {
              oInputPartField0.removeItem(item);
            }
          });

          var tokenList = inspectionLinkInput.getTokens();
          var insertFlag = !tokenList.some(t => t.getText() === report_no);
          if (insertFlag || tokenList.length === 0) {
            inspectionLinkInput.addToken(new sap.m.Token({
              key: inspection_date,
              text: report_no
            }));

            Car_Inspection_Item.where({
              master_email: emailUser,
              inspection_id: inspection_id
            }).read().done(function (results) {
              if (results.length > 0) {
                results.forEach(function (item) {
                  var newItem = new sap.ui.core.ListItem({
                    key: item.task_name,
                    text: item.task_name
                  });
                  oInputPartField0.addItem(newItem);
                });
              }
            });
          }
        } else {
          var tokenList = inspectionLinkInput.getTokens();
          var insertFlag = !tokenList.some(t => t.getText() === report_no);
          if (insertFlag || tokenList.length === 0) {
            inspectionLinkInput.addToken(new sap.m.Token({
              key: inspection_date,
              text: report_no
            }));
          }
        }

        oDialog.close();
      }
    }),
    endButton: new sap.m.Button({
      text: oBundle.getText("Cancel"),
      press: function () {
        oDialog.close();
      }
    }),
    afterClose: function () {
      oDialog.destroy();
    }
  });

  oDialog.setModel(oModel);
  oDialog.open();
};



function linkWorkorder() {
  var oSelectDialog = new sap.m.SelectDialog({
    contentWidth: "50%",
    draggable: true,
    resizable: true,
    rememberSelections: true,
    multiSelect: true,
    title: oBundle.getText("Select_Workorder_Report"),
    noDataText: oBundle.getText("No_Data"),
    liveChange: function (oEvent) {
      (sSearchValue = oEvent.getParameter("value")),
        (oBinding = oEvent.getParameter("itemsBinding"));
      if (oBinding) {
        var oFilters = [
          new sap.ui.model.Filter(
            "wo_number",
            sap.ui.model.FilterOperator.Contains,
            sSearchValue
          ),
          new sap.ui.model.Filter(
            "created_date",
            sap.ui.model.FilterOperator.Contains,
            sSearchValue
          ),
          new sap.ui.model.Filter(
            "vehicle_number",
            sap.ui.model.FilterOperator.Contains,
            sSearchValue
          ),
        ];
        var filterObj = new sap.ui.model.Filter(oFilters, false);
        oBinding.filter(filterObj);
      } else {
        oBinding.filter([]);
      }
    },
    confirm: function (oEvent) {
      var tokenList = workorderLinkInput.getTokens();
      var aContexts = oEvent.getParameter("selectedContexts");
      if (aContexts && aContexts.length) {
        aContexts.map(function (oContext) {
          var created_date = oContext.getObject()["created_date"];
          var wo_number = oContext.getObject()["wo_number"];

          var insertFlag = true;
          for (var j = 0; j < tokenList.length; j++) {
            if (tokenList[j].getText() == wo_number) {
              insertFlag = false;
            }
          }
          if (tokenList.length == 0 || insertFlag) {
            workorderLinkInput.addToken(
              new sap.m.Token({ key: created_date, text: wo_number })
            );
          }
        });
      }
      // var tokenList = workorderLinkInput.getTokens();
      // var selectedItems = oEvent.getParameter("selectedItems");
      // if (selectedItems) {
      //     for (var i = 0; i < selectedItems.length; i++) {
      //         var insertFlag = true;
      //         for (var j = 0; j < tokenList.length; j++) {
      //             if(tokenList[j].getText()==selectedItems[i].getTitle()){ insertFlag = false; }
      //         }
      //         if(tokenList.length==0 || insertFlag){
      //             workorderLinkInput.addToken(new sap.m.Token({ key: selectedItems[i].getDescription(), text: selectedItems[i].getTitle() }));
      //         }
      //     }
      // }
    },
  });

  var oItemTemplate = new sap.m.StandardListItem({
    title: "{wo_number}",
    description: "{created_date}",
    info: "{vehicle_number}",
    type: "Active",
  });

  var currentWoNumber = HVICore.getElementById("wo_number").getText();

  var vehicle_number = oTFWOV1.getValue();
  var tokenList = workorderLinkInput.getTokens();
  var result = workorderJSONArray.filter(function (obj, index) {
    if (obj.vehicle_number == vehicle_number) {
      for (var j = 0; j < tokenList.length; j++) {
        if (tokenList[j].getText() == obj.wo_number) {
          return false;
        }
      }
      if (currentWoNumber == obj.wo_number) {
        return false;
      }
      return true;
    } else {
      return false;
    }
  });

  var oModel = new sap.ui.model.json.JSONModel();
  oModel.setData({ modelData: result });
  oSelectDialog.setModel(oModel);
  oSelectDialog.bindAggregation("items", "/modelData", oItemTemplate);

  //aDataParts.splice(index, 1);
  /*
   var tokenList = workorderLinkInput.getTokens(); 
    for (var i = 0; i < tokenList.length; i++) {
        oSelectDialog.removeItem(tokenList[i].getText()); 
       
        new sap.m.StandardListItem({
                        title: tokenList[i].getText(),
                        description: tokenList[i].getKey(),
                        type: "Active"
                    })
    }
    */
  oSelectDialog.open();
}
var supplier_wo_cost = 0;
var workshop_wo_cost = 0;
var supplier_wo_flag = "Workshop";
var supplier_wo_id = "";
function calculatingPartsCost() {
  var materialCost = 0;
  var laborCost = 0;
  supplier_wo_cost = 0;
  workshop_wo_cost = 0;
  supplier_wo_flag = "Workshop";
  supplier_wo_id = "";
  var obj = oTablePartsItemWO.getItems();
  for (var i = 0; i < obj.length; i++) {
    var oContext = obj[i].getBindingContext();

    let total_cost = oContext.getObject().total_parts_cost;
    let labor_cost = oContext.getObject().labor_item_cost;
    materialCost = parseFloat(materialCost) + parseFloat(total_cost);
    laborCost = parseFloat(laborCost) + parseFloat(labor_cost);

    if (nullCheckAll(oContext.getObject().supplier_id)) {
      supplier_wo_flag = "Supplier";
      supplier_wo_id = oContext.getObject().supplier_id;
      supplier_wo_cost += parseInt(oContext.getObject().total_cost);
    } else {
      workshop_wo_cost += parseInt(oContext.getObject().total_cost);
    }
  }
  // console.log(supplier_wo_cost);
  // console.log(workshop_wo_cost);
  var roundMaterialCost = roundToInt(materialCost);
  var roundLaborCost = roundToInt(laborCost);
  oTFWOCost1.setValue(roundMaterialCost);
  oTFWOCost2.setValue(roundLaborCost);

  calculateTotalCost();
}
/*
function calculatingAdditionalCost() {
  var additionalCost = 0;
  var obj = oTableWOAdditionalCost.getItems();
  for (var i = 0; i < obj.length; i++) {
    var oContext = obj[i].getBindingContext();
    additionalCost =
      parseFloat(additionalCost) + parseFloat(oContext.getObject().cost);
  }
  var roundAdditionalCost = Math.round(additionalCost * 100) / 100;
  oTFWOCost3.setValue(roundAdditionalCost);

  calculateTotalCost();
}*/

function calculateTotalCost() {
  var materialCost = parseFloat(oTFWOCost1.getValue());
  var laborCost = parseFloat(oTFWOCost2.getValue());
  // var additionalCost = parseFloat(oTFWOCost3.getValue());

  var tax = parseFloat(oTFWOCost4.getValue());

  if (isNaN(materialCost) == true) {
    materialCost = 0;
  }
  if (isNaN(laborCost) == true) {
    laborCost = 0;
  }
  // 0
  if (isNaN(tax) == true) {
    tax = 0;
  }

  var totalWOcost = parseFloat(materialCost) + parseFloat(laborCost); //+parseFloat(additionalCost) ;
  var roundTotalWOcost = roundToInt(totalWOcost);
  oTFWOCost6.setValue(roundTotalWOcost);

  var taxCost = (roundTotalWOcost * tax) / 100;
  oTFWOCost5.setValue(roundToInt(taxCost));

  var totalWOcost =
    parseFloat(materialCost) + parseFloat(laborCost) + parseFloat(taxCost);
  var roundTotalWOcost = roundToInt(totalWOcost);
  oTFWOCost6.setValue(roundTotalWOcost);

  var total_parts_cost = oTFWOCost1.getValue();
  var total_labor_cost = oTFWOCost2.getValue();
  // var additional_cost = oTFWOCost3.getValue();

  var tax = oTFWOCost4.getValue();
  var tax_value = oTFWOCost5.getValue();
  var total_wo_cost = oTFWOCost6.getValue();

  // var currency = " "+sessionStorage.getItem('oxmaint_currency');
  var currency = " IDR";
  // HVICore.getElementById('total_cost_id').setText(total_wo_cost+currency);

  // var supplier_wo_cost_tax = (supplier_wo_cost * tax) / 100;
  // var workshop_wo_cost_tax = (workshop_wo_cost * tax) / 100;
  supplier_wo_cost = roundToInt(supplier_wo_cost);
  workshop_wo_cost = roundToInt(workshop_wo_cost);

  Car_Workorder.update({
    id: workorderID + "",
    total_parts_cost: total_parts_cost,
    total_labor_cost: total_labor_cost,
    supplier_cost: supplier_wo_cost + "",
    workshop_cost: workshop_wo_cost + "",
    supplier_wo_flag: supplier_wo_flag,
    supplier_id: supplier_wo_id,
    //additional_cost:additional_cost,
    tax_value: tax_value + "",
    total_wo_cost: total_wo_cost,
  }).done(function () {
    let currentWOSection = oAppWorkOrderPageLayout.getSelectedSection();
    // console.log(currentWOSection);
    if (currentWOSection == "GWO1") {
      getPendingWorkorder();
    } else if (currentWOSection == "GWO2") {
      getOpenWorkorder();
    } else if (currentWOSection == "GWO3") {
      getCompletedWorkorder();
    } else if (currentWOSection == "GWO4") {
      getClosedWorkorder();
    } else if (currentWOSection == "GWO5") {
      getGrnWorkorder();
    } else if (currentWOSection == "GWO6") {
      getRejectWorkorder();
    } else if (currentWOSection == "GWO7") {
      getCancelledWorkorder();
    } else if (currentWOSection == "GWO8") {
      funGetArchiveWO();
    } else if(currentWOSection == "GWO11"){
      getVerificationWorkorder();
    }

    //funGetWorkorder();
  });
}

function messageDialog(message) {
  var oDialog = new sap.m.Dialog({
    title: "Information",
    type: "Message",
    state: "Information",
    content: new sap.m.Text({ text: message }),
    beginButton: new sap.m.Button({
      type: "Emphasized",
      text: "Close",
      press: function () {
        oDialog.close();
      },
    }),
    afterClose: function () {
      oDialog.destroy();
    },
  });

  oDialog.open();
}

// function woAssignNotification(assignKey,wo_number,vehicle_number){

//      var andr ="key=AAAABHj9U8s:APA91bFr-Dk7AWfqK4O5-Pc_mQegVLY1U1_ZiBWfXAVOyearAs-RkcUwgFufCeQ3AZQnUWLtRhU7uJdsIjwXYxcABtANUH2JbtRriXMR0UyfxwdSXUHicMO4XPjEOpXckKB2OdFzOfcw"

//      var masterEmail = emailUser.replace(/[@.]/g,"");
//      var userID = assignKey.replace(/[@.]/g,"");
//      var topic = masterEmail + userID;

//        $.ajax({
//         type: 'POST',
//         url: "https://fcm.googleapis.com/fcm/send",
//         headers: {Authorization: andr},
//         contentType: 'application/json',
//         dataType: 'json',
//         data: JSON.stringify({
//             "to": "/topics/"+topic,
//             "data": {
//                 "area": "workorder_assignment",
//                 "master_email": ""+emailUser,
//                 "assign": ""+assignKey,
//                 "wo_number": ""+wo_number,
//                 "vehicle_number": ""+vehicle_number
//             }
//         })
//     });
// }

function woAssignNotification(assignKey, wo_number, vehicle_number) {
  var masterEmail = emailUser.replace(/[@.]/g, "");
  var userID = assignKey.replace(/[@.]/g, "");
  var topic = masterEmail + userID;

  $.ajax({
    type: "POST",
    url: "https://heavyvehicleinspection.com/firebase/send_hvi_notification.php",
    data: {
      topic: topic,
      area: "workorder_assignment",
      master_email: emailUser,
      assign: assignKey,
      title: "",
      message: "",

      report_number: "",
      vehicle_number: "" + vehicle_number,
      wo_number: "" + wo_number,
      wo_status: "",
    },
    success: function (data) {},
  });
};

function filterWorkorderPart(make, model, transmission) {
  // console.log(transmission);
  let filterVehiclePart = partMaster4WJSONData.filter(function (a, b) {
    return (
      a.make == make &&
      a.model == model &&
      a.transmission == transmission &&
      a.part_status == "Active"
    );
  });

  workorderPartJSONArray = filterVehiclePart;
  // console.log(filterVehiclePart)
  var oModel12 = new sap.ui.model.json.JSONModel();
  oModel12.setData({ modelData: filterVehiclePart }); // results is an array of suggestion data
  oInputPartField1.setModel(oModel12);
}
function filterWorkorderPartWorkshop() {

  // let selectedVehicle = oTFWOV1.getValue();
  // let getVehicle = vehicle4WJSONData.filter(function (vObj, index) {
  //   return vObj.license_number === selectedVehicle;
  // });
  // let transmission = 'AT';
  // if(getVehicle.length > 0){
  //   transmission = getVehicle[0]['transmission']
  // };
  let make = oTFWOV10.getValue();
  let model = oTFWOV3.getValue();
  let transmission = oTFWOV14.getValue();
  let workshop_number = "";
  let workshopWoTokenList = oTFWOV7.getTokens();

  for (var j = 0; j < workshopWoTokenList.length; j++) {
    if (workshop_number == "") {
      workshop_number = workshopWoTokenList[j].getKey();
    }
  }

  if(nullCheckAll(workshop_number) && nullCheckAll(make) && nullCheckAll(model) && nullCheckAll(transmission)){
    getWOrkorderFilteredParts(workshop_number,make,model,transmission);
  }else{
    workorderPartJSONArray = [];
  
    var oModel12 = new sap.ui.model.json.JSONModel();
    oModel12.setData({ modelData: workorderPartJSONArray }); // results is an array of suggestion data
    oInputPartField1.setModel(oModel12);
  
    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ modelData: workorderPartJSONArray });
    oTablePickPartWO.setModel(oModel);
    oTablePickPartWO.bindItems({ path: "/modelData", template : oTablePickPartTemplate });
    oTablePickPartWO.setBusy(false);
  }
  // let filterVehiclePart = partMaster4WJSONData.filter(function (a, b) {
  //   return (
  //     a.make == make &&
  //     a.model == model &&
  //     a.transmission == transmission &&
  //     a.part_status == "Active" &&
  //     a.workshop_number == workshop_number
  //   );
  // });

  // workorderPartJSONArray = filterVehiclePart;
  
  // var oModel12 = new sap.ui.model.json.JSONModel();
  // oModel12.setData({ modelData: filterVehiclePart }); // results is an array of suggestion data
  // oInputPartField1.setModel(oModel12);

  // var oModel = new sap.ui.model.json.JSONModel();
  // oModel.setData({ modelData: filterVehiclePart });
  // oTablePickPartWO.setModel(oModel);
  // oTablePickPartWO.bindItems({ path: "/modelData", template : oTablePickPartTemplate });
  // oTablePickPartWO.setBusy(false);


}

//For Schedules
function getAttachedWorkorder(wo_number) {

  Car_Workorder.where({ master_email: emailUser, wo_number: wo_number })
    .take(1)
    .orderByDescending("createdAt")
    .read()
    .done(function (results) {
      if(results.length>0){
        workorderViewGrab(results[0], "1");
      }else{
          sap.m.MessageBox.error(oBundle.getText("Workorder_not_available_might_be_deleted"));
      } 
    });
}



function workorderfailure1(){
  oBusyDialogWO.close();
  sap.m.MessageBox.error(oBundle.getText("Resubmit your workorder"));
  return;
}

var oTablePickPartWO = new sap.m.Table({
  growing: true,
  noDataText:oBundle.getText("No_Data"),
  growingTriggerText:oBundle.getText("More"),
  sticky:[sap.m.Sticky.ColumnHeaders,sap.m.Sticky.HeaderToolbar,sap.m.Sticky.InfoToolbar],
  growingThreshold: 25,
  growingScrollToLoad : false,
  columns: [
      new sap.m.Column({width:"100px",header: new sap.m.Label({text: oBundle.getText("Action"),design: sap.m.LabelDesign.Bold})}),
      new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Part_Name"), design: sap.m.LabelDesign.Bold}),
      minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
      new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Part_ID"), design: sap.m.LabelDesign.Bold}),
      minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
      new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Part_Type"), design: sap.m.LabelDesign.Bold}),
      minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
      new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Workshop"),design: sap.m.LabelDesign.Bold})}),
      new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Supplier"), design: sap.m.LabelDesign.Bold}),
      minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
      new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Make"), design: sap.m.LabelDesign.Bold}),
      minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
      new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Model"), design: sap.m.LabelDesign.Bold}),
      minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
      new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Transmission"), design: sap.m.LabelDesign.Bold}),
      minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
      new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Status"), design: sap.m.LabelDesign.Bold}),
      minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
  ],
  headerToolbar:new sap.m.OverflowToolbar({
    content: [   
      
  

        new sap.m.ToolbarSpacer(),
        new sap.m.SearchField({
            placeholder: oBundle.getText("Search"),
            width: "300px",
            liveChange: function (event) {
                var oBinding = oTablePickPartWO.getBinding("items");
                var searchStr = this.getValue();
                if (oBinding) {
                    var oFilters = [
                    new sap.ui.model.Filter("part_name", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("workshop_name", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("workshop_number", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("supplier_id", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("supplier_name", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("vehicle_part_id", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("part_id", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("supplier_name", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("make", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("model", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("transmission", sap.ui.model.FilterOperator.Contains, searchStr),
                    ];
                    var filterObj = new sap.ui.model.Filter(oFilters, false);
                    oBinding.filter(filterObj);
                } else {
                    oBinding.filter([]);
                }
            }
    
        }),
        new sap.m.Button({
            icon: "sap-icon://filter",
            type: "Transparent",
            press: function() {
                clearWOPartMultiFilters();
                populateWOPartFilterDropdowns();
                partWOMultiFilterDialog.open();
            }
        })

    ]
  })
});

var oTablePickPartTemplate = new sap.m.ColumnListItem({
  cells: [
          new sap.m.Button({
              type: "Emphasized",
              icon: "sap-icon://action",
              text: oBundle.getText("Select"),
              press: function (event) {
                var model = this.getModel();
                var path = event.getSource().getBindingContext().getPath();
                var obj = model.getProperty(path);
                if(obj['part_type'] == 'Supplier'){
                  oInputPartField3.setEnabled(false);
                  oInputPartField4.setEnabled(false);
                }else{
                  oInputPartField3.setEnabled(true);
                  oInputPartField4.setEnabled(true);
                }
                oInputPartField1.setValue(obj['part_name']);
                oInputPartField3.setValue(obj['part_cost']);
                oInputPartField4.setValue(obj['labor_cost']);
                updatetotalCostWOPart();
                oDialogWOPartItemSelect.close();
              }
          }),
          new sap.m.Label({wrapping:true,text: "{part_name}"}),
          new sap.m.Label({wrapping:true,text: "{part_id}"}),
          new sap.m.Label({wrapping:true,text: "{part_type}"}),
          new sap.m.VBox({
              items:[new sap.m.Label({ wrapping: true, text: "{workshop_number}" }),
                  new sap.m.Label({ wrapping: true, text: "{workshop_name}" }).addStyleClass(""),
              ]
          }),
          new sap.m.VBox({
              items:[
                  new sap.m.Label({ wrapping: true, text: "{supplier_id}" }),
                  new sap.m.Label({ wrapping: true, text: "{supplier_name}" }),
              ]
          }),
          new sap.m.Label({wrapping:true,text: "{make}"}),
          new sap.m.Label({wrapping:true,text: "{model}"}),
          new sap.m.Label({wrapping:true,text: "{transmission}"}),
          // new sap.m.Label({wrapping:true,text: "{part_status}"}),
          new sap.tnt.InfoLabel({
              text: {
                  path: "part_status",
                  formatter: function (status) {
                      if (status == "Inactive") { 
                          this.setColorScheme(3);
                      }else if (status == "Active") { 
                          this.setColorScheme(8);
                      }
                      return status;
                  }
              }
          }),
          
      ],
      highlight: {
          path: "part_status",
          formatter: function (status) {
              if (nullCheckAll(status)) {
                  if (status == "Inactive") {
                      return "Error";
                  } else {
                      return "Success";
                  }
              }
              return "None";
          }
      }
});

var partWOMultiFilterDialog = new sap.m.Dialog({
  title: "Multi Filter Parts",
  contentWidth: "40%",
  content: [
      new sap.m.VBox({
          width: "100%",
          items: [
              new sap.m.Label({ text: "Part Name:", design: "Bold", required: false }),
              new sap.m.ComboBox({ 
                  width: "94%",
                  placeholder: "Select Part Name"
              }),
              new sap.m.Label({ text: "Part type:", design: "Bold", required: false }),
              new sap.m.ComboBox({ 
                  width: "94%",
                  placeholder: "Select Part Type"
              }),
              new sap.m.Label({ text: "Make:", design: "Bold", required: false }),
              new sap.m.ComboBox({ 
                  width: "94%",
                  placeholder: "Select Make"
              }),
              
              new sap.m.Label({ text: "Model:", design: "Bold", required: false }),
              new sap.m.ComboBox({ 
                  width: "94%",
                  placeholder: "Select Model"
              }),
              
              new sap.m.Label({ text: "Transmission:", design: "Bold", required: false }),
              new sap.m.ComboBox({ 
                  width: "94%",
                  placeholder: "Select Transmission"
              }),
              
              new sap.m.Label({ text: "Workshop:", design: "Bold", required: false }),
              new sap.m.ComboBox({ 
                  width: "94%",
                  placeholder: "Select Workshop"
              }),
              // new sap.m.Label({ text: "Status:", design: "Bold", required: false }),
              // new sap.m.ComboBox({ 
              //     width: "94%",
              //     placeholder: "Select Status"
              // }),
          ]
      }).addStyleClass("sapUiSmallMargin")
  ],
  buttons: [
      new sap.m.Button({
          icon: "sap-icon://clear-filter",
          text: "Clear Filter",
          press: function() {
              clearWOPartMultiFilters();
          }
      }),
      new sap.m.Button({
          icon: "sap-icon://decline",
          text: "Cancel",
          press: function() {
              partWOMultiFilterDialog.close();
          }
      }),
      new sap.m.Button({
          icon: "sap-icon://filter",
          text: "Apply Filter",
          type: "Emphasized",
          press: function() {
              var aFilters = [];
              
              // Get ComboBoxes (only first two fields now)
              var aComboBoxes = partWOMultiFilterDialog.getContent()[0].getItems().filter(function(item) {
                  return item instanceof sap.m.ComboBox;
              });
              // console.log(aComboBoxes[1].getValue())
              
              // Add filters for ComboBox fields (Workshop Group and License Number)
              var comboBoxFields = ["part_name","part_type","make", "model","transmission","workshop_name"];
              aComboBoxes.forEach(function(oComboBox, index) {
                  var sValue = oComboBox.getSelectedKey();
                  if (sValue) {
                      aFilters.push(new sap.ui.model.Filter(
                          comboBoxFields[index],
                          sap.ui.model.FilterOperator.EQ,
                          sValue
                      ));
                  }
              });
          
              
              var oBinding = oTablePickPartWO.getBinding("items");
              // console.log(oBinding.length)
              if (oBinding) {
                  if (aFilters.length > 0) {
                      var oCombinedFilter = new sap.ui.model.Filter({
                          filters: aFilters,
                          and: true
                      });
                      oBinding.filter(oCombinedFilter);
                  } else {
                      oBinding.filter([]);
                  }
              }
              
              partWOMultiFilterDialog.close();
          }
      })
  ]
}).addStyleClass("sapUiSizeCompact");

function clearWOPartMultiFilters() {
  var aComboBoxes = partWOMultiFilterDialog.getContent()[0].getItems().filter(function(item) {
      return item instanceof sap.m.ComboBox;
  });
  
  // Clear ComboBoxes
  aComboBoxes.forEach(function(oComboBox) {
      oComboBox.setSelectedKey("");
  });
  
  
  // Clear table filters
  var oBinding = oTablePickPartWO.getBinding("items");
  if (oBinding) {
      oBinding.filter([]);
  }
}
  
function populateWOPartFilterDropdowns() {
  try {
      var oModel = oTablePickPartWO.getModel();
      if (!oModel) return;
      
      var aData = oModel.getProperty("/modelData");
      if (!aData) return;

      // Get unique workshop groups
      var uniquePartNameGroups = [...new Set(aData
          .map(item => item.part_name)
          .filter(item => item && item.trim() !== "")
      )].sort();
      var uniquePartTypeGroups = [...new Set(aData
          .map(item => item.part_type)
          .filter(item => item && item.trim() !== "")
      )].sort();
      var uniqueMakeGroups = [...new Set(aData
          .map(item => item.make)
          .filter(item => item && item.trim() !== "")
      )].sort();
      var uniqueModelGroups = [...new Set(aData
          .map(item => item.model)
          .filter(item => item && item.trim() !== "")
      )].sort();
      var uniqueTransmissionGroups = [...new Set(aData
          .map(item => item.transmission)
          .filter(item => item && item.trim() !== "")
      )].sort();
      var uniqueWorkshopNameGroups = [...new Set(aData
          .map(item => item.workshop_name)
          .filter(item => item && item.trim() !== "")
      )].sort();
      // var uniqueStatusGroups = [...new Set(aData
      //     .map(item => item.vehicle_status)
      //     .filter(item => item && item.trim() !== "")
      // )].sort();
      



  var comboBoxes = partWOMultiFilterDialog.getContent()[0].getItems()
  .filter(item => item instanceof sap.m.ComboBox);

  var oPartNameComboBox = comboBoxes[0];
  var oPartTypeComboBox = comboBoxes[1];
  var oMakeGroupComboBox = comboBoxes[2];
  var oModelComboBox = comboBoxes[3];
  var oTransmissionComboBox = comboBoxes[4];
  var oWorkshopNameComboBox = comboBoxes[5];
  // var oStatusComboBox = comboBoxes[6];

  // Clear existing items
  oMakeGroupComboBox.removeAllItems();
  oModelComboBox.removeAllItems();
  oTransmissionComboBox.removeAllItems();
  // oStatusComboBox.removeAllItems();
  oPartNameComboBox.removeAllItems();
  oPartTypeComboBox.removeAllItems();
  oWorkshopNameComboBox.removeAllItems();



  // Add items to Make Group ComboBox
  uniquePartNameGroups.forEach(function(group) {
      oPartNameComboBox.addItem(new sap.ui.core.Item({
          key: group,
          text: group
      }));
  });
  uniquePartTypeGroups.forEach(function(group) {
      oPartTypeComboBox.addItem(new sap.ui.core.Item({
          key: group,
          text: group
      }));
  });

  uniqueMakeGroups.forEach(function(group) {
      oMakeGroupComboBox.addItem(new sap.ui.core.Item({
          key: group,
          text: group
      }));
  });
  uniqueModelGroups.forEach(function(group) {
      oModelComboBox.addItem(new sap.ui.core.Item({
          key: group,
          text: group
      }));
  });
  uniqueTransmissionGroups.forEach(function(group) {
      oTransmissionComboBox.addItem(new sap.ui.core.Item({
          key: group,
          text: group
      }));
  });
  // uniqueStatusGroups.forEach(function(group) {
  //     oStatusComboBox.addItem(new sap.ui.core.Item({
  //         key: group,
  //         text: group
  //     }));
  // });

  
  uniqueWorkshopNameGroups.forEach(function(group) {
      oWorkshopNameComboBox.addItem(new sap.ui.core.Item({
          key: group,
          text: group
      }));
  });



  } catch (error) {
      console.error("Error populating filter dropdowns:", error);
  }
}
var oDialogWOPartItemSelect;
function getPickPartTable(){

  oDialogWOPartItemSelect = new sap.m.Dialog({ draggable: true, resizable: true, contentHeight: "70%", contentWidth: "80%",
    title: oBundle.getText("Select_Part"),
    content: [oTablePickPartWO],
    buttons: [
    new sap.m.Button({
      text: oBundle.getText("Cancel"),
      icon: "sap-icon://decline",
      press: function () {
        oDialogWOPartItemSelect.close();
      }
    })
  ]
  }).open();

}