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

var partFilterWOrkshopData = new sap.m.MultiInput({
    width:"20%",placeholder:"Select Workshop",
    enabled: true, showSuggestion: true, valueHelpOnly: true, fieldWidth: "100%",
    valueHelpRequest: function (oEvent) {
        selectTeamWorkshop(4,partFilterWOrkshopData);
    },
  });

//Part Master
var oTable4WPartMaster = new sap.m.Table({
    growing: true,
    noDataText:oBundle.getText("No_Data"),
    growingTriggerText:oBundle.getText("More"),
    sticky:[sap.m.Sticky.ColumnHeaders,sap.m.Sticky.HeaderToolbar,sap.m.Sticky.InfoToolbar],
    growingThreshold: 25,
    growingScrollToLoad : false,
    columns: [
        new sap.m.Column({width:"100px",header: new sap.m.Label({text: oBundle.getText("Action"),design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Part_Name"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Part_ID"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Part_Type"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Workshop"),design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Supplier"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Make"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Model"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Transmission"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Status"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
        // new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Brand"), design: sap.m.LabelDesign.Bold}),
        // minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
        // new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Model"), design: sap.m.LabelDesign.Bold}),
        // minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
       
    ],
    headerToolbar:new sap.m.OverflowToolbar({
        content: [   
            new sap.m.Button({ 
                id:"createPartsID",
                text: oBundle.getText("Add_Parts"), 
                type:sap.m.ButtonType.Emphasized,
                icon: sap.ui.core.IconPool.getIconURI("add"), 
                press: function(){
                    addUpdate4WPartMaster(1);//Create
                } 
            }),
            new sap.m.MenuButton({
                visible:true,
                text: oBundle.getText("Bulk_Upload"),
                icon: "sap-icon://database",
                menu: new sap.m.Menu({
                    itemSelected: function(oEvent) {
                        var key = oEvent.getParameter("item").getKey();
                        if(key == "1"){
                            sampleDownloadParts();
                        }else if(key == "2"){
                            //uploadDialogParts();
                            // uploadDialogPartsExcel();
                            // getPartsIdAPI()
                            bulkUploadParts();
                        }
                    },
                    items: [
                        new sap.m.MenuItem({text: oBundle.getText("Sample_Excel"),icon: "sap-icon://excel-attachment",key: "1"}),
                        new sap.m.MenuItem({text: oBundle.getText("Upload_Excel"),icon: "sap-icon://upload",key: "2"}),
                    ]
                })
            }),
            new sap.m.MenuButton({
                visible:true,
                text: oBundle.getText("Bulk_Update"),
                icon: "sap-icon://database",
                menu: new sap.m.Menu({
                    itemSelected: function(oEvent) {
                        var key = oEvent.getParameter("item").getKey();
                        if(key == "1"){
                            downloadPartMasterExcel();
                        }else if(key == "2"){
                            bulkUploadUpdateParts();
                        }
                    },
                    items: [
                        new sap.m.MenuItem({text: oBundle.getText("Download_Parts"),icon: "sap-icon://excel-attachment",key: "1"}),
                        new sap.m.MenuItem({text: oBundle.getText("Update_Excel"),icon: "sap-icon://upload",key: "2"}),
                    ]
                })
            }),
    
            new sap.m.ToolbarSpacer(),
            partFilterWOrkshopData,
            new sap.m.SearchField({
                placeholder: oBundle.getText("Search"),
                width: "300px",
                liveChange: function (event) {
                    var oBinding = oTable4WPartMaster.getBinding("items");
                    var searchStr = this.getValue();
                    if (oBinding) {
                        var oFilters = [
                        new sap.ui.model.Filter("part_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("workshop_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("workshop_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("supplier_id", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("supplier_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("part_id", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("supplier_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("make", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("model", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("transmission", sap.ui.model.FilterOperator.Contains, searchStr),
                        // new sap.ui.model.Filter("sub_category_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        // new sap.ui.model.Filter("brand_id", sap.ui.model.FilterOperator.Contains, searchStr),
                        // new sap.ui.model.Filter("brand_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        // new sap.ui.model.Filter("model_id", sap.ui.model.FilterOperator.Contains, searchStr),
                        // new sap.ui.model.Filter("model_name", 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() {
                    clearPartMultiFilters();
                    populatePartFilterDropdowns();
                    partMultiFilterDialog.open();
                }
            })

        ]
      })
});

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



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

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

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



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

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

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



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

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

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

 

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




function displayMenu4WPartMaster(event,obj){

    var oMenu = new sap.m.Menu({
        items: [
            new sap.m.MenuItem({visible:false, icon: "sap-icon://show",text: oBundle.getText("View"),key: "0"}),
            new sap.m.MenuItem({visible:false, icon: "sap-icon://edit",text: oBundle.getText("Update"),key: "1"}),
            new sap.m.MenuItem({visible:false, icon: "sap-icon://copy",text: oBundle.getText("Copy"),key: "3"}),
        ],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
            if (oItem == "0") { 
                if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('view_master_data_part_and_labour') != -1)){
                    addUpdate4WPartMaster(3, obj);
                }else{
                    sap.m.MessageToast.show("View Access not provided.");
                };
            } else if (oItem == "1") {
                if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('modify_master_data_part_and_labour') != -1)){
                    addUpdate4WPartMaster(2, obj);
                }else{
                    sap.m.MessageToast.show("Modify Access not provided.");
                }
            } else if (oItem == "2") {
                var oDialog = new sap.m.Dialog({
                    title: oBundle.getText("Alert"),
                    state: sap.ui.core.ValueState.Error,
                    content: [new sap.m.Label({ text: oBundle.getText("Sure_You_want_to_delete") })],
                    buttons: [
                                new sap.m.Button({text: oBundle.getText("Delete"),icon: "sap-icon://delete",
                                    press: function () {
                                        busyDialog.open();
                                        Part_Master.del({ id: obj['id'] }).done(function () {
                                            getPartsDetailsWorkshop(obj['workshop_number']);
                                            oDialog.close();
                                            busyDialog.close();
                                        });
                                    }
                                }),
                                new sap.m.Button({text: oBundle.getText("Cancel"),icon: "sap-icon://decline",
                                    press: function () {
                                        oDialog.close();
                                    }
                                })
                            ]
                }).open();
            
            } else if (oItem == "3") {
                addUpdate4WPartMaster(4,obj);
            }
        }
    });
  

    //View
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('view_master_data_part_and_labour') != -1)){
        oMenu.getItems()[0].setVisible(true);
    };
    //Modify
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('modify_master_data_part_and_labour') != -1)){
        oMenu.getItems()[1].setVisible(true);
    };
    //
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('create_master_data_part_and_labour') != -1)){
        oMenu.getItems()[2].setVisible(true);
    };
    
    //Delete
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('delete_master_data_part_and_labour') != -1)){
        getDeleteMenu(oMenu,"2");
    };
    oMenu.openBy(event.getSource());
};

