// var Car_Vehicle_Master =  client.getTable('Car_Vehicle_Master');



//Four Wheeler
var oTableFourWheeler = 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: 100,
    growingScrollToLoad : false,
    columns: [
            new sap.m.Column({width:"60px",header: new sap.m.Label({wrapping:true, text: oBundle.getText("Action"),design: sap.m.LabelDesign.Bold})}),
            new sap.m.Column({width: "60px",hAlign: "Center",header: new sap.m.Label({ text:"", design: sap.m.LabelDesign.Bold}) }),
            new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("License_Plate"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,width:"120px"}),
            new sap.m.Column({header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Make"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left",width:"100px"}),
            new sap.m.Column({header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Model"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left",width:"100px"}),
            // new sap.m.Column({header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Chassis Number"), 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("Engine_Number"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,width:"120px"}),
            new sap.m.Column({header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Odometer"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left",width:"100px"}),
            new sap.m.Column({header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Status"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left",width:"100px"}),
            new sap.m.Column({header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Jaya_current_Location"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Center",width:"120px"}),
            new sap.m.Column({header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Rental_Company_Name"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left",width:"100px"}),
            new sap.m.Column({header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Leasing_Company_Name"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left",width:"100px"}),
            // new sap.m.Column({header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Status"), design: sap.m.LabelDesign.Bold}),
            // minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Center",width:"120px"}),
            // new sap.m.Column({header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Branch"), design: sap.m.LabelDesign.Bold}),
            // minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left",width:"100px"}),
            
            // new sap.m.Column({header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Year"), design: sap.m.LabelDesign.Bold}),
            // minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left",width:"100px"}),

    ]
});

oTableFourWheeler.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 = oTableFourWheeler.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("model_year", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("vehicle_color", 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),
                    ];
                    var filterObj = new sap.ui.model.Filter(oFilters, false);
                    oBinding.filter(filterObj);
                } else {
                    oBinding.filter([]);
                }
            }
    
        }),
        // new sap.m.Button({icon: "sap-icon://sort",press: function () {
        //     VSD4WVehicle.open();
        // }}),
        // new sap.m.Button({icon: "sap-icon://filter",press: function () {
        //     funMultiFilter4WVehicle(vehicle4WJSONData);
        // }}),
        new sap.m.Button({
            icon: "sap-icon://filter",
            type: "Transparent",
            press: function() {
                clearVehicleMasterFilters();
                populateVehicleMasterFilterDropdowns();
                vehicleMasterFilterDialog.open();
            }
        }),
        new sap.m.MenuButton({
            icon: "sap-icon://menu",
            menu: new sap.m.Menu({
                itemSelected: function(oEvent) {
                    var key = oEvent.getParameter("item").getKey();
                    if(key == "1"){
                    
                        if(subscription_status != 'Inactive' && subscription_status != 'Cancelled'){
                            vehicle4WExcelExport('1',vehicle4WJSONData);
                        }else{
                            sap.m.MessageBox.error(oBundle.getText("You are not permitted to perform this action."));
                            return;
                        }
                    }else if (key == '2'){
                        if (["Administrator", "Account Payable Team", "Maintenance Team", "Quality Team"].includes(oxmaint_role)){
                            busyDialog.open();
                            vehicle4WExcelExportAll();
                        }else{
                            sap.m.MessageBox.error(oBundle.getText("You are not permitted to perform this action."));
                            return;
                        }
                    }
                },
                items: [
                    new sap.m.MenuItem({key: "1",text: oBundle.getText("Excel_Export"),
                        icon: "sap-icon://excel-attachment",
                    }),
                    new sap.m.MenuItem({key: "2",text: oBundle.getText("Excel_Export_All"),
                        icon: "sap-icon://excel-attachment",
                    })         
                ]
            })
        })
    ]
}));
 
var aVehicleFilters = [];
var vehicleMasterFilterDialog = 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: "Rental Company Name:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select Rental Company Name"
                }),
                new sap.m.Label({ text: "Leasing Company Name:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select Leasing Company Name"
                }),
                new sap.m.Label({ text: "Jaya Vehicle Location:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select Jaya Vehicle Location"
                }),
                
                // 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() {
                clearVehicleMasterFilters();
            }
        }),
        new sap.m.Button({
            icon: "sap-icon://decline",
            text: "Cancel",
            press: function() {
                vehicleMasterFilterDialog.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 = vehicleMasterFilterDialog.getContent()[0].getItems().filter(function(item) {
                    return item instanceof sap.m.ComboBox;
                });
                
                // Add filters for ComboBox fields (Workshop Group and License Number)
                var comboBoxFields = ["city_name","vehicle_status",'rental_company_name','leasing_company_name','jaya_current_location'];
                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 = oTableFourWheeler.getBinding("items");
                if (oBinding) {
                    if (aFilters.length > 0) {
                        var oCombinedFilter = new sap.ui.model.Filter({
                            filters: aFilters,
                            and: true
                        });
                        oBinding.filter(oCombinedFilter);
                        aVehicleFilters = aFilters;
                    } else {
                        oBinding.filter([]);
                        aVehicleFilters = [];
                    }
                }
                
                vehicleMasterFilterDialog.close();
            }
        })
    ]
}).addStyleClass("sapUiSizeCompact");

function clearVehicleMasterFilters() {
    var aComboBoxes = vehicleMasterFilterDialog.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 = oTableFourWheeler.getBinding("items");
    if (oBinding) {
        oBinding.filter([]);
        aVehicleFilters = [];
    }
}
    
