// var Car_Workshop = client.getTable('Car_Workshop');
// var Car_Workshop_Master = client.getTable('Car_Workshop_Master');


var oTable4WWorkshop = 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({wrapping:true, text: oBundle.getText("Workshop_Group_Number"),design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Workshop_Group_Name"), 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_Number"), 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_Name"),design: sap.m.LabelDesign.Bold})}),
        // new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Workshop_Group"), design: sap.m.LabelDesign.Bold}),
        // minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("E-mail"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("City"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left",width:"100px"}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Tax_Information"), 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("Tax_Percentage"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Center",width:"120px"}),
    ],
    headerToolbar:new sap.m.OverflowToolbar({
        content: [   
            new sap.m.Button({ 
                id:"grabWorkshopBtnID",
                text: oBundle.getText("Add_4W_Workshop"), 
                type:sap.m.ButtonType.Emphasized,
                icon: sap.ui.core.IconPool.getIconURI("add"), 
                press: function(){
                    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('create_workshop') != -1)){
                        addUpdate4WWorkshop(1);//Cretae
                    }else{
                        sap.m.MessageToast.show("Create Access not provided.");
                    }
                } 
            }),
            new sap.m.ToolbarSpacer(),
            new sap.m.SearchField({
                placeholder: oBundle.getText("Search"),
                width: "300px",
                liveChange: function (event) {
                    var oBinding = oTable4WWorkshop.getBinding("items");
                    var searchStr = this.getValue();
                    if (oBinding) {
                        var oFilters = [
                        new sap.ui.model.Filter("ws_group_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("ws_group_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("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("email", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("address", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("city", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("tax_information", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("tax_percentage", sap.ui.model.FilterOperator.Contains, searchStr),
                        ];
                        var filterObj = new sap.ui.model.Filter(oFilters, false);
                        oBinding.filter(filterObj);
                    } else {
                        oBinding.filter([]);
                    }
                }
        
            }),
        ]
      })
});

var workshop4WTemplate = 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);
                    displayMenu4WWorkshop(event,obj);
              }
          }),
          new sap.m.Label({wrapping:true,text: "{ws_group_number}"}),
          new sap.m.Label({wrapping:true,text: "{ws_group_name}"}),
          new sap.m.Label({wrapping:true,text: "{workshop_number}"}),
          new sap.m.Label({wrapping:true,text: "{workshop_name}"}),
        //   new sap.m.VBox({
        //       items:[
        //         new sap.m.Label({wrapping:true,text: "{ws_group_number}"}),
        //         new sap.m.Label({wrapping:true,text: "{ws_group_name}"}),

        //     ]
        //   }),
          new sap.m.Label({wrapping:true,text: "{email}"}),
          new sap.m.Label({wrapping:true,text: "{city}"}),
          new sap.m.Label({wrapping:true,text: "{tax_information}"}),
          new sap.m.Label({wrapping:true,text: "{tax_percentage}"}),
         
         ]
});


//Workshop Master
var oTable4WWSMaster = 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({wrapping:true, text: oBundle.getText("Workshop_Group_Number"),design: sap.m.LabelDesign.Bold}),
        sortIndicator:"Descending"}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Workshop_Group_Name"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
       
    ],
    headerToolbar:new sap.m.OverflowToolbar({
        content: [   
            new sap.m.Button({ 
                id:"grabWorkshopMasterBtnID",
                text: oBundle.getText("Add_Workshop_Group"), 
                type:sap.m.ButtonType.Emphasized,
                icon: sap.ui.core.IconPool.getIconURI("add"), 
                press: function(){
                    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('create_workshop_group') != -1)){
                        addUpdate4WWSMaster(1);//Cretae
                    }else{
                        sap.m.MessageToast.show("Create Access not provided.");
                    }
                } 
            }),
            new sap.m.ToolbarSpacer(),
            new sap.m.SearchField({
                placeholder: oBundle.getText("Search"),
                width: "300px",
                liveChange: function (event) {
                    var oBinding = oTable4WWSMaster.getBinding("items");
                    var searchStr = this.getValue();
                    if (oBinding) {
                        var oFilters = [
                        new sap.ui.model.Filter("ws_group_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("ws_group_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        ];
                        var filterObj = new sap.ui.model.Filter(oFilters, false);
                        oBinding.filter(filterObj);
                    } else {
                        oBinding.filter([]);
                    }
                }
        
            }),
        ]
      })
});