function sampleDownloadParts(){
    window.open("assets/Part.xlsx", "_blank"); 
};
/*
function uploadDialogPartsExcel(partId){

    var matchingRows = [];
    var nonMatchingRows = [];

    var oTableUpload = new sap.ui.table.Table({width : "100%",
        title: ("Duplicate Entries"),
        selectionMode:sap.ui.table.SelectionMode.Single,
        selectionBehavior:sap.ui.table.SelectionBehavior.RowOnly,
        columns:[
            new sap.ui.table.Column({
                label: new sap.ui.commons.Label({text:oBundle.getText("Part_Type")}),
                template: new sap.ui.commons.TextView({wrapping:true}).bindProperty("text", "Part Type"),
            }),
            new sap.ui.table.Column({
                label: new sap.ui.commons.Label({text:oBundle.getText("Part_Name")}),
                template: new sap.ui.commons.TextView({wrapping:true}).bindProperty("text", "Part Name"),
            }),
            new sap.ui.table.Column({
                label: new sap.ui.commons.Label({text:oBundle.getText("Part_Cost")}),
                template: new sap.ui.commons.TextView({wrapping:true}).bindProperty("text", "Part Cost"),
            }),
            new sap.ui.table.Column({
                label: new sap.ui.commons.Label({text:oBundle.getText("Labor_Cost")}),
                template: new sap.ui.commons.TextView({wrapping:true}).bindProperty("text", "Labor Cost"),
            }),
            new sap.ui.table.Column({
                label: new sap.ui.commons.Label({text:oBundle.getText("Workshop_Number")}),
                template: new sap.ui.commons.TextView({wrapping:true}).bindProperty("text", "Workshop Number"),
            }),
            new sap.ui.table.Column({
                label: new sap.ui.commons.Label({text:oBundle.getText("Make")}),
                template: new sap.ui.commons.TextView({wrapping:true}).bindProperty("text", "Make"),
            }),
            new sap.ui.table.Column({
                label: new sap.ui.commons.Label({text:oBundle.getText("Model")}),
                template: new sap.ui.commons.TextView({wrapping:true}).bindProperty("text", "Model"),
            }),
            new sap.ui.table.Column({
                label: new sap.ui.commons.Label({text:oBundle.getText("Transmission")}),
                template: new sap.ui.commons.TextView({wrapping:true}).bindProperty("text", "Transmission"),
            })
        ]
    });

    var excelData = {};
    var created_date = getCurrentDate() + " " + getTime();
    var columnHeaders = [];

    // var colHeader = ['Category', 'Part Number', 'Item Name', 'Quantity', 'UOM', 'Item Cost', 'Manufacturer'];
    var colHeader = [
        'Part Type', 'Part Name', 'Status', 'Part Cost', 'Labor Cost', 'Workshop Group Number', 'Workshop Group Name',
        'Workshop Number', 'Workshop Name', 'Make', 'Model', 'Transmission','Supplier Number','Supplier Name'
    ];
    

    var oDialogUpload = new sap.m.Dialog({ icon: 'sap-icon://upload',
        contentWidth: "80%", contentHeight: "100%", draggable: true, resizable: true,
        title: oBundle.getText('Upload_Parts'),
        endButton: new sap.m.Button({ text: oBundle.getText('Cancel'),
            press: function () { oDialogUpload.close(); }
        }),
        beginButton: new sap.m.Button({
            text: oBundle.getText('Upload_Data'),
            press: function () {
                //oDialogUpload.close(); 
                var excelCount = (nonMatchingRows.length);

                latestPartId = parseInt(partId);

                if (excelCount>-1) {

                    for (var i = 0; i < columnHeaders.length; i++) {
                        var header = columnHeaders[i];
                        if(colHeader.indexOf(header) == -1){
                            sap.m.MessageBox.error("Column name has different from sample excel");
                            return;
                        }
                    }

                    standartBusyDialog.setText("");
                   
                    if (excelCount < 500) {

                        for (var i = 0; i < excelCount; i++) {

                            let part_type = nonMatchingRows[i]['Part Type'];
                            let part_name = nonMatchingRows[i]['Part Name'];
                            let status = nonMatchingRows[i]['Status'];
                            let part_cost = nonMatchingRows[i]['Part Cost'];
                            let labor_cost = nonMatchingRows[i]['Labor Cost'];
                            let workshop_group_number = nonMatchingRows[i]['Workshop Group Number'];
                            let workshop_group_name = nonMatchingRows[i]['Workshop Group Name'];
                            let workshop_number = nonMatchingRows[i]['Workshop Number'];
                            let workshop_name = nonMatchingRows[i]['Workshop Name'];
                            let make = nonMatchingRows[i]['Make'];
                            let model = nonMatchingRows[i]['Model'];
                            let transmission = nonMatchingRows[i]['Transmission'];
                            let supplier_number = nonMatchingRows[i]['Supplier Number'];
                            let supplier_name = nonMatchingRows[i]['Supplier Name'];
                           
                            if(
                                !nullCheckAll(part_type) || !nullCheckAll(part_name) ||
                                !nullCheckAll(status) || validateNumber(part_cost) || validateNumber(labor_cost) ||
                                !nullCheckAll(workshop_group_name) || !nullCheckAll(workshop_group_number) ||
                                !nullCheckAll(workshop_number) || !nullCheckAll(workshop_name) ||
                                !nullCheckAll(make) || !nullCheckAll(model) || !nullCheckAll(transmission)
                            ){

                                sap.m.MessageBox.error("Mandatory fields must be filled out");
                                oDialogUpload.close();
                                return;
                            };

                        
                            

                            if(part_type != 'Workshop' && part_type != 'Supplier'){
                                sap.m.MessageBox.error("Part Type Should Be Workshop or Supplier at row"+" : " + (i+1));
                                oDialogUpload.close();
                                return;
                            };
                            if(status != 'Active' && part_type != 'Inactive'){
                                sap.m.MessageBox.error("Part Status Should Be Active or Inactive at row"+" : " + (i+1));
                                oDialogUpload.close();
                                return;
                            };

                            if (isNaN(part_cost)){
                                sap.m.MessageBox.error("Please check if there is any comma(,) in your sheet and part cost should be number at row"+" : " + (i+1));
                                oDialogUpload.close();
                                return;
                            };

                            if (isNaN(labor_cost) ){
                                sap.m.MessageBox.error("Please check if there is any comma(,) in your sheet and labor cost should be number at row"+" : " + (i+1));
                                oDialogUpload.close();
                                return;
                            };

                            if(!workshop_group_number.startsWith('WSG')){
                                sap.m.MessageBox.error("Workshop group number is not correct at row"+" : " + (i+1));
                                oDialogUpload.close();
                                return;
                            };
                            
                            if(!workshop_number.startsWith('WS')){
                                sap.m.MessageBox.error("Workshop number is not correct at row"+" : " + (i+1));
                                oDialogUpload.close();
                                return;
                            };
                            
                        }
                      
                        updateBulkPartsIdAPI(nonMatchingRows.length)
                        standartBusyDialog.open();

                        var dotCounter = -1;
                        (function addDot() {
                            setTimeout(function () {
                                if (dotCounter++ < excelCount) {
                                    oDialogUpload.close();
                                   
                                    standartBusyDialog.setText("" + dotCounter + "/" + (excelCount));

                                    if (dotCounter == excelCount) {
                                        standartBusyDialog.close();
                                        get4WPartMaster();
                                        return;
                                    }

                    
                                    let insert_part_type = nonMatchingRows[dotCounter]['Part Type'];
                                    let insert_part_name = nonMatchingRows[dotCounter]['Part Name'];
                                    let insert_status = nonMatchingRows[dotCounter]['Status'];
                                    let insert_part_cost = nonMatchingRows[dotCounter]['Part Cost'];
                                    let insert_labor_cost = nonMatchingRows[dotCounter]['Labor Cost'];
                                    let insert_workshop_group_number = nonMatchingRows[dotCounter]['Workshop Group Number'];
                                    let insert_workshop_group_name = nonMatchingRows[dotCounter]['Workshop Group Name'];
                                    let insert_workshop_number = nonMatchingRows[dotCounter]['Workshop Number'];
                                    let insert_workshop_name = nonMatchingRows[dotCounter]['Workshop Name'];
                                    let insert_make = nonMatchingRows[dotCounter]['Make'];
                                    let insert_model = nonMatchingRows[dotCounter]['Model'];
                                    let insert_transmission = nonMatchingRows[dotCounter]['Transmission'];
                                    let supplier_number = nonMatchingRows[dotCounter]['Supplier Number'];
                                    let supplier_name = nonMatchingRows[dotCounter]['Supplier Name'];
                                    let created_date = getIndonesianTime();


                                    var newItem = { 
                                        master_email: emailUser,
                                        part_type:insert_part_type,
                                        vehicle_part_id:latestPartId,
                                        part_name:insert_part_name,
                                        part_status:insert_status,
                                        part_cost:insert_part_cost,
                                        labor_cost:insert_labor_cost,
                                        ws_group_number:insert_workshop_group_number,
                                        ws_group_name:insert_workshop_group_name,
                                        workshop_number:insert_workshop_number,
                                        workshop_name:insert_workshop_name,
                                        make:insert_make,
                                        supplier_id:supplier_number,
                                        supplier_name:supplier_name,
                                        model:insert_model,
                                        transmission:insert_transmission,
                                        created_date:created_date, 
                                        created_by:operatedID
                                    };
                    
                                    Part_Master.insert(newItem).done(function () {
                                        latestPartId++; 
                                        addDot();

                                    });

                                }
                            }, 1000);
                        })();

                    } else {
                        sap.m.MessageBox.error(oBundle.getText("You_can_add_1000_parts_in_single_upload"));
                        oDialogUpload.close();
                    }
                } else {
                    sap.m.MessageBox.error(oBundle.getText("Excel_is_empty"));

                }
            }
        })
    });

    var uploader = new sap.ui.unified.FileUploader({
        width: '90%',style:"Accept",
        icon:'sap-icon://browse-folder',
        fileType:["XLSX","XLS","xlsx","xls"],
        change: function (oEvent) {
        //console.log(oEvent.getParameter("files"));
            matchingRows = [];
            nonMatchingRows = [];
            var file = oEvent.getParameter("files")[0];
            if (file && window.FileReader) {
                var reader = new FileReader();
                reader.onload = function (e) {
                                                
                    var data = e.target.result;
                    var workbook = XLSX.read(data, {type: 'binary'});
                    
                    workbook.SheetNames.forEach(function (sheetName) {
                                          
                        excelData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets["Parts"]);

                        var worksheet = workbook.Sheets["Parts"]; //workbook.Sheets[sheet_name_list[sheetIndex]];
                        for (let key in worksheet) {
                            let regEx = new RegExp("^\(\\w\)\(1\){1}$");
                            if (regEx.test(key) == true) {
                                columnHeaders.push(worksheet[key].v);
                            }
                        }    
                    });
                
                let uniqueExcelData = Array.from(
                    new Map(
                        excelData.map(row => [
                            row['Part Name'] + row['Model'] + row['Make'] + row['Transmission'] +
                            row['Workshop Number'] + row['Supplier Number'] + row['Supplier Name'], 
                            row
                        ])
                    ).values()
                );
                var allPartsData = partMaster4WJSONData;
                
                uniqueExcelData.forEach(excelRow => {
                
                    var isMatching = allPartsData.some(part =>
                        part.part_name == excelRow['Part Name'] &&
                        part.make == excelRow['Make'] &&
                        part.model == excelRow['Model'] &&
                        part.transmission == excelRow['Transmission'] &&
                        part.workshop_number === excelRow['Workshop Number'] 
                    );

                    
                    if (isMatching) {
                        matchingRows.push(excelRow);
                    } else {
                        nonMatchingRows.push(excelRow);
                    }
                });

                console.log("Matching Rows:", matchingRows);
                console.log("Non-Matching Rows:", nonMatchingRows);


                var oModelUpload = new sap.ui.model.json.JSONModel();
                oModelUpload.setData({ modelData: matchingRows });
                oTableUpload.setModel(oModelUpload);
                oTableUpload.bindRows("/modelData");

                };

                reader.onerror = function (ex) {
                    console.log(ex);
                };
                reader.readAsBinaryString(file);
                //reader.readAsText(file);
            }
            //oDialogUpload.close();
        }
    });

    
    oDialogUpload.addContent(uploader);
    oDialogUpload.addContent(oTableUpload);
    // oDialogUpload.addContent(oTable);
    oDialogUpload.addContent(new sap.m.Label({wrapping : true, text: oBundle.getText("uploadNote1")}));
    // oDialogUpload.addContent(new sap.m.Label({wrapping : true, text: oBundle.getText("uploadNote2")}));
    oDialogUpload.open();
       
}*/