function populateVehicleMasterFilterDropdowns() {
    try {
        var oModel = oTableFourWheeler.getModel();
        if (!oModel) return;
        
        var aData = oModel.getProperty("/modelData");
        if (!aData) return;

        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 uniqueRCNGroups = [...new Set(aData
            .map(item => item.rental_company_name)
            .filter(item => item && item.trim() !== "")
        )].sort();
        var uniqueLCNGroups = [...new Set(aData
            .map(item => item.leasing_company_name)
            .filter(item => item && item.trim() !== "")
        )].sort();
        var uniqueJVLGroups = [...new Set(aData
            .map(item => item.jaya_current_location)
            .filter(item => item && item.trim() !== "")
        )].sort();
        

    var comboBoxes = vehicleMasterFilterDialog.getContent()[0].getItems()
    .filter(item => item instanceof sap.m.ComboBox);
    
    
    var oCityNameComboBox = comboBoxes[0];
    var oStatusComboBox = comboBoxes[1];
    var oRCNComboBox = comboBoxes[2];
    var oLCNComboBox = comboBoxes[3];
    var oJCLComboBox = comboBoxes[4];

    // Clear existing items
    oCityNameComboBox.removeAllItems();
    oStatusComboBox.removeAllItems();
    oRCNComboBox.removeAllItems();
    oLCNComboBox.removeAllItems();
    oJCLComboBox.removeAllItems();

    // Add items to Make Group ComboBox
    //City
    uniqueCityNameGroups.forEach(function(group) {
        oCityNameComboBox.addItem(new sap.ui.core.Item({
            key: group,
            text: group
        }));
    });
    //Status
    uniqueStatusGroups.forEach(function(group) {
        oStatusComboBox.addItem(new sap.ui.core.Item({
            key: group,
            text: group
        }));
    });
    //Rental Company Name
    uniqueRCNGroups.forEach(function(group) {
        oRCNComboBox.addItem(new sap.ui.core.Item({
            key: group,
            text: group
        }));
    });
    //Leasing Company Name
    uniqueLCNGroups.forEach(function(group) {
        oLCNComboBox.addItem(new sap.ui.core.Item({
            key: group,
            text: group
        }));
    });
    //Jaya Current Location
    uniqueJVLGroups.forEach(function(group) {
        oJCLComboBox.addItem(new sap.ui.core.Item({
            key: group,
            text: group
        }));
    });

 

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



var fourWheelerTemplate = new sap.m.ColumnListItem({
  cells: [
        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);
                vehicleID = obj['id'];
                vehicleNumber = obj['vehicle_serial'];
                displayMenu4WVehicle(event,obj);
            }
        }),
         new sap.f.Avatar({
           src: {
                path: "imgurl",
                formatter: function (value) {
                    if (value != null && value != "" ) {
                        return value;
                    }else{
                        return "sap-icon://product";
                    }
                }
            },
           displaySize: "XS",
           displayShape: "Circle",
           imageFitType: "Cover"
       }),
        new sap.m.Label({wrapping:true,text: "{license_number}"}),
        // new sap.m.Label({wrapping:true,text: "{chassis_number}"}),
        new sap.m.Label({wrapping:true,text: "{make}"}),
        new sap.m.Label({wrapping:true,text: "{model}"}),
        new sap.m.Label({wrapping:true,text: "{engine_number}"}),
        new sap.m.Label({wrapping:true,text: "{current_odometer}"}),
        new sap.m.Label({wrapping:true,text: "{vehicle_status}"}),

        // new sap.m.Label({
        //     wrapping:true,
        //     text: {
        //         path: "vehicle_status",
        //         formatter: function (status) {
        //             if (status === "writeoff") {
        //                 return "Writeoff";
        //             } else if (status === "removed") {
        //                 return "Removed";
        //             } else if (status === "pending_service") {
        //                 return "Pending Service";
        //             } else if (status === "on_rent") {
        //                 return "On Rent";
        //             } else if (status === "rented_in_repair_accident") {
        //                 return "Rented in Repair (Accident)";
        //             } else if (status === "in_service") {
        //                 return "In Service";
        //             } else if (status === "total_loss") {
        //                 return "Total Loss";
        //             } else if (status === "in_repair") {
        //                 return "In Repair";
        //             } else if (status === "pending_repair") {
        //                 return "Pending Repair";
        //             } else if (status === "total_loss_accident") {
        //                 return "Total Loss (Accident)";
        //             } else if (status === "pending_disposal") {
        //                 return "Pending Disposal";
        //             } else if (status === "checkin") {
        //                 return "Checkin";
        //             } else if (status === "replacement_pool") {
        //                 return "Replacement Pool";
        //             } else if (status === "operation_car") {
        //                 return "Operation Car";
        //             } else if (status === "rented_in_repair_maintain") {
        //                 return "Rented in Repair (Maintain)";
        //             } else if (status === "sold") {
        //                 return "Sold";
        //             } else if (status === "preparation") {
        //                 return "Preparation";
        //             } else if (status === "replacement") {
        //                 return "Replacement";
        //             } else if (status === "document_issue") {
        //                 return "Document Issue";
        //             } else if (status === "lost_in_rent") {
        //                 return "Lost in Rent";
        //             } else if (status === "impounded") {
        //                 return "Impounded";
        //             } else {
        //                 return "Unknown Status";
        //             }
        //         }
        //     }
        // }),
        new sap.m.Label({wrapping:true,text: "{jaya_current_location}"}),
        new sap.m.Label({wrapping:true,text: "{rental_company_name}"}),
        new sap.m.Label({wrapping:true,text: "{leasing_company_name}"}),       
       ]
});