var wsMaster4WTemplate = 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);
                    displayMenu4WWSMaster(event,obj);
              }
          }),
          new sap.m.Label({wrapping:true,text: "{ws_group_number}"}),
          new sap.m.Label({wrapping:true,text: "{ws_group_name}"}),
         
         ]
});



function displayMenu4WWorkshop(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"}),
        ],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
            if (oItem == "0") { 
                addUpdate4WWorkshop(3, obj);  // View
            } else if (oItem == "1") {
                addUpdate4WWorkshop(2, obj); // Update
            } 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();
                                        Car_Workshop.del({ id: obj['id'] }).done(function () {
                                            getWorkshop();
                                            addHistoryTableData(obj['workshop_number'],"Delete","Workshop");
                                            oDialog.close();
                                            busyDialog.close();
                                        });
                                    }
                                }),
                                new sap.m.Button({text: oBundle.getText("Cancel"),icon: "sap-icon://decline",
                                    press: function () {
                                        oDialog.close();
                                    }
                                })
                            ]
                }).open();
            }
        }
    });

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

function displayMenu4WWSMaster(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"}),
        ],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
            if (oItem == "0") { 
                addUpdate4WWSMaster(3, obj); // View
            } else if (oItem == "1") {
                getLatestWorkshopMaster(obj['ws_group_number']);
                // addUpdate4WWSMaster(2, obj); //Update
            } 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();
                                        Car_Workshop_Master.del({ id: obj['id'] }).done(function () {
                                            getWorkshopMaster();
                                            addHistoryTableData(obj['ws_group_number'],"Delete","Workshop Group");
                                            oDialog.close();
                                            busyDialog.close();
                                        });
                                    }
                                }),
                                new sap.m.Button({text: oBundle.getText("Cancel"),icon: "sap-icon://decline",
                                    press: function () {
                                        oDialog.close();
                                    }
                                })
                            ]
                }).open();
            
            
            }
        }
    });
    //View
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('view_workshop_group') != -1)){
        oMenu.getItems()[0].setVisible(true);
    }
    //Modify
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('modify_workshop_group') != -1)){
        oMenu.getItems()[1].setVisible(true);
    }
    //DELETE
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('delete_workshop_group') != -1)){
        getDeleteMenu(oMenu,"2");
    }
    oMenu.openBy(event.getSource());
};