function addUpdate4WPartMaster(src,obj){


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

    let oIF4WPartMaster1 = new sap.m.Input({type:"Number",enabled:false}); 
    let oIF4WPartMaster2 = new  sap.m.ComboBox({
        value:oBundle.getText("Workshop"),
        items:[    
            new sap.ui.core.ListItem({key:"Workshop",text:oBundle.getText("Workshop")}),
            new sap.ui.core.ListItem({key:"Supplier",text:oBundle.getText("Supplier")}),
        ],
        change: function (oEvent) {
            let enteredValue = oEvent.getParameter("value");
            let isValid = oIF4WPartMaster2.getItems().some(item => item.getText() === enteredValue);
    
            if(enteredValue == "Workshop"){
                oFormPartMaster.getFormContainers()[1].getFormElements()[3].setVisible(false);
                supplierPartDB.removeAllTokens();
            }else{
                oFormPartMaster.getFormContainers()[1].getFormElements()[3].setVisible(true);
            }
             
            if (!isValid) {
                sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list"));
                oIF4WPartMaster2.setValue(oBundle.getText("Workshop"));
            }
        }
    }).addEventDelegate({onAfterRendering: function(e) {oIF4WPartMaster2.$().find("input").attr("readonly", true);}});
     
    
    let oIF4WPartMaster6 = new sap.m.Input({}); 
    let oIF4WPartMaster11 = new  sap.m.ComboBox({
        value:oBundle.getText("Active"),
        items:[    
            new sap.ui.core.ListItem({key:"Active",text:oBundle.getText("Active")}),
            new sap.ui.core.ListItem({key:"Inactive",text:oBundle.getText("Inactive")}),
        ],
        change: function (oEvent) {
            let enteredValue = oEvent.getParameter("value");
            let isValid = oIF4WPartMaster11.getItems().some(item => item.getText() === enteredValue);
    
             
            if (!isValid) {
                sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list"));
                oIF4WPartMaster11.setValue(oBundle.getText("Active"));
            }
        }
    }).addEventDelegate({onAfterRendering: function(e) {oIF4WPartMaster11.$().find("input").attr("readonly", true);}});
    let oIF4WPartMaster12 = new sap.m.Input({enabled:false}); 
    let oIF4WPartMaster13 = new sap.m.Input({type:'Number',
    //    change: function(oEvent) {
        // var value = oEvent.getParameter("value");
        // // Remove any dot or minus sign from the input
        // value = value.replace(/[.-]/g, "");
 
        // // Set the cleaned value back to the input
        // oEvent.getSource().setValue(value);
    // }
    }); 
    let oIF4WPartMaster14 = new sap.m.Input({type:'Number'}); 


    let oIF4WPartMaster15 = new sap.m.ComboBox({
        value: oBundle.getText("Select_Make"),
        items: {
            path: "/makes",
            template: new sap.ui.core.ListItem({
                key: "{key}",
                text: "{text}"
            })
        }
    }).addEventDelegate({onAfterRendering: function(e) {oIF4WPartMaster15.$().find("input").attr("readonly", true);}});
    let oIF4WPartMaster16 = new sap.m.ComboBox({
        value:  oBundle.getText("Select_Model"),
        items: {
            path: "/models",
            template: new sap.ui.core.ListItem({
                key: "{key}",
                text: "{text}"
            })
        }
    }).addEventDelegate({onAfterRendering: function(e) {oIF4WPartMaster16.$().find("input").attr("readonly", true);}});

    let worshopPartDB = new sap.m.MultiInput({ showSuggestion: true, fieldWidth: "100%",autocomplete:true,
        showValueHelp: true, valueHelpOnly: true,
        valueHelpRequest: function () { selectTeamWorkshop(1,worshopPartDB,oIF4WPartMaster12); },
        tokenUpdate: function (oEvent) {
            let operation = oEvent.getParameter("type"); // Type of token update: "added" or "removed"
    
            if (operation === "removed") {
                let removedTokens = oEvent.getParameter("removedTokens"); // Array of removed tokens
                let removedTexts = removedTokens.map(token => token.getText()).join(", ");
                oIF4WPartMaster12.setValue("");
            }
        }
    
    });
    
    //Vehicle Make Bind
    var filteredVehicleMake = [...new Set(vehicle4WJSONData.map(vehicle => vehicle.make))];
    let makeData = filteredVehicleMake.map(make => ({ key: make, text: make }));
    makeData.unshift({ key: oBundle.getText("Select_Make"), text: oBundle.getText("Select_Make") });
    let oMakeModel = new sap.ui.model.json.JSONModel({ makes: makeData });
    oIF4WPartMaster15.setModel(oMakeModel);

    //Vehicle Model Bind
    var filteredVehicleModel = [...new Set(vehicle4WJSONData.map(vehicle => vehicle.model))];
    let modelData = filteredVehicleModel.map(make => ({ key: make, text: make }));
    modelData.unshift({ key: oBundle.getText("Select_Model"), text: oBundle.getText("Select_Model") });
    let oModelModel = new sap.ui.model.json.JSONModel({ models: modelData });
    oIF4WPartMaster16.setModel(oModelModel);

    let worshopGroupPartDB = new sap.m.MultiInput({ showSuggestion: true, fieldWidth: "100%",
        showValueHelp: true, valueHelpOnly: true,
        valueHelpRequest: function () { selectTeamWSGroup(worshopGroupPartDB); },
        tokenUpdate: function (oEvent) {
            let operation = oEvent.getParameter("type"); // Type of token update: "added" or "removed"
    
            if (operation === "removed") {
                worshopPartDB.removeAllTokens();
                oIF4WPartMaster12.setValue("");
                let removedTokens = oEvent.getParameter("removedTokens"); // Array of removed tokens
                let removedTexts = removedTokens.map(token => token.getText()).join(", ");
            }
        }
    });
    
    var supplierPartDB = new sap.m.MultiInput({ showSuggestion: true, fieldWidth: "100%",showValueHelp: true,
        valueHelpOnly: true,
        valueHelpRequest: function () { selectSupplierWS(2,supplierPartDB); }
    });


    let oIF4WPartMaster17 = new  sap.m.ComboBox({
        value:oBundle.getText("Select_Transmission"),
        items:[    
            new sap.ui.core.ListItem({key:"Select_Transmission",text:oBundle.getText("Select_Transmission")}),
            new sap.ui.core.ListItem({key:"AT",text:oBundle.getText("AT")}),
            new sap.ui.core.ListItem({key:"MT",text:oBundle.getText("MT")}),
        ]
    }).addEventDelegate({onAfterRendering: function(e) {oIF4WPartMaster17.$().find("input").attr("readonly", true);}});


    let oFormPartMaster =  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("Part_Type")),fields: [oIF4WPartMaster2]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Part_ID")),fields: [oIF4WPartMaster1]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Part_Name")),fields: [oIF4WPartMaster6]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Status")),fields: [oIF4WPartMaster11]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Part_Cost")),fields: [oIF4WPartMaster13]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Labor_Cost")),fields: [oIF4WPartMaster14]}),
                    
                ]
            }),
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Workshop_Group_Name")),fields: [worshopGroupPartDB]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Workshop_Number")),fields: [worshopPartDB]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Workshop_Name")),fields: [oIF4WPartMaster12]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Supplier_ID")),fields: [supplierPartDB]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Make")),fields: [oIF4WPartMaster15]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Model")),fields: [oIF4WPartMaster16]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Transmission")),fields: [oIF4WPartMaster17]}),
                    
                ]
            })
        ]
    })
    
    oFormPartMaster.getFormContainers()[1].getFormElements()[3].setVisible(false);
    var add4WPartBtn = new sap.m.Button({ 
        text: oBundle.getText("Add"), 
        icon: "sap-icon://add",
        press: function(){
            let ws_group_number = "";
            let ws_group_name = "";
            let ws_groupTokenList = worshopGroupPartDB.getTokens();
            
            for (var j = 0; j < ws_groupTokenList.length; j++) {
                if (ws_group_number == "") {
                    ws_group_number = ws_groupTokenList[j].getKey();
                    ws_group_name = ws_groupTokenList[j].getText();
                }
            };

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


            let supplier_id = "";
            let supplier_name = "";
            let supplierTokenList = supplierPartDB.getTokens();
            
            for (var j = 0; j < supplierTokenList.length; j++) {
                if (supplier_id == "") {
                    supplier_id = supplierTokenList[j].getKey();
                    supplier_name = supplierTokenList[j].getText();
                }
            };

            let part_type = oIF4WPartMaster2.getValue();
            // let workshop_number = worshopPartDB.getValue();
            let workshop_name = oIF4WPartMaster12.getValue();
            
            if(!nullCheckAll(ws_group_number)){
                sap.m.MessageBox.error(oBundle.getText("Select_Workshop_Group_Name")); return; 
            }
            if (validation(workshop_number, oBundle.getText("Workshop_Number"))) { return; }
            if (validation(workshop_name, oBundle.getText("Workshop_Name"))) { return; }
            if(part_type == "Supplier"){
                if(!nullCheckAll(supplier_id)){
                    sap.m.MessageBox.error(oBundle.getText("Select_Supplier")); return; 
                }
            }


            // let part_id = oIF4WPartMaster1.getValue();
            let part_name = oIF4WPartMaster6.getValue();
            let status = oIF4WPartMaster11.getValue();
            let part_cost = oIF4WPartMaster13.getValue();
            let labor_cost = oIF4WPartMaster14.getValue();
            let make = oIF4WPartMaster15.getValue();
            let model = oIF4WPartMaster16.getValue();
            let transmission = oIF4WPartMaster17.getValue();
            
            // if (validation(part_id, oBundle.getText("Part_Id"))) { return; }
            if (validation(part_name, oBundle.getText("Part_Name"))) { return; }
            if (validation(status, oBundle.getText("Status"))) { return; }
            if (validation(make, oBundle.getText("Make"))) { return; }
            if (validation(model, oBundle.getText("Model"))) { return; }
            
            if (validateNumber(part_cost,oBundle.getText("Part_Cost") )) { return; }
            if (validateNumber(labor_cost,oBundle.getText("Labor_Cost") )) { return; }
            if(model == oBundle.getText("Select_Model")){
                sap.m.MessageBox.error("Please " +oBundle.getText("Select_Model")); 
                return
            }
            if(make == oBundle.getText("Select_Make")){
                sap.m.MessageBox.error("Please " + oBundle.getText("Select_Make")); 
                return
            }
            if(transmission == oBundle.getText("Select_Transmission")){
                sap.m.MessageBox.error("Please " +oBundle.getText("Select_Transmission")); 
                return
            }
            busyDialog.open();

            // Part_Master.where({master_email:emailUser,vehicle_part_id:part_id}).take(10).read().done(function (results) {
            //     if(results.length > 0){
            //         sap.m.MessageBox.error(oBundle.getText("Same_Part_ID_Available_for_workshop")); 
            //         busyDialog.close();
            //         return; 
            //     }else{
                    Part_Master.where({master_email:emailUser,part_name:part_name,workshop_number:workshop_number,make:make,model:model,transmission:transmission}).take(10).read().done(function (results) {
        
                        if(results.length > 0){
                            sap.m.MessageBox.error(oBundle.getText("Same_Part_Available_for_workshop") + " " + workshop_number);
                            busyDialog.close();
                            return; 
                        }else{
                            
                            
                            var current_date = getIndonesianTime();
        
                            let insertItems = {
                                master_email:emailUser,part_type:part_type, //vehicle_part_id:part_id, 
                                part_name:part_name,  part_status:status,
                                part_cost:part_cost,labor_cost:labor_cost,make:make,model:model,transmission:transmission,
                                ws_group_name:ws_group_name,ws_group_number:ws_group_number, workshop_number:workshop_number, workshop_name:workshop_name,
                                supplier_id:supplier_id,supplier_name:supplier_name,
                                created_date:current_date, created_by:operatedID
                            } 
        
                            Part_Master.insert(insertItems).done(function(){
                                
                                // get4WPartMaster();
                                getPartsDetailsWorkshop(insertItems['workshop_number']);
                                updateBulkPartsIdAPI(1);
                                addHistoryTableData(insertItems['part_name'],"Insert","Part");
                                sap.m.MessageToast.show("Part Added Successfully.");
                                busyDialog.close();
                                oDialog.close();
                            }, failure)
                        }
                    })
                // }
            // })

        }
    });
    var update4WPartBtn = new sap.m.Button({ 
        visible:false,
        text: oBundle.getText("Update"), 
        icon: "sap-icon://edit",
        press: function(){
            let ws_group_number = "";
            let ws_group_name = "";
            let ws_groupTokenList = worshopGroupPartDB.getTokens();
            
            for (var j = 0; j < ws_groupTokenList.length; j++) {
                if (ws_group_number == "") {
                    ws_group_number = ws_groupTokenList[j].getKey();
                    ws_group_name = ws_groupTokenList[j].getText();
                }
            };

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


            let supplier_id = "";
            let supplier_name = "";
            let supplierTokenList = supplierPartDB.getTokens();
            
            for (var j = 0; j < supplierTokenList.length; j++) {
                if (supplier_id == "") {
                    supplier_id = supplierTokenList[j].getKey();
                    supplier_name = supplierTokenList[j].getText();
                }
            };

            let part_type = oIF4WPartMaster2.getValue();
            
            // let workshop_number = worshopPartDB.getValue();
            let workshop_name = oIF4WPartMaster12.getValue();
            if(!nullCheckAll(ws_group_number)){
                sap.m.MessageBox.error(oBundle.getText("Select_Workshop_Group_Name")); return; 
            };
            if (validation(workshop_number, oBundle.getText("Workshop_Number"))) { return; }
            if (validation(workshop_name, oBundle.getText("Workshop_Name"))) { return; }
            if(part_type == "Supplier"){
                if(!nullCheckAll(supplier_id)){
                    sap.m.MessageBox.error(oBundle.getText("Select_Supplier")); return; 
                }
            }


            // let part_id = oIF4WPartMaster1.getValue();
            let part_name = oIF4WPartMaster6.getValue();
            let status = oIF4WPartMaster11.getValue();
            let part_cost = oIF4WPartMaster13.getValue();
            let labor_cost = oIF4WPartMaster14.getValue();
            let make = oIF4WPartMaster15.getValue();
            let model = oIF4WPartMaster16.getValue();
            let transmission = oIF4WPartMaster17.getValue();
            
            // if (validation(part_id, oBundle.getText("Part_Id"))) { return; }
            if (validation(part_name, oBundle.getText("Part_Name"))) { return; }
            if (validation(status, oBundle.getText("Status"))) { return; }
            if (validation(make, oBundle.getText("Make"))) { return; }
            if (validation(model, oBundle.getText("Model"))) { return; }

            if (validateNumber(part_cost,oBundle.getText("Part_Cost") )) { return; }
            if (validateNumber(labor_cost,oBundle.getText("Labor_Cost") )) { return; }
            if(model == oBundle.getText("Select_Model")){
                sap.m.MessageBox.error("Please " +oBundle.getText("Select_Model")); 
                return
            }
            if(make == oBundle.getText("Select_Make")){
                sap.m.MessageBox.error("Please " + oBundle.getText("Select_Make")); 
                return
            }
            if(transmission == oBundle.getText("Select_Transmission")){
                sap.m.MessageBox.error("Please " +oBundle.getText("Select_Transmission")); 
                return
            }
            busyDialog.open();

            // Car_Pa_Master.where(filterQueryVehicleCheck,license_number,obj['id']).take(2000).orderByDescending("createdAt").read().done(function (result) {
            Part_Master.where(filterQueryPartCheck,part_name,workshop_number,obj['id'],make,model,transmission).take(10).read().done(function (results) {
                if(results.length > 0 ){
                    busyDialog.close();
                    sap.m.MessageBox.error(oBundle.getText("Same_Part_Available_for_workshop") + workshop_number); return;
                }else{
                    busyDialog.open();
                    var updated_date = getIndonesianTime();
        
                    let updateItems = {id:obj['id'],part_name:part_name,  part_status:status,
                        // vehicle_part_id:part_id, 
                        part_cost:part_cost,labor_cost:labor_cost,make:make,model:model,transmission:transmission,
                        ws_group_name:ws_group_name,ws_group_number:ws_group_number, workshop_number:workshop_number, workshop_name:workshop_name,
                        supplier_id:supplier_id,supplier_name:supplier_name,
                        updated_date:updated_date, updated_by:operatedID
                    } 
        
                    Part_Master.update(updateItems).done(function(){
                        // get4WPartMaster();
                        getPartsDetailsWorkshop(updateItems['workshop_number']);
                        sap.m.MessageToast.show("Part Updated Successfully.");
                        addHistoryTableData(updateItems['id'],"Update","Part",obj,updateItems);
                        busyDialog.close();
                        oDialog.close();
                    }, failure)
                }
            })


        }
    });

    var oDialog = new sap.m.Dialog({ contentWidth: "80%", contentHeight: "40%", draggable: true, resizable: true,
        title: oBundle.getText("Add_Parts"),
        content: [oFormPartMaster],
        buttons: [add4WPartBtn,update4WPartBtn,
			new sap.m.Button({ text: oBundle.getText("Close"), icon: "sap-icon://decline",press: function () { oDialog.close();}})
		]
    }).open();

    if(src == 1){ //Add

        oFormPartMaster.getFormContainers()[0].getFormElements()[1].setVisible(false);

    }else if(src == 2){ //Update
        add4WPartBtn.setVisible(false);
        update4WPartBtn.setVisible(true);
        oDialog.setTitle(oBundle.getText("Update_Parts"));
        

        oIF4WPartMaster1.setValue(obj["part_id"]);
        oIF4WPartMaster1.setEnabled(false);
        oIF4WPartMaster2.setValue(obj["part_type"]);
        oIF4WPartMaster2.setEnabled(false);
        
        

        oIF4WPartMaster6.setValue(obj["part_name"]);
        oIF4WPartMaster11.setValue(obj["part_status"]);
        oIF4WPartMaster12.setValue(obj["workshop_name"]);
        oIF4WPartMaster13.setValue(obj["part_cost"]);
        oIF4WPartMaster14.setValue(obj["labor_cost"]);
        oIF4WPartMaster15.setValue(obj["make"]);
        oIF4WPartMaster16.setValue(obj["model"]);
        oIF4WPartMaster17.setValue(obj["transmission"]);
        
        if(nullCheckAll(obj['workshop_number'])){
            // worshopPartDB.setValue(obj['workshop_number']);
            worshopPartDB.addToken(new sap.m.Token({ key: obj['workshop_number'], text: obj['workshop_number'] }));
            oIF4WPartMaster12.setValue(obj['workshop_name']);
        };
        if(nullCheckAll( obj['ws_group_number'])){
            worshopGroupPartDB.addToken(new sap.m.Token({ key: obj['ws_group_number'], text: obj['ws_group_name'] }));
        };
        
        if(obj['part_type'] == "Workshop"){
            oFormPartMaster.getFormContainers()[1].getFormElements()[3].setVisible(false);
        }else{
            oFormPartMaster.getFormContainers()[1].getFormElements()[3].setVisible(true);
            if(nullCheckAll( obj['supplier_id'])){
                supplierPartDB.addToken(new sap.m.Token({ key: obj['supplier_id'], text: obj['supplier_name'] }));
            };
        }

    }else if(src == 3){ //View
        
        add4WPartBtn.setVisible(false);
        update4WPartBtn.setVisible(false);
        oDialog.setTitle(oBundle.getText("View Parts Detail"));

        
        oIF4WPartMaster1.setValue(obj["part_id"]);
        oIF4WPartMaster2.setValue(obj["part_type"]);
       
        
        
        oIF4WPartMaster6.setValue(obj["part_name"]);
        oIF4WPartMaster11.setValue(obj["part_status"]);
        oIF4WPartMaster12.setValue(obj["workshop_name"]);
        oIF4WPartMaster13.setValue(obj["part_cost"]);
        oIF4WPartMaster14.setValue(obj["labor_cost"]);
        oIF4WPartMaster15.setValue(obj["make"]);
        oIF4WPartMaster16.setValue(obj["model"]);
        oIF4WPartMaster17.setValue(obj["transmission"]);

        if(nullCheckAll(obj['workshop_number'])){
            worshopPartDB.setValue(obj['workshop_number']);
            oIF4WPartMaster12.setValue(obj['workshop_name']);
        };
        if(nullCheckAll( obj['ws_group_number'])){
            worshopGroupPartDB.addToken(new sap.m.Token({ key: obj['ws_group_number'], text: obj['ws_group_name'] }));
        };
        
        if(obj['part_type'] == "Workshop"){
            oFormPartMaster.getFormContainers()[1].getFormElements()[3].setVisible(false);
        }else{
            oFormPartMaster.getFormContainers()[1].getFormElements()[3].setVisible(true);
            if(nullCheckAll( obj['supplier_id'])){
                supplierPartDB.addToken(new sap.m.Token({ key: obj['supplier_id'], text: obj['supplier_name'] }));
            };
        }


        oIF4WPartMaster1.setEnabled(false);
        oIF4WPartMaster2.setEnabled(false);
        oIF4WPartMaster6.setEnabled(false);
        oIF4WPartMaster11.setEnabled(false);
        oIF4WPartMaster12.setEnabled(false);
        oIF4WPartMaster13.setEnabled(false);
        oIF4WPartMaster14.setEnabled(false);
        oIF4WPartMaster15.setEnabled(false);
        oIF4WPartMaster16.setEnabled(false);
        oIF4WPartMaster17.setEnabled(false);
        worshopGroupPartDB.setEnabled(false);
        worshopPartDB.setEnabled(false);
        supplierPartDB.setEnabled(false);
    }else if(src == 4){

        oFormPartMaster.getFormContainers()[0].getFormElements()[1].setVisible(false);

        // oIF4WPartMaster1.setValue(obj["vehicle_part_id"]);
        oIF4WPartMaster2.setValue(obj["part_type"]);
       
        
        
        oIF4WPartMaster6.setValue(obj["part_name"]);
        oIF4WPartMaster11.setValue(obj["part_status"]);
        oIF4WPartMaster13.setValue(obj["part_cost"]);
        oIF4WPartMaster14.setValue(obj["labor_cost"]);
        oIF4WPartMaster15.setValue(obj["make"]);
        oIF4WPartMaster16.setValue(obj["model"]);
        
        if(obj['part_type'] == "Workshop"){
            oFormPartMaster.getFormContainers()[1].getFormElements()[3].setVisible(false);
        }else{
            oFormPartMaster.getFormContainers()[1].getFormElements()[3].setVisible(true);
            if(nullCheckAll( obj['supplier_id'])){
                supplierPartDB.addToken(new sap.m.Token({ key: obj['supplier_id'], text: obj['supplier_name'] }));
            };
        }
    }

};