var VSD4WVehicle = 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;
            }

            oTableFourWheeler.getColumns()[1].setSortIndicator(sap.ui.core.SortOrder.None);
            oTableFourWheeler.getColumns()[2].setSortIndicator(sap.ui.core.SortOrder.None);
            oTableFourWheeler.getColumns()[3].setSortIndicator(sap.ui.core.SortOrder.None);
            oTableFourWheeler.getColumns()[4].setSortIndicator(sap.ui.core.SortOrder.None);
            oTableFourWheeler.getColumns()[5].setSortIndicator(sap.ui.core.SortOrder.None);
            oTableFourWheeler.getColumns()[6].setSortIndicator(sap.ui.core.SortOrder.None);
            oTableFourWheeler.getColumns()[7].setSortIndicator(sap.ui.core.SortOrder.None);
            oTableFourWheeler.getColumns()[8].setSortIndicator(sap.ui.core.SortOrder.None);
            oTableFourWheeler.getColumns()[9].setSortIndicator(sap.ui.core.SortOrder.None);
            oTableFourWheeler.getColumns()[10].setSortIndicator(sap.ui.core.SortOrder.None);
            oTableFourWheeler.getColumns()[11].setSortIndicator(sap.ui.core.SortOrder.None);

            if (key == "1") {
                oTableFourWheeler.getColumns()[2].setSortIndicator(sortType);
            } else if (key == "2") {
                // oTableFourWheeler.getColumns()[2].setSortIndicator(sortType);
            } else if (key == "3") {
                oTableFourWheeler.getColumns()[3].setSortIndicator(sortType);
            } else if (key == "4") {
                oTableFourWheeler.getColumns()[4].setSortIndicator(sortType);
            } else if (key == "5") {
                oTableFourWheeler.getColumns()[7].setSortIndicator(sortType);
            } else if (key == "6") {
                oTableFourWheeler.getColumns()[8].setSortIndicator(sortType);
            } else if (key == "7") {
                oTableFourWheeler.getColumns()[9].setSortIndicator(sortType);
            } else if (key == "8") {
                oTableFourWheeler.getColumns()[10].setSortIndicator(sortType);
            } else if (key == "9") {
                oTableFourWheeler.getColumns()[11].setSortIndicator(sortType);
            } else if (key == "10") {
                oTableFourWheeler.getColumns()[12].setSortIndicator(sortType);
            } 

            if (oSorter) {
                oSorter.bDescending = p.sortDescending;
                // if (key === "2") {
                //     oSorter.fnCompare = function (a, b) {

                //         var strDate1 = a;
                //         var strDate2 = b;

                //         if (strDate1.length == 11) {
                //             strDate1 = strDate1 + " 01:00 PM";
                //         } else if (strDate1.length == 17) {
                //             strDate1 = strDate1 + " PM";
                //         } else if (strDate1.length == 10) {
                //             strDate1 = "0" + strDate1 + " 01:00 PM";
                //         }

                //         if (strDate2.length == 11) {
                //             strDate2 = strDate2 + " 01:00 PM";
                //         } else if (strDate2.length == 17) {
                //             strDate2 = strDate2 + " PM";
                //         } else if (strDate2.length == 10) {
                //             strDate2 = "0" + strDate2 + " 01:00 PM";
                //         }

                //         var aDate = new Date(strDate1);
                //         var bDate = new Date(strDate2);

                //         if (bDate == null) { return -1; }
                //         if (aDate == null) { return 1; }
                //         if (aDate < bDate) { return -1; }
                //         if (aDate > bDate) { return 1; }
                //         return 0;
                //     };
                // }
                // if (key === "7") {
                //     oSorter.fnCompare = function (a, b) {

                //         var cost1 = 0;
                //         var cost2 = 0;

                //         if (a == null || a == "") {
                //             cost1 = 0;
                //         }else{
                //             cost1 = parseFloat(a);
                //         }
                //         if (b == null || b == "") {
                //             cost2 = 0;
                //         }else{
                //             cost2 = parseFloat(b);
                //         }

                //           if (cost1 < cost2) return -1;
                //           if (cost1 == cost2) return 0;
                //           if (cost1 > cost2) return 1;

                //           return 0;
                //     };
                // }
                oTableFourWheeler.getBinding("items").sort(oSorter);
            }
        }
    },
    sortItems:[
        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)
            })
        }),
        new sap.m.ViewSettingsItem({
            text: oBundle.getText("Created_Date"),
            customData: new sap.ui.core.CustomData({
                key:"2",
                value: new sap.ui.model.Sorter("created_date", false)
            })
        }),
        new sap.m.ViewSettingsItem({
            text: oBundle.getText("Chassis_Number"),
            customData: new sap.ui.core.CustomData({
                key:"3",
                value: new sap.ui.model.Sorter("chassis_number", false)
            })
        }),
        new sap.m.ViewSettingsItem({
            text: oBundle.getText("Engine_Number"),
            customData: new sap.ui.core.CustomData({
                key:"4",
                value: new sap.ui.model.Sorter("engine_number", false)
            })
        }),
        new sap.m.ViewSettingsItem({
            text: oBundle.getText("City"),
            customData: new sap.ui.core.CustomData({
                key:"5",
                value: new sap.ui.model.Sorter("city_name", false)
            })
        }),
        new sap.m.ViewSettingsItem({
            text: oBundle.getText("Make"),
            customData: new sap.ui.core.CustomData({
                key:"6",
                value: new sap.ui.model.Sorter("make", false)
            })
        }),
        new sap.m.ViewSettingsItem({
            text: oBundle.getText("Model"),
            customData: new sap.ui.core.CustomData({
                key:"7",
                value: new sap.ui.model.Sorter("model", false)
            })
        }),
        new sap.m.ViewSettingsItem({
            text: oBundle.getText("Rental_company_Name"),
            customData: new sap.ui.core.CustomData({
                key:"8",
                value: new sap.ui.model.Sorter("rental_company_name", false)
            })
        }),
        new sap.m.ViewSettingsItem({
            text: oBundle.getText("Leasing_company_Name"),
            customData: new sap.ui.core.CustomData({
                key:"9",
                value: new sap.ui.model.Sorter("leasing_company_name", false)
            })
        }),
        new sap.m.ViewSettingsItem({
            text: oBundle.getText("Year"),
            customData: new sap.ui.core.CustomData({
                key:"10",
                value: new sap.ui.model.Sorter("model_year", false)
            })
        }),
    ]
});

function displayMenu4WVehicle(event,obj){

    var oMenu = new sap.m.Menu({
        items: [
            new sap.m.MenuItem({icon: "sap-icon://show",text: oBundle.getText("View"),key: "1"}),
            new sap.m.MenuItem({icon: "sap-icon://show",text: oBundle.getText("Overview"),key: "3"}),
            new sap.m.MenuItem({icon: "sap-icon://edit",text: oBundle.getText("Update"),key: "2"})
            ],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
            if (oItem == "1") {
                addUpdate4WVehicle(3,obj);//View Vehicle Data
                var startDate = "01-Jan-2025";
                var endDate = "01-Jan-2035"+" "+"11:59 PM";
                // vehicleOverviewDialog(obj,startDate,endDate);

            } else if (oItem == "2") {
                addUpdate4WVehicle(2,obj); // Update Vehicle Data
            } else if (oItem == "3") {
               
                var startDate = "01-Jan-2025";
                var endDate = "01-Jan-2035"+" "+"11:59 PM";
                vehicleOverviewDialog(obj,startDate,endDate);
            }
        }
    });

    // getDeleteMenu(oMenu,"4");
    oMenu.openBy(event.getSource());
    
}