function addUpdate4WWorkshop(src,obj){
   
    let reqLbl = new sap.m.Label({ required: true });
    let oLbl = new sap.m.Label({ });

    let oIF4wWorkshop1 = new sap.m.Input({placeholder:"Pick From Workshop Group"}); 
    let oIF4wWorkshop2 = new sap.m.Input({enabled:false}); 
    let oIF4wWorkshop3 = new sap.m.Input({
        maxLength:100,
        liveChange: function (oEvent) {
            var sValue = oEvent.getParameter("value");
            if (sValue.length == 100) {
                sap.m.MessageToast.show("Maximum character limit of Workshop Name " + 100 + " reached.");
            }
        }
    }); 
    let oIF4wWorkshop4 = new sap.m.Input({}); 
    let oIF4wWorkshop5 = new sap.m.TextArea({width:"100%",height:"100px",rows : 4, wrapping : sap.ui.core.Wrapping.on});
    let oIF4wWorkshop6 = cityCB.clone(); 
    oIF4wWorkshop6.addEventDelegate({onAfterRendering: function(e) {oIF4wWorkshop6.$().find("input").attr("readonly", true);}});
    let oIF4wWorkshop7 = new sap.m.Input({placeholder:"MultiSelect Supplier"}); 
    // let oIF4wWorkshop8 = new sap.m.Input({}); 
    // let oIF4wWorkshop9 = new sap.m.Input({}); 
    let oIF4wWorkshop10 = new  sap.m.ComboBox({
        // layoutData: new sap.ui.layout.GridData({span: "L3 M6 S12"}),
        value:oBundle.getText("No"),
        items:[    
            new sap.ui.core.ListItem({key:"1",text:oBundle.getText("Yes")}),
            new sap.ui.core.ListItem({key:"2",text:oBundle.getText("No")}),
        ],
        change: function (oEvent) {
            let enteredValue = oEvent.getParameter("value");
            let isValid = oIF4wWorkshop10.getItems().some(item => item.getText() === enteredValue);
    
             
            if(oIF4wWorkshop10.getSelectedKey() == "1"){
                oIF4wWorkshop11.setEnabled(true);
                oIF4wWorkshop11.setValue("0");
            }else{
                oIF4wWorkshop11.setEnabled(false);
                oIF4wWorkshop11.setValue("0");
            }

            if (!isValid) {
                sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list"));
                oIF4wWorkshop10.setValue(oBundle.getText("No"));
            }
        }
    }).addEventDelegate({onAfterRendering: function(e) {oIF4wWorkshop10.$().find("input").attr("readonly", true);}});
     
    let oIF4wWorkshop11 = new sap.m.Input({value:"0",
        enabled:false,
        maxLength:100,
        liveChange: function (oEvent) {
            var sValue = oEvent.getParameter("value");
            if (sValue.length == 100) {
                sap.m.MessageToast.show("Maximum character limit of Tax percentage " + 100 + " reached.");
            }
        }
    }); 

    oIF4wWorkshop6.attachChange(function (oEvent) {
        let enteredValue = oEvent.getParameter("value");
        let isValid = oIF4wWorkshop6.getItems().some(item => item.getText() === enteredValue);

        if (!isValid) {
            sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list_for_tax_Information"));
            oIF4wWorkshop10.setValue(oBundle.getText("No"));
        }
    });

    var worshopGroupWSDB = new sap.m.MultiInput({ showSuggestion: true, fieldWidth: "100%",
        showValueHelp: true,valueHelpOnly: true,
        valueHelpRequest: function () { selectTeamWSGroup(worshopGroupWSDB); }
    });
    var suppliesWSDB = new sap.m.MultiInput({ showSuggestion: true, fieldWidth: "100%",
        showValueHelp: true,valueHelpOnly: true,
        valueHelpRequest: function () { selectSupplierWS(1,suppliesWSDB); }
    });

    let oForm2w =  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("Workshop_Group_Name")),fields: [worshopGroupWSDB]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Workshop_Number")),fields: [oIF4wWorkshop2]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Workshop_Name")),fields: [oIF4wWorkshop3]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("E-mail")),fields: [oIF4wWorkshop4]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("City")),fields: [oIF4wWorkshop6]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Supplier")),fields: [suppliesWSDB]}),
                ]}),
                new sap.ui.layout.form.FormContainer({
                    formElements: [
                        new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Address")),fields: [oIF4wWorkshop5]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Tax_Information")),fields: [oIF4wWorkshop10]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Tax_Percentage")),fields: [oIF4wWorkshop11]}),
                ]
            })
        ]
    });


    var add4WWorkshopBtn = new sap.m.Button({ 
        text: oBundle.getText("Add"), 
        icon: "sap-icon://add",
        press: function(){
            // let ws_group_number = worshopGroupWSDB.getTokens()[0].getKey();
            // let ws_group_name = worshopGroupWSDB.getTokens()[0].getText();

            let ws_group_number = "";
            let ws_group_name = "";
            let ws_groupTokenList = worshopGroupWSDB.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 = oIF4wWorkshop2.getValue();
            let workshop_name = oIF4wWorkshop3.getValue();
            let email = oIF4wWorkshop4.getValue();
            let city = oIF4wWorkshop6.getValue();
            let address = oIF4wWorkshop5.getValue();
            let tax_information = oIF4wWorkshop10.getValue();
            let tax_percentage = oIF4wWorkshop11.getValue();
            
            // let supplier = oIF4wWorkshop7.getValue();
            let supplier_number = "";
            let supplier_name = "";
            let oTokenList = suppliesWSDB.getTokens();
            for (var j = 0; j < oTokenList.length; j++) {
                if (supplier_number == "") {
                    supplier_number = oTokenList[j].getKey();
                    supplier_name = oTokenList[j].getText();
                } else {
                    supplier_number = supplier_number + "^" + oTokenList[j].getKey();
                    supplier_name = supplier_name + "^" + oTokenList[j].getText();
                }
            }

            // if(supplier_number == ""){
            //     sap.m.MessageBox.error(oBundle.getText("Select Supplier"));
            //     return false;
            // }
            //Validation            
            if (validation(ws_group_number, oBundle.getText("Workshop_Group_Number"))) { return; }
            if (validation(workshop_number, oBundle.getText("Workshop_Number"))) { return; }
            if (validation(workshop_name, oBundle.getText("Workshop_Name"))) { return; }
            if (validation(email, oBundle.getText("Email"))) { return; }
            if (validation(city, oBundle.getText("City"))) { return; }
            if (validation(address, oBundle.getText("Address"))) { return; }
            if (validation(tax_information, oBundle.getText("Tax_Information"))) { return; }
            if (validateNumber(tax_percentage, oBundle.getText("Tax_Percentage"))) { return; }
            
            if(city == "Select City"){
                sap.m.MessageBox.error(oBundle.getText("Please_Select_City")); return;
            }

            // return
            busyDialog.open();
            var current_date = getIndonesianTime();
            let insertItems = {
                master_email:emailUser,
                ws_group_number:ws_group_number, ws_group_name:ws_group_name, workshop_number:workshop_number, workshop_name:workshop_name, 
                email:email, address:address, city:city, supplier_number:supplier_number, supplier_name:supplier_name,
                tax_information:tax_information, tax_percentage:tax_percentage, 
                created_date:current_date, created_by:operatedID
            };

            Car_Workshop.insert(insertItems).done(function(){
                getWorkshop();
                sap.m.MessageToast.show("Workshop Added Successfully.");
                addHistoryTableData(insertItems['workshop_number'],"Insert","Workshop");
                busyDialog.close();
                oDialog.close();
            }, failure)

        }
    });
    var update4WWorkshopBtn = new sap.m.Button({ 
        visible:false,
        text: oBundle.getText("Update"), 
        icon: "sap-icon://edit",
        press: function(){
 
            
            // let ws_group_number = worshopGroupWSDB.getTokens()[0].getKey();
            // let ws_group_name = worshopGroupWSDB.getTokens()[0].getText();

            let ws_group_number = "";
            let ws_group_name = "";
            let ws_groupTokenList = worshopGroupWSDB.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 = oIF4wWorkshop2.getValue();
            let workshop_name = oIF4wWorkshop3.getValue();
            let email = oIF4wWorkshop4.getValue();
            let city = oIF4wWorkshop6.getValue();
            let address = oIF4wWorkshop5.getValue();
            let tax_information = oIF4wWorkshop10.getValue();
            let tax_percentage = oIF4wWorkshop11.getValue();

            //Validation            
            if (validation(ws_group_number, oBundle.getText("Workshop_Group_Number"))) { return; }
            if (validation(workshop_number, oBundle.getText("Workshop_Number"))) { return; }
            if (validation(workshop_name, oBundle.getText("Workshop_Name"))) { return; }
            if (validation(email, oBundle.getText("Email"))) { return; }
            if (validation(city, oBundle.getText("City"))) { return; }
            if (validation(address, oBundle.getText("Address"))) { return; }
            if (validation(tax_information, oBundle.getText("Tax_Information"))) { return; }
            if (validateNumber(tax_percentage, oBundle.getText("Tax_Percentage"))) { return; }

            if(city == "Select City"){
                sap.m.MessageBox.error(oBundle.getText("Please_Select_City")); return;
            }
            
            let supplier_number = "";
            let supplier_name = "";
            let oTokenList = suppliesWSDB.getTokens();
            for (var j = 0; j < oTokenList.length; j++) {
                if (supplier_number == "") {
                    supplier_number = oTokenList[j].getKey();
                    supplier_name = oTokenList[j].getText();
                } else {
                    supplier_number = supplier_number + "^" + oTokenList[j].getKey();
                    supplier_name = supplier_name + "^" + oTokenList[j].getText();
                }
            }

            busyDialog.open();
            var updated_date = getIndonesianTime();
            var updateItems = {
                id:obj['id'], 
                ws_group_number:ws_group_number, ws_group_name:ws_group_name, workshop_number:workshop_number, workshop_name:workshop_name, 
                email:email, address:address, city:city, supplier_number:supplier_number, supplier_name:supplier_name,
                tax_information:tax_information, tax_percentage:tax_percentage,
                updated_date:updated_date,updated_by:operatedID
            }
            Car_Workshop.update(updateItems).done(function(){
                getWorkshop();
                sap.m.MessageToast.show("Workshop Updated Successfully.");
                addHistoryTableData(workshop_number,"Update","Workshop",obj,updateItems);
                busyDialog.close();
                oDialog.close();
            }, failure)
        }
    });
    var oDialog = new sap.m.Dialog({ contentWidth: "100%", contentHeight: "50%", draggable: true, resizable: true,
        title: oBundle.getText("Add_4W_Workshop"),
        content: [oForm2w],
        buttons: [add4WWorkshopBtn,update4WWorkshopBtn,
			new sap.m.Button({ text: oBundle.getText("Close"), icon: "sap-icon://decline",press: function () { oDialog.close();}})
		]
    }).open();
    

    if(src == 1){
        Car_Workshop.where({master_email:emailUser}).take(1).orderByDescending("createdAt").read().done(function (results) {
            if(results.length > 0 ){
                let latestNumber = results[0]['workshop_number'];
                let numericPart = parseInt(latestNumber.slice(2));  // Extract the numeric part and convert to an integer
                let newWSNumber = numericPart + 1;          // Add 1 to the numeric part
                oIF4wWorkshop2.setValue("WS"+newWSNumber);
            }else{
                oIF4wWorkshop2.setValue("WS1001");
            }
        });
        // getWorkshopIndex(oIF4wWorkshop2);
        
    }else if(src == 2){
        add4WWorkshopBtn.setVisible(false);
        update4WWorkshopBtn.setVisible(true);
        oDialog.setTitle(`Update Workshop`);

        
        oIF4wWorkshop2.setValue(obj['workshop_number']);
        oIF4wWorkshop3.setValue(obj['workshop_name']);
        oIF4wWorkshop4.setValue(obj['email']);
        oIF4wWorkshop5.setValue(obj['address']);
        oIF4wWorkshop6.setValue(obj['city']);
        oIF4wWorkshop7.setValue(obj['supplier']);

        worshopGroupWSDB.addToken(new sap.m.Token({ key: obj['ws_group_number'], text: obj['ws_group_name'] }));

        if(nullCheckAll(obj['supplier_number'])){
            suppliesWSDB.removeAllTokens();
            var supplier_number_key = obj['supplier_number'].split("^");
            var supplier_name_text = obj['supplier_name'].split("^");
            for (var i = 0; i < supplier_number_key.length; i++) {
                suppliesWSDB.addToken(new sap.m.Token({ key: supplier_number_key[i], text: supplier_name_text[i] }));
            }
        }else{
            suppliesWSDB.removeAllTokens();
        }
        
        if(obj["tax_information"] == 'Yes'){
            oIF4wWorkshop11.setEnabled(true)
            oIF4wWorkshop11.setValue(obj['tax_percentage']);
        }else{

            oIF4wWorkshop11.setValue('0')
            oIF4wWorkshop11.setEnabled(false)
        }

        oIF4wWorkshop10.setValue(obj['tax_information']);

    }else if(src == 3){

        add4WWorkshopBtn.setVisible(false);
        update4WWorkshopBtn.setVisible(false);
        oDialog.setTitle(`View Workshop`);

        oIF4wWorkshop2.setValue(obj['workshop_number']);
        oIF4wWorkshop3.setValue(obj['workshop_name']);
        oIF4wWorkshop4.setValue(obj['email']);
        oIF4wWorkshop5.setValue(obj['address']);
        oIF4wWorkshop6.setValue(obj['city']);
        oIF4wWorkshop10.setValue(obj['tax_information']);
        oIF4wWorkshop11.setValue(obj['tax_percentage']);
        
        worshopGroupWSDB.addToken(new sap.m.Token({ key: obj['ws_group_number'], text: obj['ws_group_name'] }));

        if(nullCheckAll(obj['supplier_number'])){
            suppliesWSDB.removeAllTokens();
            var supplier_number_key = obj['supplier_number'].split("^");
            var supplier_name_text = obj['supplier_name'].split("^");
            for (var i = 0; i < supplier_number_key.length; i++) {
                suppliesWSDB.addToken(new sap.m.Token({ key: supplier_number_key[i], text: supplier_name_text[i] }));
            }
        }else{
            suppliesWSDB.removeAllTokens();
        }

        
        worshopGroupWSDB.setEnabled(false)
        suppliesWSDB.setEnabled(false)
        oIF4wWorkshop1.setEnabled(false);
        oIF4wWorkshop2.setEnabled(false);
        oIF4wWorkshop3.setEnabled(false);
        oIF4wWorkshop4.setEnabled(false);
        oIF4wWorkshop5.setEnabled(false);
        oIF4wWorkshop6.setEnabled(false);
        // oIF4wWorkshop7.setEnabled(false);
        // oIF4wWorkshop8.setEnabled(false);
        // oIF4wWorkshop9.setEnabled(false);
        oIF4wWorkshop10.setEnabled(false);
        oIF4wWorkshop11.setEnabled(false);
    };

    
}