function downloadPartMasterExcel() {
    var xlsHeader = [
        oBundle.getText("Part ID"), 
        oBundle.getText("Part Name"),
        oBundle.getText("Part Cost"),         
        oBundle.getText("Labor Cost"),         
        oBundle.getText("Make"),
        oBundle.getText("Model"),
        oBundle.getText("Transmission"),
        oBundle.getText("Workshop Number"),
        oBundle.getText("Workshop Name"),
        oBundle.getText("Workshop Group Number"),
        oBundle.getText("Workshop Group Name"),
        oBundle.getText("Supplier ID"),
        oBundle.getText("Supplier Number"),
        oBundle.getText("Status")
    ];

    var dataObject = [];
    // var tableItem = oTable4WPartMaster.getItems();
    var alltableItemdata = oTable4WPartMaster.getModel().getData();
    var tableItem = alltableItemdata['modelData']
    for (var i = 0; i < tableItem.length; i++) {
        var item = tableItem[i]; //.getBindingContext().getObject();

        dataObject.push([
            item.part_id,   
            item.part_name, 
            item.part_cost,  
            item.labor_cost,
            item.make,
            item.model,
            item.transmission,
            item.workshop_number,
            item.workshop_name,
            item.ws_group_number,
            item.ws_group_name,
            item.supplier_id,
            item.supplier_name,
            item.part_status
        ]);
    }

    var createXLSLFormatObj = [];
    createXLSLFormatObj.push(xlsHeader);
    createXLSLFormatObj = createXLSLFormatObj.concat(dataObject);

    var filename = "partsUpdateExcelExport.xlsx";
    var sheet_name = "Parts";

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

    var range = XLSX.utils.decode_range(ws['!ref']);

    // Step 1: Unlock all cells first (to prevent the whole sheet from being locked)
    for (var R = range.s.r; R <= range.e.r; ++R) {
        for (var C = range.s.c; C <= range.e.c; ++C) {
            var cellRef = XLSX.utils.encode_cell({ r: R, c: C });
            if (!ws[cellRef]) ws[cellRef] = {};
            ws[cellRef].s = { protection: { locked: false } }; // Unlock all cells
        }
    }

    // Step 2: Lock only column A (Part ID)
    for (var R = range.s.r + 1; R <= range.e.r; ++R) { // Skip the header row
        var cellRef = XLSX.utils.encode_cell({ r: R, c: 0 }); // Column A (Index 0)
        ws[cellRef].s = { protection: { locked: true } }; // Lock only this column
    }

    // Step 3: Enable sheet protection but keep unlocked cells editable
    // ws['!protect'] = { 
    //     sheet: true, 
    //     selectLockedCells: true, 
    //     selectUnlockedCells: true,
    //     formatCells: false, 
    //     formatColumns: false, 
    //     formatRows: false
    // };

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




var partMaster4WJSONData = [];
/*
var tempPartMaster4WJSONData = [];
var skipRowPartmaster4w = 0;

function get4WPartMaster(){
    oTable4WPartMaster.setBusy(true);
    Part_Master.where({master_email:emailUser}).skip(skipRowPartmaster4w).take(2000).orderByDescending("createdAt").read().done(function (results) {
        tempPartMaster4WJSONData = tempPartMaster4WJSONData.concat(results);

        if(results.length < 2000){
            
            results =  "";
            let oxmaint_role = sessionStorage.getItem('oxmaint_role');

            if(allowedRoles.includes(oxmaint_role) ){
                results = tempPartMaster4WJSONData
            }else{
                results = tempPartMaster4WJSONData.filter(function(val,ind){
                    return val.workshop_number == oxmaint_workshop_number;
                })
            }
            partMaster4WJSONData = results;            


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

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

            skipRowPartmaster4w = 0
            tempPartMaster4WJSONData = [];
        
        }else{
            skipRowPartmaster4w += 2000;
            get4WPartMaster();
        }
    })

}
*/


function get4WPartMaster(){
    // getPartsDetails()

    let oxmaint_role = sessionStorage.getItem('oxmaint_role');

    if(allowedRoles.includes(oxmaint_role) ){
        // getPartsDetails();
    }else{
        getPartsDetailsWorkshop(oxmaint_workshop_number);
    }
}

var partMasterPage4W = new sap.m.Page("part_master_page_4w", {
    title:oBundle.getText("Parts_Master"),
    showHeader:true,
    enableScrolling:true,
    content : [oTable4WPartMaster] 
}); 

