 var selectVehiclArea = "";
 var oDialogPickVehicle;
 var meterUnitType = "KM";

var actionColumn =  new sap.m.Column({ width: "130px", header: new sap.m.Label({ text: oBundle.getText("Action"), design: sap.m.LabelDesign.Bold }) });

var oTablePickVehicle = new sap.m.Table({growing: true,noDataText:oBundle.getText("No_Data"),
    growingTriggerText:oBundle.getText("More"),growingThreshold: 500,
    growingScrollToLoad : false,
    sticky:[sap.m.Sticky.ColumnHeaders,sap.m.Sticky.HeaderToolbar,sap.m.Sticky.InfoToolbar],
    columns: [
        // new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("License_Number"),design: sap.m.LabelDesign.Bold})}),
        // new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Make"),design: sap.m.LabelDesign.Bold})}),
        // new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Model"),design: sap.m.LabelDesign.Bold})}),
        // new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Transmission"),design: sap.m.LabelDesign.Bold})}),
        // new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Chassis_Number"),design: sap.m.LabelDesign.Bold})}),
        // new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Engine_Number"), design: sap.m.LabelDesign.Bold}),
        // minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
        // new sap.m.Column({  header: new sap.m.Label({text: oBundle.getText("City"),design: sap.m.LabelDesign.Bold})}),
        // new sap.m.Column({  header: new sap.m.Label({text: oBundle.getText("Status"),design: sap.m.LabelDesign.Bold})}),
        // actionColumn
        
        // Desktop only columns
    // Always visible columns (shown even on Mobile)
        new sap.m.Column({
            header: new sap.m.Label({ text: oBundle.getText("License_Number"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Tablet",demandPopin: true, popinDisplay: "Inline"
        }),
        new sap.m.Column({
            header: new sap.m.Label({ text: oBundle.getText("Make"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Tablet",demandPopin: true,popinDisplay: "Inline"
        }),
        new sap.m.Column({
            header: new sap.m.Label({ text: oBundle.getText("Model"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Tablet",demandPopin: true,popinDisplay: "Inline"
        }),
        
        // Tablet & up (shown in pop-in on Mobile)
        new sap.m.Column({
            header: new sap.m.Label({ text: oBundle.getText("Transmission"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Tablet",demandPopin: true,popinDisplay: "Inline"
        }),
        new sap.m.Column({
            header: new sap.m.Label({ text: oBundle.getText("Chassis_Number"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Tablet",demandPopin: true,popinDisplay: "Inline"
        }),
        new sap.m.Column({
            header: new sap.m.Label({ text: oBundle.getText("Engine_Number"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Tablet",demandPopin: true,popinDisplay: "Inline"
        }),
        new sap.m.Column({
            header: new sap.m.Label({ text: oBundle.getText("City"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Tablet",demandPopin: true,popinDisplay: "Inline"
        }),
        new sap.m.Column({
            header: new sap.m.Label({ text: oBundle.getText("Status"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Tablet",demandPopin: true,popinDisplay: "Inline"
        }),
        // Action column (optional, shown on all or limited depending on use)
        actionColumn
  

  
    ]
}).addStyleClass('withGrid');

// oTablePickVehicle.attachGrowingFinished(function() {
//     if (selectVehiclArea == "assign_vehicle") {
//         console.log("More button clicked, refreshing table...");
//         setMultiSelect();
//         // oTable.getModel().refresh(true);
//     }
// });

var PickVehicleTemplate = new sap.m.ColumnListItem({
    cells: [
        new sap.m.Label({wrapping:true,text: "{license_number}"}),
        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: "{chassis_number}"}),
        new sap.m.Label({wrapping:true,text: "{engine_number}"}),
        new sap.m.Label({wrapping:true,text: "{city_name}"}),
        new sap.m.Label({wrapping:true,text: "{vehicle_status}"}),
        new sap.m.Button({type: "Emphasized",icon: "sap-icon://complete",
            text: oBundle.getText("Select"),
            enabled: {
                path: "vehicle_status",
                formatter: function (status) {
                    var disabledStatuses = [
                        "sold", "total_loss", "loss_in_rent", "removed", "total_loss_accident", "total_loss"
                    ];
                    return !disabledStatuses.includes(status); // enable only if status is NOT in the list
                }
            },
            press: function (e) {
                var model = this.getModel();
                var path = e.getSource().getBindingContext().getPath();
                var obj = model.getProperty(path);
                selectVehicle(obj);
            }
        })
    ]
});

var VSDPickVehicle = new sap.m.ViewSettingsDialog({
    sortDescending: true,
    confirm: function (oEvent) {
        var p = oEvent.getParameters();
        var oSorter = null;
        if (p.sortItem) {
            oSorter = p.sortItem.getCustomData()[0].getValue();
            var key = p.sortItem.getCustomData()[0].getKey();

            var sortType = sap.ui.core.SortOrder.Descending;
            if (this.getSortDescending()) {
                sortType = sap.ui.core.SortOrder.Descending;
            } else {
                sortType = sap.ui.core.SortOrder.Ascending;
            }
            oTablePickVehicle.getColumns()[0].setSortIndicator(sap.ui.core.SortOrder.None);
            oTablePickVehicle.getColumns()[1].setSortIndicator(sap.ui.core.SortOrder.None);
            oTablePickVehicle.getColumns()[2].setSortIndicator(sap.ui.core.SortOrder.None);
            oTablePickVehicle.getColumns()[3].setSortIndicator(sap.ui.core.SortOrder.None);
            if (key == "1") { oTablePickVehicle.getColumns()[0].setSortIndicator(sortType);
            } else if (key == "2") { oTablePickVehicle.getColumns()[1].setSortIndicator(sortType);
            } else if (key == "3") { oTablePickVehicle.getColumns()[2].setSortIndicator(sortType);
            }else if (key == "4") { oTablePickVehicle.getColumns()[3].setSortIndicator(sortType);
        }
            if (oSorter) {
                oSorter.bDescending = p.sortDescending;
                oTablePickVehicle.getBinding("items").sort(oSorter);
            }
        }
    }
});
oTablePickVehicle.getColumns()[0].setSortIndicator(sap.ui.core.SortOrder.Ascending);

VSDPickVehicle.addSortItem(new sap.m.ViewSettingsItem({
    text: oBundle.getText("License_Number" ),selected: true,
    customData: new sap.ui.core.CustomData({key:"1",
        value: new sap.ui.model.Sorter("license_number", false)
    })
}));
VSDPickVehicle.addSortItem(new sap.m.ViewSettingsItem({
    text: oBundle.getText("Chassis_Number" ),
    customData: new sap.ui.core.CustomData({key:"2",
        value: new sap.ui.model.Sorter("chassis_number", false)
    })
}));
VSDPickVehicle.addSortItem(new sap.m.ViewSettingsItem({
    text: oBundle.getText("Engine_Number"),
    customData: new sap.ui.core.CustomData({key:"3",
        value: new sap.ui.model.Sorter("engine_number", false)
    })
}));
VSDPickVehicle.addSortItem(new sap.m.ViewSettingsItem({
    text: oBundle.getText("City"),
    customData: new sap.ui.core.CustomData({key:"4",
        value: new sap.ui.model.Sorter("city_name", false)
    })
}));
     
var selectVehicleSearchInput = new sap.m.Input({
    width:"15%",
    placeholder:"Search License Number",
});
var selectVehicleSearchInputBtn =  new sap.m.Button({
    // width:"15%",
    type: "Emphasized",
    text:"Search",
    press:function(oEvent){
        var sValue = selectVehicleSearchInput.getValue();

        if(sValue.length > 0 ){
            getVehicleByLicenseNumber(sValue);
        }
    }
});
oTablePickVehicle.setInfoToolbar(new sap.m.Toolbar({
    content: [ //new sap.m.Label({text: oBundle.getText("VEHICLE_INVENTRY")}).addStyleClass("whiteText"),
            
        new sap.m.Text({
            text: oBundle.getText("Vehicle_Inventory")
        }),
        selectVehicleSearchInput,
        selectVehicleSearchInputBtn,
        new sap.m.ToolbarSpacer(),
        new sap.m.SearchField({placeholder: oBundle.getText("Search"),width: "300px",
            liveChange: function (event) {
                var oBinding = oTablePickVehicle.getBinding("items");
                var searchStr = this.getValue();
                if (oBinding) {
                    var oFilters = [new sap.ui.model.Filter("license_number", 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("city_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),
                    new sap.ui.model.Filter("vehicle_status", 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() {
                clearSelectVehicleFilters();
                populateSelectVehicleFilterDropdowns();
                SelectVehicleFilterDialog.open();
            }
        })
        // new sap.m.Button({type:"Accept",text:oBundle.getText("sorting"),icon: "sap-icon://sort",
        //     press: function () { VSDPickVehicle.open();}
        // })
    ]
}));


var SelectVehicleFilterDialog = new sap.m.Dialog({
    title: "Multi Filter Vehicle",
    contentWidth: "40%",
    content: [
        new sap.m.VBox({
            width: "100%",
            items: [
                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: "City:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select City"
                }),
                new sap.m.Label({ text: "Status:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select Status"
                }),
                
                // new sap.m.Label({ text: "Status:", design: "Bold", required: false }),
                // new sap.m.Input({ 
                //     width: "94%",
                //     placeholder: "Enter Invoice Number"
                // }),
            ]
        }).addStyleClass("sapUiSmallMargin")
    ],
    buttons: [
        new sap.m.Button({
            icon: "sap-icon://clear-filter",
            text: "Clear Filter",
            press: function() {
                clearSelectVehicleFilters();
            }
        }),
        new sap.m.Button({
            icon: "sap-icon://decline",
            text: "Cancel",
            press: function() {
                SelectVehicleFilterDialog.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 = SelectVehicleFilterDialog.getContent()[0].getItems().filter(function(item) {
                    return item instanceof sap.m.ComboBox;
                });
                
                // Add filters for ComboBox fields (Workshop Group and License Number)
                var comboBoxFields = ["make", "model","transmission","city_name","vehicle_status"];
                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 = oTablePickVehicle.getBinding("items");
                if (oBinding) {
                    if (aFilters.length > 0) {
                        var oCombinedFilter = new sap.ui.model.Filter({
                            filters: aFilters,
                            and: true
                        });
                        oBinding.filter(oCombinedFilter);
                    } else {
                        oBinding.filter([]);
                    }
                }
                
                SelectVehicleFilterDialog.close();
            }
        })
    ]
}).addStyleClass("sapUiSizeCompact");

function clearSelectVehicleFilters() {
    var aComboBoxes = SelectVehicleFilterDialog.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 = oTablePickVehicle.getBinding("items");
    if (oBinding) {
        oBinding.filter([]);
    }
}
    
function populateSelectVehicleFilterDropdowns() {
    try {
        var oModel = oTablePickVehicle.getModel();
        if (!oModel) return;
        
        var aData = oModel.getProperty("/modelData");
        if (!aData) return;

        // Get unique workshop groups
        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 uniqueCityNameGroups = [...new Set(aData
            .map(item => item.city_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 = SelectVehicleFilterDialog.getContent()[0].getItems()
    .filter(item => item instanceof sap.m.ComboBox);
    
    var oMakeGroupComboBox = comboBoxes[0];
    var oModelComboBox = comboBoxes[1];
    var oTransmissionComboBox = comboBoxes[2];
    var oCityNameComboBox = comboBoxes[3];
    var oStatusComboBox = comboBoxes[4];

    // Clear existing items
    oMakeGroupComboBox.removeAllItems();
    oModelComboBox.removeAllItems();
    oTransmissionComboBox.removeAllItems();
    oCityNameComboBox.removeAllItems();
    oStatusComboBox.removeAllItems();

    // Add items to Make Group ComboBox
    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
        }));
    });
    uniqueCityNameGroups.forEach(function(group) {
        oCityNameComboBox.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
        }));
    });

 

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


function selectVehicle(obj) {

    var vehicle_serial = obj['vehicle_serial'];
    var vehicle_name = obj['vehicle_name'];
    var vehicle_meter = obj['odometer'];
    var meter_unit = obj['odometer_unit'];
    var vehicle_vin = obj['vehicle_vin'];
    var vehicle_operator = obj['vehicle_operator'];
    var vehicle_category = obj['vehicle_categoty'];
    var vehicle_model = obj['vehicle_model'];
    
    let license_number = obj['license_number'];
    let chassis_number = obj['chassis_number'];
    let engine_number = obj['engine_number'];
    let last_service_odometer = obj['last_service_odometer'];




        if (selectVehiclArea == "missed_report") {
            missed_Reminder_Search.setValue(vehicle_serial);
            missed_Reminder_Search.fireLiveChange();
        } else if (selectVehiclArea == "history") {
            historySearch.setValue(vehicle_serial);
            historySearch.fireLiveChange();
        } else if (selectVehiclArea == "vehicle_overview") {
            oSearchVehicleOverView.setValue(vehicle_serial);
        } else if(selectVehiclArea == "workorder") {
            workorderSearch.setValue(vehicle_serial);
            workorderSearch.fireLiveChange();
        } else if(selectVehiclArea == "workorder_archive") {
            workorderSearchArchive.setValue(vehicle_serial);
            workorderSearchArchive.fireLiveChange();
        } else if(selectVehiclArea == "inspection") {
             inspectionFieldV1.setValue(license_number);
             inspectionFieldV2.setValue(chassis_number);
             inspectionFieldV3.setValue(engine_number);
             inspectionFieldV4.setValue(last_service_odometer);
             inspectionMeterDB.setValue(meter_unit);

        }else if(selectVehiclArea == "workorder_create") {
            oTFWOV0.setValue(obj['id']);
            oTFWOV1.setValue(obj['license_number']);
            oTFWOV2.setValue(obj['vehicle_name']);
            oTFWOV3.setValue(obj['model']);
            oTFWOV8.setValue(obj['chassis_number']);
            oTFWOV9.setValue(obj['engine_number']);
            oTFWOV10.setValue(obj['make']);
            oTFWOV11.setValue(obj['vehicle_color']);

            // oTFWOV4.setValue(obj['current_odometer']||"0");
            oTFWOV4.setValue("0");
            oTFWOV12.setValue(obj["rental_company_name"]);
            oTFWOV13.setValue(obj["leasing_company_name"]);
            oTFWOV14.setValue(obj["transmission"]);

            WOmeterUnit.setValue("KM");
            // filterWorkorderPart(obj['make'],obj['model'],obj['transmission']);
            filterWorkorderPartWorkshop();
         

        }else if(selectVehiclArea == "incident_create") {
             oTFIncidentV1.setValue(vehicle_serial);
             oTFIncidentV2.setValue(vehicle_name);
             oTFIncidentV3.setValue(vehicle_operator);
             oTFIncidentV4.setValue(vehicle_category);
             oTFIncidentV5.setValue(vehicle_vin);

        }else if(selectVehiclArea == "daily") {
            dailySearch.setValue(vehicle_serial);
            dailySearch.fireLiveChange();
        }else if(selectVehiclArea == "incident") {
            incidentSearch.setValue(vehicle_serial);
        }else if(selectVehiclArea == "schedule") {
            scheduleSearch.setValue(vehicle_serial);
        }else if(selectVehiclArea == "fault") {
            faultVehicleField.setValue(vehicle_serial);
        }else if(selectVehiclArea == "assign_vehicle") {

            aDataAssignVehicle.push({ Vehicle_Number: obj['license_number']});
	        oModelAssignVehicle.setData({ modelData: aDataAssignVehicle });
	        oTableAssignVehicle.setModel(oModelAssignVehicle);
	        oTableAssignVehicle.bindRows("/modelData");

        // }else if(selectVehiclArea == "document"){
            // oField4DocVehicle.setValue(vehicle_serial); 
        } else if(selectVehiclArea == "multiFilter_wo"){
            openWOField3.setValue(obj['license_number']); 
        }
          
        oDialogPickVehicle.close();
}

function pickVehicle(){

    var doneBtn = new sap.m.Button({text: oBundle.getText("Done"),icon: "sap-icon://accept",
        press: function () {
            if(selectVehiclArea == 'remove_vehicle'){
                assignSelectedRemove();
                oDialogPickVehicle.close();
            }else{
                multiSelect();
                oDialogPickVehicle.close();
            }
        }
    });
    oDialogPickVehicle = new sap.m.Dialog({modal : true,
        title: oBundle.getText("Select_Vehicle"),
        state: sap.ui.core.ValueState.Success,
        content: [oTablePickVehicle],
        buttons: [doneBtn,
					new sap.m.Button({text: oBundle.getText("Cancel"),icon: "sap-icon://decline",
					    press: function () { oDialogPickVehicle.close();}
					})
				]
    }).open();


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

    if (selectVehiclArea == "assign_vehicle") {

        var objAssignVehicle = oModelAssignVehicle.getProperty("/modelData");
        let vehicleNumbers = new Set(objAssignVehicle.map(item => item.Vehicle_Number));
        vehicleJSONArray = vehicle4WJSONData.filter(item => !vehicleNumbers.has(item.license_number));

        
        oModel.setData({ modelData: vehicleJSONArray });
        // oTablePickVehicle.setModel(oModel);
        // oTablePickVehicle.bindItems({ path: "/modelData", template: PickVehicleTemplate });
        // oTablePickVehicle.setBusy(false);
        selectVehicleSearchInput.setValue("");
        selectVehicleSearchInput.setVisible(true);
        selectVehicleSearchInputBtn.setVisible(true);
        actionColumn.setVisible(false);
        oTablePickVehicle.setMode(sap.m.ListMode.MultiSelect);
        doneBtn.setVisible(true);
        // setMultiSelect();
    } else if (selectVehiclArea == "remove_vehicle") {
        oDialogPickVehicle.setTitle("Remove Vehicle")
        selectVehicleSearchInput.setVisible(false);
        selectVehicleSearchInputBtn.setVisible(false);

        var objAssignVehicle = oModelAssignVehicle.getProperty("/modelData");
        let vehicleNumbers = new Set(objAssignVehicle.map(item => item.Vehicle_Number));

        vehicleJSONArray = vehicle4WJSONData.filter(item => vehicleNumbers.has(item.license_number));
   


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

        actionColumn.setVisible(false);
        oTablePickVehicle.setMode(sap.m.ListMode.MultiSelect);
        doneBtn.setVisible(true);
        busyDialog.close();
    }else { 
        // var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: vehicle4WJSONData });
        // oTablePickVehicle.setModel(oModel);
        // oTablePickVehicle.bindItems({ path: "/modelData", template: PickVehicleTemplate });
        // oTablePickVehicle.setBusy(false);
        selectVehicleSearchInput.setValue("");
        selectVehicleSearchInput.setVisible(true);
        selectVehicleSearchInputBtn.setVisible(true);

        
        selectVehicleSearchInput.setVisible(true);
        selectVehicleSearchInputBtn.setVisible(true);
        actionColumn.setVisible(true);
        doneBtn.setVisible(false);
        oTablePickVehicle.setMode(sap.m.ListMode.None);    
    }
    oTablePickVehicle.setModel(oModel);
    oTablePickVehicle.bindItems({ path: "/modelData", template: PickVehicleTemplate });
    oTablePickVehicle.setBusy(false);
   
}

// function multiSelect() {

//     var oSelectedIndices = oTablePickVehicle.getSelectedItems();
//     // var newVehicleData = [];
//     for (var i = 0; i < oSelectedIndices.length; i++) {

//         var oItem = oSelectedIndices[i];
//         var oContext = oItem.getBindingContext();
//             //var oProperty = oContext.getProperty("SupplierName");

//         //var oContext = oTablePickVehicle.getContextByIndex(oSelectedIndices[i]);

//         let license_number = oContext.getObject().license_number;

//         if (isContains(aDataAssignVehicle,license_number)) {
//             aDataAssignVehicle.push({ Vehicle_Number: license_number });
//             // newVehicleData.push({ Vehicle_Number: license_number });
//         }
//     }
  
//     oModelAssignVehicle.setData({ modelData: aDataAssignVehicle });
//     oTableAssignVehicle.setModel(oModelAssignVehicle);
//     oTableAssignVehicle.bindRows("/modelData");
// }

var bIsSelectAllPressed = false;
var aManuallyDeselectedPaths = [];

oTablePickVehicle.attachSelectionChange(function(oEvent) {
    if (oEvent.getParameter("selectAll")) {
        bIsSelectAllPressed = true;
        aManuallyDeselectedPaths = []; // reset if new select all is pressed
    } else {
        var oListItem = oEvent.getParameter("listItem");
        var bSelected = oEvent.getParameter("selected");
        var sPath = oListItem.getBindingContext().getPath();

        if (bIsSelectAllPressed) {
            if (!bSelected && !aManuallyDeselectedPaths.includes(sPath)) {
                aManuallyDeselectedPaths.push(sPath);
            } else if (bSelected) {
                // Re-selected item, remove from deselected
                aManuallyDeselectedPaths = aManuallyDeselectedPaths.filter(p => p !== sPath);
            }
        }
    }
});



function multiSelect() {
    var aContextsToProcess = [];

    var oBinding = oTablePickVehicle.getBinding("items");

    if (bIsSelectAllPressed) {
        var aAllContexts = oBinding.getContexts(0, oBinding.getLength());

        aContextsToProcess = aAllContexts.filter(function(oContext) {
            return !aManuallyDeselectedPaths.includes(oContext.getPath());
        });
    } else {
        var aSelectedItems = oTablePickVehicle.getSelectedItems();
        aContextsToProcess = aSelectedItems.map(item => item.getBindingContext());
    }

    var newSelected = [];
    for (var i = 0; i < aContextsToProcess.length; i++) {
        var oContext = aContextsToProcess[i];
        var license_number = oContext.getObject().license_number;

        if (isContains(aDataAssignVehicle, license_number)) {
            aDataAssignVehicle.push({ Vehicle_Number: license_number });
            newSelected.push({ Vehicle_Number: license_number });
        }
    }

    oModelAssignVehicle.setData({ modelData: aDataAssignVehicle });
    oTableAssignVehicle.setModel(oModelAssignVehicle);
    oTableAssignVehicle.bindRows("/modelData");

    // Reset after use
    bIsSelectAllPressed = false;
    aManuallyDeselectedPaths = [];
}




// oTablePickVehicle.attachSelectionChange(function(oEvent) {
//     if (oEvent.getParameter("selectAll")) {
//         multiSelectALL();
//     }
// });


// function multiSelectALL() {

//     var oBinding = oTablePickVehicle.getBinding("items");
//     var aAllContexts = oBinding.getContexts(0, oBinding.getLength()); // Get all filtered/bound items

//     var newVehicleData = []
//     for (var i = 0; i < aAllContexts.length; i++) {
//         var oContext = aAllContexts[i];
//         console.log(oContext.getObject().license_number)
//         var license_number = oContext.getObject().license_number;

//         if (isContains(aDataAssignVehicle, license_number)) {
//             console.log(license_number)
//             aDataAssignVehicle.push({ Vehicle_Number: license_number });
//             newVehicleData.push({ Vehicle_Number: license_number });
//         }
//     }

//     console.log(newVehicleData);
//     console.log(aDataAssignVehicle);

//     return
//     oModelAssignVehicle.setData({ modelData: aDataAssignVehicle });
//     oTableAssignVehicle.setModel(oModelAssignVehicle);
//     oTableAssignVehicle.bindRows("/modelData");
// }


function setMultiSelect(){
    // console.log("asxdasd")
    var oSelected = oTablePickVehicle.getItems();

    for (var i = 0; i < oSelected.length; i++) {
         var oItem = oSelected[i];
         var oContext = oItem.getBindingContext();
         var license_number = oContext.getObject().license_number;

         if (isContains(aDataAssignVehicle,license_number)) {
             oItem.setSelected(false);
             //oItem.setVisible(true);
        }else{
             oItem.setSelected(true);
             //oItem.setVisible(false);
        }

    }

}

function isContains(json, value) {

    for (i = 0; i < json.length; i++) {
        if (json[i].Vehicle_Number == value)
            return false;
    }
    return true;
}


function assignSelectedRemove() {
    var allVehicledata = oTableAssignVehicle.getModel().getData();
    var vehicleArray = allVehicledata['modelData'];
    var indexes = oTablePickVehicle.getSelectedItems();

    let vehicleList = new Set(); // Using Set for O(1) lookup

    indexes.forEach(oItem => {
        let vehicleNumberSelected = oItem.getBindingContext().getObject().license_number;
        vehicleList.add(vehicleNumberSelected);
    });

    // Current Vehicle List in Workshop Group
    let objAssignVehicle = oModelAssignVehicle.getProperty("/modelData");
    let vehicleNumbers = new Set(objAssignVehicle.map(item => item.Vehicle_Number));

    if (vehicleList.size > 0) {
        // Removing selected vehicles efficiently
        let newVehicleArray = [...vehicleNumbers]
            .filter(vehicle => !vehicleList.has(vehicle))
            .map(vehicle => ({ Vehicle_Number: vehicle }));

        // Updating model
        aDataAssignVehicle = newVehicleArray;
        oModelAssignVehicle.setData({ modelData: newVehicleArray });
        oTableAssignVehicle.setModel(oModelAssignVehicle);
        oTableAssignVehicle.bindRows("/modelData");
    }
}



var btnRemoveAssignVehicle =  new sap.m.Button({ icon: "sap-icon://action", text: oBundle.getText("Remove"), //width: "100%",
    layoutData: new sap.ui.layout.GridData({ span: "L2 M4 S6" }),
    type: sap.m.ButtonType.Emphasized,
    press: function () {
        busyDialog.open();
        selectVehiclArea = "remove_vehicle";
        pickVehicle();
    } 
});