function vehicle4WExcelExport(src, data){
   
    var xlsHeader = [oBundle.getText("License_Plate"), 
                     oBundle.getText("Chassis_Number"),
                     oBundle.getText("Engine_Number"),
                     oBundle.getText("Vehicle Year"),
                     oBundle.getText("Make"),
                     oBundle.getText("Make_Id"),
                     oBundle.getText("Model"),
                     oBundle.getText("Model_ID"),
                     oBundle.getText("Color"),
                     oBundle.getText("Transmission"),
                     oBundle.getText("Status"),
                     oBundle.getText("City"),
                     oBundle.getText("Jaya_vehicle_Location"),
                     oBundle.getText("Rental_Company_Name"),
                     oBundle.getText("Leasing_Company_Name"),
                     oBundle.getText("Jaya_Driver_ID"),
                     oBundle.getText("Driver_Name"),
                     oBundle.getText("Driver_Type"),
                     oBundle.getText("Driver_Email"),
                     oBundle.getText("Handover_Date"),
                     oBundle.getText("KEUR_Registration_Number"),
                     oBundle.getText("KP_Registration_Number"),
                     oBundle.getText("STNK_Due_1_Year"),
                     oBundle.getText("STNK_Due_5_Year"),
                     oBundle.getText("KEUR_Due_Date"),
                     oBundle.getText("Control_Card_Due_Date"),
                     oBundle.getText("Vehicle Id"),
                     oBundle.getText("Current Odometer"),
                       
                ];

    var dataObject = [];
    // var tableItem = oTableFourWheeler.getItems();
    var tableItem = data;

    for(var i=0;i<tableItem.length;i++){
        var item = tableItem[i]//.getBindingContext().getObject();


           dataObject.push({
                "1":item.license_number,
                "2":item.chassis_number,
                "3":item.engine_number,
                "4":item.model_year,
                "5":item.make,
                "6":item.make_id,
                "7":item.model,
                "8":item.model_id,
                "9":item.vehicle_color,
                "10":item.transmission,
                "11":item.vehicle_status,
                "12":item.city_name,
                "13":item.jaya_current_location,
                "14":item.rental_company_name,
                "15":item.leasing_company_name,
                "16":item.jaya_driver_id,
                "17":item.driver_name,
                "18":item.driver_type,
                "19":item.driver_email,
                "20":item.handover_date,
                "21":item.keur_reg_no,
                "22":item.kp_reg_no,
                "23":item.stnk_due_1year,
                "24":item.stnk_due_5year,
                "25":item.keur_due_date,
                "26":item.due_control_card,
                "27":item.id,
                "28":item.current_odometer
            });
}




    var createXLSLFormatObj = [];

    createXLSLFormatObj.push(xlsHeader);
    $.each(dataObject, function(index, value) {
        var innerRowData = [];
        $.each(value, function(ind, val) {
            innerRowData.push(val);
        });
        createXLSLFormatObj.push(innerRowData);
    });

    var filename = "vehicle4WExport.xlsx";
    if(src == '2'){
        filename = "AllVehicle4WExport.xlsx"
    }
    var sheet_name = "Data";

    var wb = XLSX.utils.book_new();
    var ws = XLSX.utils.aoa_to_sheet(createXLSLFormatObj);

    XLSX.utils.book_append_sheet(wb, ws, sheet_name);
    XLSX.writeFile(wb, filename);
}