function addUpdate4WWSMaster(src,obj){


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

    let oIF4WWSMaster1 = new sap.m.Input({enabled:false}); 
    let oIF4WWSMaster2 = new sap.m.Input({}); 


    let oFormWMaster =  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("Workshop_Group_Number")),fields: [oIF4WWSMaster1]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Workshop_Group_Name")),fields: [oIF4WWSMaster2]}),
                    
                ]
            }),
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({
                        fields: [oTableAssignVehicle]
                    }),
                ]
            })
        ]
    })
    
    var add4WWSMasterBtn = new sap.m.Button({ 
        text: oBundle.getText("Add"), 
        icon: "sap-icon://add",
        press: function(){
            let ws_group_number = oIF4WWSMaster1.getValue();
            let ws_group_name = oIF4WWSMaster2.getValue();

            //Validation            
            if (validation(ws_group_number, oBundle.getText("Workshop_Group_Number"))) { return; }
            if (validation(ws_group_name, oBundle.getText("Workshop_Group_Name"))) { return; }
           


            busyDialog.open();
            var current_date = getIndonesianTime();
            let insertItems = {
                master_email:emailUser,
                ws_group_number:ws_group_number, 
                ws_group_name:ws_group_name, 
                created_date:current_date, 
                created_by:operatedID,
                assign_vehicle:""
            };

            Car_Workshop_Master.insert(insertItems).done(function(){
                getWorkshopMaster();
                sap.m.MessageToast.show("Workshop Group Added Successfully.");
                addHistoryTableData(insertItems['ws_group_number'],"Insert","Workshop Group");
                busyDialog.close();
                oDialog.close();
            }, failure)

        }
    });
    var update4WWSMasterBtn = new sap.m.Button({ 
        visible:false,
        text: oBundle.getText("Update"), 
        icon: "sap-icon://edit",
        press: function(){
            let ws_group_number = oIF4WWSMaster1.getValue();
            let ws_group_name = oIF4WWSMaster2.getValue();

            //Validation            
            if (validation(ws_group_number, oBundle.getText("Workshop_Group_Number"))) { return; }
            if (validation(ws_group_name, oBundle.getText("Workshop_Group_Name"))) { return; }
           
            // var oldAssigned_vehicle = obj['assign_vehicle'];

            let assignVehicle = "";
            var objAssignVehicle = oModelAssignVehicle.getProperty("/modelData");
            var assignVehicleCount = oTableAssignVehicle.getBinding("rows").getLength();

            if (assignVehicleCount == vehicle4WJSONData.length) {
                assignVehicle = "1";
            } else {
                for (var i = 0; i < assignVehicleCount; i++) {
                    if (vehicle4WArray.indexOf(objAssignVehicle[i]['Vehicle_Number']) > -1) {
                        assignVehicle = assignVehicle + objAssignVehicle[i]['Vehicle_Number'] + "^";
                    }
                }
                assignVehicle = assignVehicle.slice(0, -1);
            }



            // return
            busyDialog.open();
            var updated_date = getIndonesianTime();
            let insertItems = {
                id:obj['id'],
                ws_group_number:ws_group_number, 
                ws_group_name:ws_group_name,  
                assign_vehicle:assignVehicle,
                updated_date:updated_date, 
                updated_by:operatedID
            };


            updateWOrkshopMaster(insertItems,oDialog,obj);

            // Car_Workshop_Master.update(insertItems).done(function(){
            //     getWorkshopMaster();

            //     var blankAssignVehicle = [];
            //     oModelAssignVehicle.setData({ modelData: blankAssignVehicle });
            //     oTableAssignVehicle.setModel(oModelAssignVehicle);
            //     oTableAssignVehicle.bindRows("/modelData");

            //     sap.m.MessageToast.show("Workshop Group Updated Successfully.");
            //     busyDialog.close();
            //     oDialog.close();
            // }, failure)

        }
    });

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

    if(src == 1){
        newToolbarAssign.setVisible(false);
        oTableAssignVehicle.setVisible(false);
        oDialog.setContentWidth("35%");
        oDialog.setContentHeight("20%");

        Car_Workshop_Master.where({master_email:emailUser}).take(1).orderByDescending("createdAt").read().done(function (results) {
            if(results.length > 0){
                let latestNumber = results[0]['ws_group_number'];
                let numericPart = parseInt(latestNumber.slice(3));  // Extract the numeric part and convert to an integer
                let newWSNumber = numericPart + 1;          // Add 1 to the numeric part
                oIF4WWSMaster1.setValue("WSG"+newWSNumber);
            }else{
                oIF4WWSMaster1.setValue("WSG1001");
            }    
        });

    }else if(src == 2){
        aDataAssignVehicle = [];
        newToolbarAssign.setVisible(true);
        oTableAssignVehicle.setVisible(true);
        // oDialog.setContentWidth("60%");
        // oDialog.setContentHeight("80%");


        add4WWSMasterBtn.setVisible(false);
        update4WWSMasterBtn.setVisible(true);
        oDialog.setTitle(oBundle.getText("Update_4W_Workshop_Group"));

        oIF4WWSMaster1.setValue(obj['ws_group_number']);
        oIF4WWSMaster2.setValue(obj['ws_group_name']);

        var assign_vehicle = obj['assign_vehicle'];
        if (assign_vehicle == null) { assign_vehicle = ""; }
        var assign_vehicle = assign_vehicle.split("^");

        if (assign_vehicle != "") {
        for (var i = 0; i < assign_vehicle.length; i++) {

            if (assign_vehicle[i] == "1") {
                for(var j=0;j< vehicle4WArray.length; j++){
                    aDataAssignVehicle.push({ Vehicle_Number: vehicle4WArray[j]});
                }
            } else {
                aDataAssignVehicle.push({ Vehicle_Number: assign_vehicle[i] });
            }
        }
        }

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

    }else if(src == 3){
        aDataAssignVehicle = [];
        add4WWSMasterBtn.setVisible(false);
        update4WWSMasterBtn.setVisible(false);
        newToolbarAssign.setVisible(false);
        oDialog.setTitle(oBundle.getText("View_4W_Workshop_Group"));

        oIF4WWSMaster1.setValue(obj['ws_group_number']);
        oIF4WWSMaster2.setValue(obj['ws_group_name']);

        oIF4WWSMaster1.setEnabled(false);
        oIF4WWSMaster2.setEnabled(false);

        var assign_vehicle = obj['assign_vehicle'];
        if (assign_vehicle == null) { assign_vehicle = ""; }
        var assign_vehicle = assign_vehicle.split("^");

        if (assign_vehicle != "") {
        for (var i = 0; i < assign_vehicle.length; i++) {

            if (assign_vehicle[i] == "1") {
                for(var j=0;j< vehicle4WArray.length; j++){
                    aDataAssignVehicle.push({ Vehicle_Number: vehicle4WArray[j]});
                }
            } else {
                aDataAssignVehicle.push({ Vehicle_Number: assign_vehicle[i] });
            }
        }
        }

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

};