//Add Update View 4W Vehicle
function addUpdate4WVehicle(src,obj){


    var reqLbl = new sap.m.Label({ required: true });
    var oLbl = new sap.m.Label({ });

    var o4WField1 = new sap.m.Input({enabled:false});
    var o4WField2 = new sap.m.Input({maxLength:20});
    var o4WField3 = new sap.m.Input({maxLength:50});
    var o4WField4 = new sap.m.Input({maxLength:100});
    var o4WField5 = new sap.m.DatePicker({width:"100%",displayFormat: "yyyy",valueFormat: "yyyy"});
    o4WField5.attachBrowserEvent("keydown", function (oEvent) {
        oEvent.preventDefault(); // Prevent manual typing
    });
    
    o4WField5.attachBrowserEvent("keypress", function (oEvent) {
        oEvent.preventDefault(); // Prevent manual typing
    });

    var o4WField6 = new sap.m.Input({});
    var o4WField7 = new sap.m.Input({maxLength:50});
    var o4WField8 = new sap.m.Input({});
    var o4WField9 = new sap.m.Input({maxLength:50});
    var o4WField10 = new sap.m.ComboBox({
        // layoutData: new sap.ui.layout.GridData({span: "L3 M6 S12"}),
        value:oBundle.getText("Black"),
        items:[    
            new sap.ui.core.ListItem({key:"Black",text:oBundle.getText("Black")}),
            new sap.ui.core.ListItem({key:"Red",text:oBundle.getText("Red")}),
            new sap.ui.core.ListItem({key:"White",text:oBundle.getText("White")}),
            new sap.ui.core.ListItem({key:"Yellow",text:oBundle.getText("Yellow")}),
            new sap.ui.core.ListItem({key:"Blue",text:oBundle.getText("Blue")})
        ],
        change: function (oEvent) {
            let enteredValue = oEvent.getParameter("value");
            let isValid = o4WField10.getItems().some(item => item.getText() === enteredValue);
    
            if (!isValid) {
                sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list_for_Vehicle_Color"));
                o4WField10.setValue(oBundle.getText("Black"));
            }
        }
    }).addEventDelegate({onAfterRendering: function(e) {o4WField10.$().find("input").attr("readonly", true);}});
    var o4WField11 = new sap.m.Input({});
    var o4WField12 = new sap.m.Input({});
    var o4WField13 = new sap.m.Input({});
    var o4WField14 =  new sap.m.ComboBox({
        value:oBundle.getText("Select_Status"),
        items:[
            new sap.ui.core.ListItem({ key: "Select Status", text: "Select Status" }),
            new sap.ui.core.ListItem({ key: "writeoff", text: "writeoff" }),
            new sap.ui.core.ListItem({ key: "removed", text: "removed" }),
            new sap.ui.core.ListItem({ key: "pending_service", text: "pending_service" }),
            new sap.ui.core.ListItem({ key: "on_rent", text: "on_rent" }),
            new sap.ui.core.ListItem({ key: "rented_in_repair_accident", text: "rented_in_repair_accident" }),
            new sap.ui.core.ListItem({ key: "in_service", text: "in_service" }),
            new sap.ui.core.ListItem({ key: "total_loss", text: "total_loss" }),
            new sap.ui.core.ListItem({ key: "in_repair", text: "in_repair" }),
            new sap.ui.core.ListItem({ key: "pending_repair", text: "pending_repair" }),
            new sap.ui.core.ListItem({ key: "total_loss_accident", text: "total_loss_accident" }),
            new sap.ui.core.ListItem({ key: "pending_disposal", text: "pending_disposal" }),
            new sap.ui.core.ListItem({ key: "checkin", text: "checkin" }),
            new sap.ui.core.ListItem({ key: "replacement_pool", text: "replacement_pool" }),
            new sap.ui.core.ListItem({ key: "operation_car", text: "operation_car" }),
            new sap.ui.core.ListItem({ key: "rented_in_repair_maintain", text: "rented_in_repair_maintain" }),
            new sap.ui.core.ListItem({ key: "sold", text: "sold" }),
            new sap.ui.core.ListItem({ key: "preparation", text: "preparation" }),
            new sap.ui.core.ListItem({ key: "replacement", text: "replacement" }),
            new sap.ui.core.ListItem({ key: "document_issue", text: "document_issue" }),
            new sap.ui.core.ListItem({ key: "lost_in_rent", text: "lost_in_rent" }),
            new sap.ui.core.ListItem({ key: "available", text: "available" }),
            new sap.ui.core.ListItem({ key: "impounded", text: "impounded" })

        ],
        change: function (oEvent) {
            let enteredValue = oEvent.getParameter("value");
            let isValid = o4WField14.getItems().some(item => item.getText() === enteredValue);
    
            if (!isValid) {
                sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list_for_Vehicle_Status"));
                o4WField14.setValue(oBundle.getText("Select_Status"));
            }
        }
    }).addEventDelegate({onAfterRendering: function(e) {o4WField14.$().find("input").attr("readonly", true);}});
    var o4WField15 = new sap.m.ComboBox({
        value:oBundle.getText("Available"),
        items:[    
            new sap.ui.core.ListItem({key:"Available",text:oBundle.getText("Available")}),
            new sap.ui.core.ListItem({key:"Breakdown",text:oBundle.getText("Breakdown")}),
            new sap.ui.core.ListItem({key:"In Maintenance",text:oBundle.getText("In_Maintenance")})
        ],
        change: function (oEvent) {
            let enteredValue = oEvent.getParameter("value");
            let isValid = o4WField15.getItems().some(item => item.getText() === enteredValue);
    
            if (!isValid) {
                sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list_for_Jaya_Vehicle_Status"));
                o4WField15.setValue(oBundle.getText("Available"));
            }
        }
    }).addEventDelegate({onAfterRendering: function(e) {o4WField15.$().find("input").attr("readonly", true);}});
    var o4WField16 = new sap.m.Input({});

    var o4WField17 = new sap.m.Input({});
    var o4WField18 = new sap.m.Input({});
    var o4WField19 = new sap.m.Input({});
    
    var o4WField20 = new sap.m.Input({enabled:false});
    var o4WField21 = new sap.m.Input({enabled:false});
    var o4WField22 = new sap.m.Input({enabled:false});
    var o4WField23 = new sap.m.Input({enabled:false});
   
    
    
    var o4WField24 = new sap.m.Input({});
    var o4WField25 = new sap.m.Input({});
    var o4WField26 = new sap.m.DatePicker({width:"100%",displayFormat: "dd-MMM-yyyy" ,valueFormat: "dd-MMM-yyyy"});
    o4WField26.attachBrowserEvent("keydown", function (oEvent) {
        oEvent.preventDefault(); // Prevent manual typing
    });
    o4WField26.attachBrowserEvent("keypress", function (oEvent) {
        oEvent.preventDefault(); // Prevent manual typing
    });
    var o4WField27 = new sap.m.DatePicker({width:"100%",displayFormat: "dd-MMM-yyyy", valueFormat: "dd-MMM-yyyy"});
    o4WField27.attachBrowserEvent("keydown", function (oEvent) {
        oEvent.preventDefault(); // Prevent manual typing
    });
    o4WField27.attachBrowserEvent("keypress", function (oEvent) {
        oEvent.preventDefault(); // Prevent manual typing
    });
    var o4WField28 = new sap.m.DatePicker({width:"100%",displayFormat: "dd-MMM-yyyy", valueFormat: "dd-MMM-yyyy"});
    o4WField28.attachBrowserEvent("keydown", function (oEvent) {
        oEvent.preventDefault(); // Prevent manual typing
    });
    o4WField28.attachBrowserEvent("keypress", function (oEvent) {
        oEvent.preventDefault(); // Prevent manual typing
    });
    var o4WField29 = new sap.m.DatePicker({width:"100%",displayFormat: "dd-MMM-yyyy", valueFormat: "dd-MMM-yyyy"});
    o4WField29.attachBrowserEvent("keydown", function (oEvent) {
        oEvent.preventDefault(); // Prevent manual typing
    });
    o4WField29.attachBrowserEvent("keypress", function (oEvent) {
        oEvent.preventDefault(); // Prevent manual typing
    });
    var o4WField30 = new sap.m.Input({enabled:false});
    var o4WField31 = new sap.m.Input({type:'Number'});

    let oForm4w =  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: reqLbl.clone().setText(oBundle.getText("Vehicle_ID")),fields: [o4WField1]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("License_Plate")),fields: [o4WField2]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Chassis_Number")),fields: [o4WField3]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Engine_Number")),fields: [o4WField4]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Vehicle_Year")),fields: [o4WField5]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Make_Id")),fields: [o4WField6]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Make")),fields: [o4WField7]}),
                ]
            }),
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Model_ID")),fields: [o4WField8]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Model")),fields: [o4WField9]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Color")),fields: [o4WField10]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Transmission")),fields: [o4WField11]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("city")),fields: [o4WField12]}),
                    // new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Workshop Group Name")),fields: [o4WField13]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Status")),fields: [o4WField14]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Odometer")),fields: [o4WField31]}),
                ]
            }),
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Jaya_Vehicle_Location")),fields: [o4WField16]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Rental_Company_Name")),fields: [o4WField17]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Leasing_Company_Name")),fields: [o4WField18]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Leasing_Company_Type")),fields: [o4WField19]}),
                ]
            }),
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Jaya_Driver_ID")),fields: [o4WField20]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Driver_Name")),fields: [o4WField21]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Driver_Type")),fields: [o4WField30]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Email")),fields: [o4WField22]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("last Checkout Date")),fields: [o4WField23]}),
                ]
            }),
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("KEUR_Registration_Number")),fields: [o4WField24]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("KP_Registration_Number")),fields: [o4WField25]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("STNK_Due_1_Year")),fields: [o4WField26]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("STNK_Due_5_Year")),fields: [o4WField27]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("KEUR_Due_Date")),fields: [o4WField28]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Control_Card_Due_Date")),fields: [o4WField29]}),
                ]
            }),
            // Button to generate QR Code
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Vehicle_QR")),fields: [
                    new sap.m.Button({
                        text: "Generate QR Code",
                        width:"50%",
                        type: sap.m.ButtonType.Emphasized,
                        press: function () {
                            // Dynamic data for QR Code
                            let qrData = o4WField2.getValue(); // Replace this with dynamic data
                            
                            var oDialog = new sap.m.Dialog({  draggable: true, resizable: true,
                                title: oBundle.getText("Vehicle_QR"),
                                content: [
                                    new sap.ui.core.HTML({
                                        content: '<canvas id="qrCanvas" style="border: 1px solid #ccc; width: 200px; height: 200px;"></canvas>',
                                    })
                                ],
                                buttons: [
                                    new sap.m.Button({ text: oBundle.getText("Close"), icon: "sap-icon://decline",press: function () { oDialog.close();}})
                                ]
                            }).open();


                            // Generate QR Code
                            let canvas = document.getElementById("qrCanvas");
                            QRCode.toCanvas(canvas, qrData, { width: 200 }, function (error) {
                                if (error) {
                                    console.error(error);
                                    sap.m.MessageToast.show("Failed to generate QR Code.");
                                } else {
                                    sap.m.MessageToast.show("QR Code generated successfully!");
                                }
                            });
                        },
                    }),
                ],
            }),]})
            
        ]});
    


    /*var add4WVehicleBtn = new sap.m.Button({ 
        enabled:false,
        // type: sap.m.ButtonType.Unstyled,
        text: oBundle.getText("Add_Vehicle"), 
        icon: "sap-icon://add",
        press: function(){
            
            // let vehicle_number = o4WField1.getValue();
            let license_number = o4WField2.getValue();
            let chassis_number = o4WField3.getValue();
            let engine_number = o4WField4.getValue();
            let vehicle_year = o4WField5.getValue();
            let make_id = o4WField6.getValue();
            let make = o4WField7.getValue();

            let model_id = o4WField8.getValue();
            let model = o4WField9.getValue();
            let vehicle_color = o4WField10.getValue();
            let vehicle_transmission = o4WField11.getValue();
            let branch = o4WField12.getValue();
            let workshop_group_name = o4WField13.getValue();
            let vehicle_status = o4WField14.getValue();
            
            let jaya_vehicle_location = o4WField16.getValue();
            let rental_company_name = o4WField17.getValue();
            let leasing_company_name = o4WField18.getValue();
            let leasing_company_type = o4WField19.getValue();

            let jaya_driver_id = o4WField20.getValue(); 
            let driver_name = o4WField21.getValue();
            let driver_email = o4WField22.getValue();
            let handover_date= o4WField23.getValue();
            let driver_type = o4WField30.getValue();


            let keur_reg_no = o4WField24.getValue();
            let kp_reg_no = o4WField25.getValue();
            let stnk_due_1year = o4WField26.getValue();
            let stnk_due_5year = o4WField27.getValue();
            let keur_due_date = o4WField28.getValue();
            let due_control_card = o4WField29.getValue();


            // if (validation( vehicle_number, oBundle.getText("Vehicle Number"))) { return; }
            if (validation( license_number, oBundle.getText("License_Plate"))) { return; }
            if (validation( chassis_number, oBundle.getText("Chassis_Number"))) { return; }
            if (validation( engine_number, oBundle.getText("Engine_Number"))) { return; }
            if (validation( vehicle_year, oBundle.getText("Vehicle_Year"))) { return; }
            if (validation( make_id, oBundle.getText("Make_ID"))) { return; }
            if (validation( make, oBundle.getText("Make"))) { return; }
            if (validation( model_id, oBundle.getText("Model_ID"))) { return; }
            if (validation( model, oBundle.getText("Model"))) { return; }
            if (validation( vehicle_color, oBundle.getText("Vehicle_Color"))) { return; }
            if (validation( vehicle_transmission, oBundle.getText("Vehicle_Transmission"))) { return; }
            if (validation( branch, oBundle.getText("Branch"))) { return; }
            if (validation( workshop_group_name, oBundle.getText("Workshop_Group_Name"))) { return; }
            // if (validation( vehicle_status, oBundle.getText("Vehicle Status"))) { return; } 
            if(vehicle_status == "Select Status"){
                vehicle_status = "";
            }
            return
            busyDialog.open();
            let current_date = getIndonesianTime();
            let insertItems = {
                master_email:emailUser,
                license_number:license_number, chassis_number:chassis_number, engine_number:engine_number, model_year:vehicle_year, make_id:make_id, make:make,
                model_id:model_id, model:model, vehicle_color:vehicle_color, transmission:vehicle_transmission,
                branch:branch, ws_group_name:workshop_group_name, vehicle_status:vehicle_status,
                jaya_vehicle_location:jaya_vehicle_location,
                rental_company_name:rental_company_name, leasing_company_name:leasing_company_name, leasing_company_type:leasing_company_type,
                jaya_driver_id:jaya_driver_id, driver_name:driver_name, driver_type:driver_type, driver_email:driver_email, handover_date:handover_date,
                keur_reg_no:keur_reg_no, kp_reg_no:kp_reg_no, stnk_due_1year:stnk_due_1year, stnk_due_5year:stnk_due_5year, keur_due_date:keur_due_date, due_control_card:due_control_card,
                created_date:current_date, created_by:operatedID
            };

            // return;

            Car_Vehicle_Master.insert(insertItems).done(function () {
                get4WVehicle();
                busyDialog.close();
                oDialog.close();
            }, failure);



        }
    });*/
   
    var update4WVehicleBtn = new sap.m.Button({ 
        visible:false,
        text: oBundle.getText("Update"), 
        icon: "sap-icon://edit",
        press: function(){
               

            let license_number = o4WField2.getValue();
            let chassis_number = o4WField3.getValue();
            let engine_number = o4WField4.getValue();
            let vehicle_year = o4WField5.getValue();
            let vehicle_status = o4WField14.getValue();
            let keur_reg_no = o4WField24.getValue();
            let kp_reg_no = o4WField25.getValue();
            let city_name = o4WField12.getValue();
            let vehicle_transmission = o4WField11.getValue();

            let stnk_due_1year = o4WField26.getValue();
            let stnk_due_5year = o4WField27.getValue();
            let keur_due_date = o4WField28.getValue();
            let due_control_card = o4WField29.getValue();
            let odometer = o4WField31.getValue();

            if (validation( license_number, oBundle.getText("License_Plate"))) { return; }
            if (validation( chassis_number, oBundle.getText("Chassis_Number"))) { return; }
            if (validation( engine_number, oBundle.getText("Engine_Number"))) { return; }
             if (validation( vehicle_year, oBundle.getText("Vehicle_Year"))) { return; }
             if (validation( city_name, oBundle.getText("City"))) { return; }
             if (validation( vehicle_transmission, oBundle.getText("Transmission"))) { return; }
             if (validation( odometer, oBundle.getText("Odometer"))) { return; }
            //  if (validation( keur_reg_no, oBundle.getText("KEUR_Registration_Number"))) { return; }
            //  if (validation( kp_reg_no, oBundle.getText("KP_Registration_Number"))) { return; }
            //  if (validation( stnk_due_1year, oBundle.getText("STNK_Due_1_Year"))) { return; }
            //  if (validation( stnk_due_5year, oBundle.getText("STNK_Due_5_Year"))) { return; }
            //  if (validation( keur_due_date, oBundle.getText("KEUR_Due_Date"))) { return; }
            //  if (validation( due_control_card, oBundle.getText("Control_Card_Due_Date"))) { return; }
         
            if(vehicle_status == "Select Status"){
                vehicle_status = "";
            };

            Car_Vehicle_Master.where(filterQueryVehicleCheck,license_number,obj['id']).take(2000).orderByDescending("createdAt").read().done(function (result) {
                if(result.length > 0 ){
                    sap.m.MessageBox.error(oBundle.getText("Duplicate_License_Number_detected_Please_enter_a_different_User_ID"));
                    return ;
                }
            })
            busyDialog.open();
            let current_date = getIndonesianTime();
            let updateItems = {
                id:obj["id"],
                model_year:vehicle_year, transmission:vehicle_transmission,city_name:city_name,
                keur_reg_no:keur_reg_no, kp_reg_no:kp_reg_no,
                license_number:license_number, chassis_number:chassis_number, engine_number:engine_number, 
                stnk_due_1year:stnk_due_1year, stnk_due_5year:stnk_due_5year, keur_due_date:keur_due_date, due_control_card:due_control_card,
                current_odometer:odometer,
                updated_date:current_date, updated_by:operatedID
            };

            Car_Vehicle_Master.update(updateItems).done(function () {
                get4WVehicle();
                addHistoryTableData(obj["license_number"],"Update","Vehicle",obj,updateItems);
                busyDialog.close();
                oDialog.close();
            }, failure);



        }
    });


    var oDialog = new sap.m.Dialog({ contentWidth: "100%", contentHeight: "70%", draggable: true, resizable: true,
        title: oBundle.getText("Add_4W_Vehicle"),
        content: [oForm4w],
        buttons: [update4WVehicleBtn,
			new sap.m.Button({ text: oBundle.getText("Close"), icon: "sap-icon://decline",press: function () { oDialog.close();}})
		]
    }).open();



    if(src == 1){

    }else if(src == 2){
        update4WVehicleBtn.setVisible(true);
        // add4WVehicleBtn.setVisible(false);
        oDialog.setTitle("Update 4W Vehicle");


        o4WField6.setEnabled(false);
        o4WField7.setEnabled(false);
        o4WField8.setEnabled(false);
        o4WField9.setEnabled(false);
        o4WField10.setEnabled(false);
        // o4WField11.setEnabled(false);
        // o4WField12.setEnabled(false);
        o4WField13.setEnabled(false);
        o4WField14.setEnabled(false);
        o4WField16.setEnabled(false);
        o4WField17.setEnabled(false);
        o4WField18.setEnabled(false);
        o4WField19.setEnabled(false);


        o4WField1.setValue(obj["id"]);
        o4WField2.setValue(obj["license_number"]);
        o4WField3.setValue(obj["chassis_number"]);
        o4WField4.setValue(obj["engine_number"]);
        o4WField5.setValue(obj["model_year"]);
        o4WField6.setValue(obj["make_id"]);
        o4WField7.setValue(obj["make"]);
        o4WField8.setValue(obj["model_id"]);
        o4WField9.setValue(obj["model"]);
        o4WField10.setValue(obj["vehicle_color"]);
        o4WField11.setValue(obj["transmission"]);
        o4WField12.setValue(obj["city_name"]);
        o4WField13.setValue(obj["workshop_group"]);
        o4WField14.setValue(obj["vehicle_status"]);
 
        o4WField16.setValue(obj["jaya_current_location"]);
        o4WField17.setValue(obj["rental_company_name"]);
        o4WField18.setValue(obj["leasing_company_name"]);
        o4WField19.setValue(obj["leasing_company_type"]);
      
        o4WField20.setValue(obj["jaya_driver_id"]);
        // o4WField21.setValue(obj["driver_name"]);
        // o4WField30.setValue(obj["driver_type"]);
        // o4WField22.setValue(obj["driver_email"]);
        // o4WField23.setValue(obj["handover_date"]);
        
        if(nullCheckAll(obj["stnk_due_1year"])){
            let stnk1Yr = formatDateToDDMMMYYYY(obj["stnk_due_1year"])
            o4WField26.setValue(stnk1Yr);
        }
        if(nullCheckAll(obj["stnk_due_5year"])){
            let stnk5Yr = formatDateToDDMMMYYYY(obj["stnk_due_5year"])
            o4WField27.setValue(stnk5Yr);
        }
        if(nullCheckAll(obj["due_control_card"])){
            let due_control = formatDateToDDMMMYYYY(obj["due_control_card"])
            o4WField29.setValue(due_control);
        }
        
        o4WField24.setValue(obj["keur_reg_no"]);
        o4WField25.setValue(obj["kp_reg_no"]);
        o4WField28.setValue(obj["keur_due_date"]);
        o4WField31.setValue(obj['current_odometer']);
        
        if(nullCheckAll(obj['jaya_driver_id'])){
            Car_Driver_Master.where({master_email:emailUser,jaya_driver_id:obj['jaya_driver_id']}).take(1).orderByDescending("createdAt").read().done(function (results) {
                // console.log(results[0]['driver_name'])
                // console.log(results[0]['driver_type'])
                // console.log(results[0]['driver_email'])
                // console.log(results[0]['handover_date'])
                o4WField21.setValue(results[0]["driver_name"]);
                o4WField30.setValue(results[0]["driver_type"]);
                o4WField22.setValue(results[0]["driver_email"]);
                o4WField23.setValue(formatDateToDDMMMYYYY(results[0]["last_due_date"]));
            })
        }
        // o4WField2.setEnabled(false);
        // o4WField3.setEnabled(false);
        // o4WField4.setEnabled(false);
        // o4WField5.setEnabled(false);
       
        // o4WField24.setEnabled(false);
        // o4WField25.setEnabled(false);
        // o4WField26.setEnabled(false);
        // o4WField27.setEnabled(false);
        // o4WField28.setEnabled(false);
        // o4WField29.setEnabled(false);
    }else if(src == 3){

        update4WVehicleBtn.setVisible(false);
        // add4WVehicleBtn.setVisible(false);
        oDialog.setTitle("View Vehicle Details");


        o4WField1.setEnabled(false);
        o4WField2.setEnabled(false);
        o4WField3.setEnabled(false);
        o4WField4.setEnabled(false);
        o4WField5.setEnabled(false);
        o4WField6.setEnabled(false);
        o4WField7.setEnabled(false);
        o4WField8.setEnabled(false);
        o4WField9.setEnabled(false);
        o4WField10.setEnabled(false);
        o4WField11.setEnabled(false);
        o4WField12.setEnabled(false);
        o4WField13.setEnabled(false);
        o4WField14.setEnabled(false);
        o4WField15.setEnabled(false);
        o4WField16.setEnabled(false);
        o4WField17.setEnabled(false);
        o4WField18.setEnabled(false);
        o4WField19.setEnabled(false);
        o4WField16.setEnabled(false);
        o4WField17.setEnabled(false);
        o4WField18.setEnabled(false);
        o4WField19.setEnabled(false);
        o4WField20.setEnabled(false);
        o4WField21.setEnabled(false);
        o4WField30.setEnabled(false);
        o4WField22.setEnabled(false);
        o4WField23.setEnabled(false);
        o4WField24.setEnabled(false);
        o4WField25.setEnabled(false);
        o4WField26.setEnabled(false);
        o4WField27.setEnabled(false);
        o4WField28.setEnabled(false);
        o4WField29.setEnabled(false);
        o4WField31.setEnabled(false);


        o4WField1.setValue(obj["id"]);
        o4WField2.setValue(obj["license_number"]);
        o4WField3.setValue(obj["chassis_number"]);
        o4WField4.setValue(obj["engine_number"]);
        o4WField5.setValue(obj["model_year"]);
        o4WField6.setValue(obj["make_id"]);
        o4WField7.setValue(obj["make"]);
        o4WField8.setValue(obj["model_id"]);
        o4WField9.setValue(obj["model"]);
        o4WField10.setValue(obj["vehicle_color"]);
        o4WField11.setValue(obj["transmission"]);
        o4WField12.setValue(obj["city_name"]);
        o4WField13.setValue(obj["workshop_group"]);
        o4WField14.setValue(obj["vehicle_status"]);
    
        o4WField16.setValue(obj["jaya_current_location"]);
        o4WField17.setValue(obj["rental_company_name"]);
        o4WField18.setValue(obj["leasing_company_name"]);
        o4WField19.setValue(obj["leasing_company_type"]);
          
        o4WField16.setValue(obj["jaya_current_location"]);
        o4WField17.setValue(obj["rental_company_name"]);
        o4WField18.setValue(obj["leasing_company_name"]);
        o4WField19.setValue(obj["leasing_company_type"]);
        o4WField20.setValue(obj["jaya_driver_id"]);
        // o4WField21.setValue(obj["driver_name"]);
        // o4WField30.setValue(obj["driver_type"]);
        // o4WField22.setValue(obj["driver_email"]);
        // o4WField23.setValue(obj["handover_date"]);
        o4WField31.setValue(obj['current_odometer']);


        if(nullCheckAll(obj["stnk_due_1year"])){
            let stnk1Yr = formatDateToDDMMMYYYY(obj["stnk_due_1year"])
            o4WField26.setValue(stnk1Yr);
        }
        if(nullCheckAll(obj["stnk_due_5year"])){
            let stnk5Yr = formatDateToDDMMMYYYY(obj["stnk_due_5year"])
            o4WField27.setValue(stnk5Yr);
        }
        if(nullCheckAll(obj["due_control_card"])){
            let due_control = formatDateToDDMMMYYYY(obj["due_control_card"])
            o4WField29.setValue(due_control);
        }
        o4WField24.setValue(obj["keur_reg_no"]);
        o4WField25.setValue(obj["kp_reg_no"]);
        o4WField28.setValue(obj["keur_due_date"]);

        if(nullCheckAll(obj['jaya_driver_id'])){
            Car_Driver_Master.where({master_email:emailUser,jaya_driver_id:obj['jaya_driver_id']}).take(1).orderByDescending("createdAt").read().done(function (results) {
                // console.log(results[0]['driver_name'])
                // console.log(results[0]['driver_type'])
                // console.log(results[0]['driver_email'])
                // console.log(results[0]['handover_date'])
                o4WField21.setValue(results[0]["driver_name"]);
                o4WField30.setValue(results[0]["driver_type"]);
                o4WField22.setValue(results[0]["driver_email"]);
                o4WField23.setValue(formatDateToDDMMMYYYY(results[0]["last_checkout_date"]));
            })
        }
    }
}






var vehicle4WJSONData = [];
var vehicle4WArray = [];
// var tempVehicle4WJSONData = [];

// var skipRowVehicle4w = 0;
// function get4WVehicle(){
//     oTableFourWheeler.setBusy(true);
//     Car_Vehicle_Master.where({master_email:emailUser}).skip(skipRowVehicle4w).take(2000).orderByDescending("createdAt").read().done(function (results) {
//         tempVehicle4WJSONData = tempVehicle4WJSONData.concat(results);

//         if(results.length < 2000){
//             vehicle4WJSONData = tempVehicle4WJSONData;            

//             var assignVehicleValues = tempVehicle4WJSONData;
//             let oxmaint_role = sessionStorage.getItem('oxmaint_role');
//             if(!allowedRoles.includes(oxmaint_role)){
//                 assignVehicleValues = filterGrabVehicle(assignVehicleValues);
//             }
            

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

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

//             for (var i = 0; i < vehicle4WJSONData.length; i++) {
//                 var vehicle = vehicle4WJSONData[i]['license_number'];
//                 vehicle4WArray = vehicle4WArray.concat(vehicle);

//             }
//             skipRowVehicle4w = 0
//             tempVehicle4WJSONData = [];
        
//         }else{
//             skipRowVehicle4w += 2000;
//             get4WVehicle();
//         }
//     })