//Get Workshop
var workshop4WJSONData = [];
function getWorkshop(){

    oTable4WWorkshop.setBusy(true);
    Car_Workshop.where({master_email:emailUser}).take(1000).orderByDescending("createdAt").read().done(function (results) {
        
        workshop4WJSONData = results;            
        
        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        oTable4WWorkshop.setModel(oModel);
        oTable4WWorkshop.bindItems({ path: "/modelData", template : workshop4WTemplate });
        
        oTable4WWorkshop.setBusy(false);

    })
}

//Get Workshop Master
var workshopmaster4WJSONData = [];
function getWorkshopMaster(){

    oTable4WWSMaster.setBusy(true);
    Car_Workshop_Master.where({master_email:emailUser}).take(1000).orderByDescending("createdAt").read().done(function (results) {

        let filterWSM = results.filter(function(a,b){ 
            return a.ws_group_number == oxmaint_ws_group_number
        });

        if(filterWSM.length > 0){
            sessionStorage.setItem("oxmaint_assign_vehicle",filterWSM[0]['assign_vehicle'])
        }
        workshopmaster4WJSONData = results;            
        
        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        oTable4WWSMaster.setModel(oModel);
        oTable4WWSMaster.bindItems({ path: "/modelData", template : wsMaster4WTemplate });
        
        oTable4WWSMaster.setBusy(false);


    })
}

async function getWorkshopMasterLoad() {
    return new Promise((resolve, reject) => {
        oTable4WWSMaster.setBusy(true);

        Car_Workshop_Master.where({ master_email: emailUser }).take(1000).orderByDescending("createdAt").read().done(function (results) {
            let filterWSM = results.filter(function (a, b) {
                return a.ws_group_number == oxmaint_ws_group_number;
            });

            if (filterWSM.length > 0) {
                sessionStorage.setItem("oxmaint_assign_vehicle", filterWSM[0]['assign_vehicle']);
                hvi_assign_vehicle = filterWSM[0]['assign_vehicle']||"";
            }

            workshopmaster4WJSONData = results;

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

            oTable4WWSMaster.setBusy(false);

            resolve(); // Resolve the promise once data is loaded
        })
    });
}


var workshopMain = new sap.uxap.ObjectPageLayout({ headerContentPinnable: true, 
    preserveHeaderStateOnScroll: true, useIconTabBar: true, toggleHeaderOnTitleClick: false,showHeaderContent:false,
    // headerContent:[ customDateWOD1, customDateWOD2, customDateWODButton],
    toggleHeaderOnTitleClick:false,
    sections: [
        new sap.uxap.ObjectPageSection({id:"GW1", showTitle: true, title: oBundle.getText("Workshop"),
            subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTable4WWorkshop]})
        }),
        new sap.uxap.ObjectPageSection({id:"GW2", showTitle: true, title: oBundle.getText("Workshop_Group"),
            subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTable4WWSMaster]})
        }),
        
    ],
    navigate: function (event) {
        // var mID = event.getParameter('section').getId();
        // var buttonSegmentNumber = oSegmentedGroupWorkorderDashboard.getSelectedButton();
        // // console.log(mID)
        // // console.log(buttonSegmentNumber)
        // // console.log(mainDashboard)
        // if(buttonSegmentNumber == "WODsegment1" && mainDashboard ){
        //     funWODashboard(new Date(getCurrentDate()),new Date(getCurrentDate()));
        //     console.log("Dashboard Funtion")
        // }

    }
});