// };


// function get4WVehicle(){
//     oTableFourWheeler.setBusy(true);
//     getAllVehicleData();
// }


function get4WVehicle(){
    busyDialog.open();
    oTableFourWheeler.setBusy(true);
    let oxmaint_role = sessionStorage.getItem('oxmaint_role');

    if(!allowedRoles.includes(oxmaint_role) && hvi_assign_vehicle != '1'){
        getAssignedVehicleData();
        // getAssignedVehicleData();
    }else{
        getAllVehicleData();
    }


};


var VehiclePage4W = new sap.m.Page("vehicle_page_4w", {
    title:oBundle.getText("4W_Vehicle_Inventory"),
    showHeader:true,
    enableScrolling:true,
    content : [oTableFourWheeler] 
}); 



// function grabVehiclePull(){
//     var vehicle_list = hvi_assign_vehicle.split('^');

//     const vehicleFilter = vehicle_list.map(num => `license_number eq '${num}'`).join(" or ");

//     const filterQuery = `master_email eq '${emailUser}' and (${vehicleFilter})`;
//     console.log(filterQuery)
//     Car_Vehicle_Master
//         .where(filterQuery)
//         .take(100)
//         .read()
//         .done(function (results) {
//             vehicle4WJSONData = results;
//             var oModel = new sap.ui.model.json.JSONModel();
//             oModel.setData({ modelData: results });
//             oTableFourWheeler.setModel(oModel);
//             oTableFourWheeler.bindItems({ path: "/modelData", template : fourWheelerTemplate });
//             oTableFourWheeler.setBusy(false);

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

//             for (var i = 0; i < vehicle4WJSONData.length; i++) {
//                 var vehicle = vehicle4WJSONData[i]['license_number'];
//                 vehicle4WArray = vehicle4WArray.concat(vehicle);

//             }
//         });
// }