var workshopPage4W = new sap.m.Page("workshop_page_4w", {
    title:oBundle.getText("Create_4W_Workshop"),
    showHeader:true,
    enableScrolling:true,
    content : [workshopMain] 
}); 




function selectSupplierWS(src,input){
    var oSelectDialog = new sap.m.SelectDialog({ contentWidth: "50%", draggable: true,
        resizable: true, rememberSelections: true, multiSelect: true,
        title: oBundle.getText("Select_Supplier"),
        noDataText: oBundle.getText("No_Data"),
        liveChange: function (oEvent) {
            sSearchValue = oEvent.getParameter("value"),
            oBinding = oEvent.getParameter("itemsBinding");
            if (oBinding) {
                var oFilters = [
                    new sap.ui.model.Filter("supplier_number", sap.ui.model.FilterOperator.Contains, sSearchValue),
                    new sap.ui.model.Filter("supplier_name", sap.ui.model.FilterOperator.Contains, sSearchValue),                    
                ];
                var filterObj = new sap.ui.model.Filter(oFilters, false);
                oBinding.filter(filterObj);
            } else {
                oBinding.filter([]);
            }
        },
        confirm: function (oEvent) {
            
            if(src == 2){
                input.removeAllTokens();
            }
            var tokenList = input.getTokens();
            var aContexts = oEvent.getParameter("selectedContexts");
            if (aContexts && aContexts.length) {
                aContexts.map(function (oContext) { 
                    let supplier_number =  oContext.getObject()['supplier_number'];
                    let supplier_name =  oContext.getObject()['supplier_name'];

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

                });
            }
        }
    });

    var oItemTemplate = new sap.m.StandardListItem({title: "{supplier_number}",
        description: "{supplier_name}",type: "Active"
    })

    let tokenList = input.getTokens();
    let resultTokenList = supplier4WJSONData.filter(function (obj, index) {
        for (var j = 0; j < tokenList.length; j++) {
            if (tokenList[j].getKey() == obj.supplier_number) { return false; }
        }
        return true;
    });



    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ modelData: resultTokenList });
    oSelectDialog.setModel(oModel); 
    oSelectDialog.bindAggregation("items", "/modelData", oItemTemplate);
    oSelectDialog.open();    
    
    oSelectDialog._getOkButton().setText(oBundle.getText("Select"));
    oSelectDialog._getCancelButton().setText(oBundle.getText("Cancel"));

    if(src == 2){
        oSelectDialog.setMultiSelect(false);
    }else{
        oSelectDialog.setMultiSelect(true);
    }
}