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

var oTable4WGrabTeam = new sap.m.Table({
    growing: true,
    mode: "None", // or "SingleSelectMaster" if you need selection
    noDataText: oBundle.getText("No_Data"),
    growingTriggerText: oBundle.getText("More"),
    growingThreshold: 25,
    growingScrollToLoad: false,
    sticky: [sap.m.Sticky.ColumnHeaders, sap.m.Sticky.HeaderToolbar, sap.m.Sticky.InfoToolbar],
    columns: [
        new sap.m.Column({
            width: "100px",
            header: new sap.m.Label({ text: oBundle.getText("Action"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Phone", demandPopin: true, popinDisplay: "Inline"
        }),
        new sap.m.Column({
            width: "80px", hAlign: "Center",
            header: new sap.m.Label({ text: "", design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Tablet", demandPopin: true, popinDisplay: "Inline"
        }),
        new sap.m.Column({
            header: new sap.m.Label({ text: oBundle.getText("Name"), design: sap.m.LabelDesign.Bold, wrapping: true }),
            minScreenWidth: "Phone", demandPopin: true, popinDisplay: "Inline"
        }),
        new sap.m.Column({
            header: new sap.m.Label({ text: oBundle.getText("User_ID"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Phone", demandPopin: true, popinDisplay: "Inline"
        }),
        new sap.m.Column({
            header: new sap.m.Label({ text: oBundle.getText("Email"), design: sap.m.LabelDesign.Bold, wrapping: true }),
            minScreenWidth: "Tablet", demandPopin: true, popinDisplay: "Inline"
        }),
        new sap.m.Column({
            width: "100px",
            header: new sap.m.Label({ text: oBundle.getText("Status"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Tablet", demandPopin: true, popinDisplay: "Inline"
        })
    ]
});

oTable4WGrabTeam.setHeaderToolbar(new sap.m.Toolbar({
    content: [
        new sap.m.Button({ 
            id:"createTeamID",
            text: oBundle.getText("Add_Team_Member"), 
            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_user_account') != -1)){
                    // if(locationMasterJSONArray.length > 0){
                        addUpdate4WUser(1);//Create
                    // }else{
                    //     sap.m.MessageBox.warning("Please wait while the Location Data is loading.");
                    // }

                }else{
                    sap.m.MessageToast.show("Create Access not provided.");
                }
            } 
        }),
        new sap.m.ToolbarSpacer(),
        new sap.m.SearchField({
            placeholder: oBundle.getText("Search"),
            width: "300px",
            liveChange: function (event) {
                var oBinding = oTable4WGrabTeam.getBinding("items");
                var searchStr = this.getValue();
                if (oBinding) {
                    var oFilters = [
                        new sap.ui.model.Filter("role", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("user_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("user_id", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("email", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("workshop_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("workshop_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("approval_amount", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("approval_level", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("city", sap.ui.model.FilterOperator.Contains, searchStr),
                    ];
                    var filterObj = new sap.ui.model.Filter(oFilters, false);
                    oBinding.filter(filterObj);
                } else {
                    oBinding.filter([]);
                }
            }
    
        }),
        // new sap.m.MenuButton({
        //     icon: "sap-icon://menu",
        //     menu: new sap.m.Menu({
        //         itemSelected: function(oEvent) {
        //             var key = oEvent.getParameter("item").getKey();
        //             if(key == "1"){
                    
        //                 if(subscription_status != 'Inactive' && subscription_status != 'Cancelled'){
        //                     teamExcelExport();
        //                 }else{
        //                     sap.m.MessageBox.error(oBundle.getText("Your_subscription_is_inactive_please_buy_subscription"));
        //                     return;
        //                 }
        //             }
        //         },
        //         items: [
        //             new sap.m.MenuItem({key: "1",text: oBundle.getText("Excel_Export"),
        //             icon: "sap-icon://excel-attachment",
        //             })         
        //         ]
        //     })
        // })
    ]
}));
var team4WGrabTemplate = 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 obj1 = model.getProperty(path);
                displayMenuGrabTeam(event, obj1);
            }
        }),
        new sap.f.Avatar({ src: "{image}",displaySize: "S",displayShape: "Circle",imageFitType: "Cover",
        initials: { path: "name",
            formatter: function (value) {
                if(value!=null){
                    var arr = value.split(" ");
                    var secW = "";
                    if(arr[1]!=null){
                        secW = arr[1].charAt(0);
                    }
                    return arr[0].charAt(0)+secW;
                }
            }
        }}),
        new sap.m.VBox({
            items:[ new sap.tnt.InfoLabel({colorScheme:6,
                text: { path: "role",
                    formatter: function (role) {
                        if(role==oBundle.getText("Administrator")){
                            return oBundle.getText("Administrator");
                        }else if(role==oBundle.getText("Account_Payable_Team")){
                            return oBundle.getText("Account_Payable_Team");
                        }else if(role==oBundle.getText("Driver")){
                            return oBundle.getText("Driver");
                        }else if(role==oBundle.getText("Maintenance_Team")){
                            return oBundle.getText("Maintenance_Team");
                        }else if(role==oBundle.getText("Quality_Team")){
                            return oBundle.getText("Quality_Team");
                        }else if(role==oBundle.getText("Supplier")){
                            return oBundle.getText("Supplier");
                        }else if(role==oBundle.getText("Workshop")){
                            return oBundle.getText("Workshop");
                        }else if(role==oBundle.getText("Workshop_Group_Admin")){
                            return oBundle.getText("Workshop_Group_Admin");
                        }else if(role=="4"){
                            return oBundle.getText("Sub_Admin");
                        }  
                    }
                }}),
                new sap.m.Label({wrapping:true,text: "{user_name}"}).addStyleClass("sapUiTinyMarginTop"),
            ]}).addStyleClass("sapUiTinyMargin"),
        new sap.m.Label({ text: "{user_id}"}),
        new sap.m.Label({ text: "{email}"}),
        new sap.tnt.InfoLabel({colorScheme:6,
            text: { path: "status",
                formatter: function (status) {
                    if(status=="Inactive"){
                        this.setColorScheme(3);
                        return oBundle.getText("Inactive");
                    }else {
                        this.setColorScheme(8);
                        return oBundle.getText("Active");
                    }
                }
            }}),
        new sap.tnt.InfoLabel({colorScheme:6,
            text: { path: "active",
                formatter: function (active) {
                    if(active=="1"){
                        this.setColorScheme(3);
                        return oBundle.getText("Inactive");
                    }else {
                        this.setColorScheme(8);
                        return oBundle.getText("Active");
                    }
                }
            }}),
    ],
    highlight: {
        path: "user_block",
        formatter: function (block) {
            if (block != null) {
                if (block == "Yes" || block == "2") {
                    return "Error";
                } else {
                    return "Success";
                }
            }
            return "None";
        }
    }
});


//Add Update Team 4W
function addUpdate4WUser(src,obj){

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


    // var o4WteamField1 = new sap.m.Input({placeholder:"Pick From Workshop Master"});
    // var o4WteamField2 = new sap.m.Input({placeholder:"Pick From Workshop"});
    var o4WteamField3 = new sap.m.Input({placeholder:"Auto from workshop",enabled:false});
    var o4WteamField4 = new sap.m.Input({});
    var o4WteamField5 = new sap.m.Input({});
    // var o4WteamField6 = new sap.m.Input({placeholder:"Minimum 12 alphanumeric characters",
    //     liveChange:function(){
    //         console.log("adsdasds")
    //     }
    // });
    var o4WteamField6 = new sap.m.Input({placeholder:"Minimum 12 alphanumeric characters", type:"Password", value: "", width: "100%",
        liveChange : function(event) {
            var password = this.getValue();
            var specialCharRegex = /[!@#$%^&*(),.?":{}|<>]/; // Regex to check for special symbols
            var capitalLetterRegex = /[A-Z]/; // Regex to check for at least one capital letter

            if (password.length < 12) {
                this.setValueStateText(oBundle.getText("Minimum_12_alphanumeric_character"));
                this.setValueState(sap.ui.core.ValueState.Error);  // if the field is empty after change, it will go red
            }else if (!specialCharRegex.test(password)) {
                this.setValueStateText(oBundle.getText("Password_must_contain_at_least_one_special_symbol"));
                this.setValueState(sap.ui.core.ValueState.Error);
            } else if (!capitalLetterRegex.test(password)) {
                this.setValueStateText(oBundle.getText("Password_must_contain_at_least_one_capital_letter"));
                this.setValueState(sap.ui.core.ValueState.Error);
            }else {
                this.setValueStateText("");
                this.setValueState(sap.ui.core.ValueState.None); }
        } });
    var o4WteamField7 = new sap.m.ComboBox({
        selectedKey:"0",
        width:"100%",
        items:[
            new sap.ui.core.ListItem({key:"0",text:oBundle.getText("Select_Role")}),
            new sap.ui.core.ListItem({key:"1",text:oBundle.getText("Administrator")}),
            new sap.ui.core.ListItem({key:"2",text:oBundle.getText("Account_Payable_Team")}),
            new sap.ui.core.ListItem({key:"3",text:oBundle.getText("Driver")}),
            new sap.ui.core.ListItem({key:"4",text:oBundle.getText("Maintenance_Team")}),
            new sap.ui.core.ListItem({key:"5",text:oBundle.getText("Quality_Team")}),
            new sap.ui.core.ListItem({key:"6",text:oBundle.getText("Supplier")}),
            new sap.ui.core.ListItem({key:"7",text:oBundle.getText("Workshop")}),
            new sap.ui.core.ListItem({key:"8",text:oBundle.getText("Workshop_Group_Admin")}),
        ],
        change: function (oEvent) {
            let enteredValue = oEvent.getParameter("value");
            let isValid = o4WteamField7.getItems().some(item => item.getText() === enteredValue);
    
            if (!isValid) {
                sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list_role"));
                o4WteamField7.setSelectedKey("0")
            }

            if(enteredValue == "Supplier"){
                oTeamForm4w.getFormContainers()[1].getFormElements()[3].setVisible(true);
            }else{
                o4WteamField13.removeAllTokens();
                oTeamForm4w.getFormContainers()[1].getFormElements()[3].setVisible(false);

            }
            let rolePermissions = {
                "Supplier": [
                    "download_report", "delete_work_order_notification", "view_work_order_notification", "supplier_invoice" 
                    // "view_work_order",  "create_invoice_work_order", "modify_invoice_work_order"
                ],
                "Driver": [
                    "create_appointment_inspection", "modify_appointment_inspection"
                ],
                "Account Payable Team": [
                    "download_report", "delete_work_order_notification","view_work_order_notification", 
                    "view_work_order", "create_mark_as_receipt_work_order", "modify_mark_as_receipt_work_order", 
                    "create_mark_as_receipt_work_order_using_bulk_upload"
                ],
                "Quality Team": [
                    "create_inspection_transaction", "modify_inspection_transaction","view_inspection_transaction", 
                    "delete_inspection_transaction", "view_work_order"
                ],
                "Maintenance Team": [
                    "download_report", "delete_work_order_notification", 
                    "view_work_order_notification", "view_work_order", 
                    "assign_vehicle", "modify_assign_vehicle", 
                    "view_assign_vehicle", "modify_invoice_work_order",  
                    "create_work_order", "modify_work_order", "cancel_work_order", "view_work_order"
                ],
                "Workshop": [
                    "create_inspection_transaction", "modify_inspection_transaction", 
                    "view_inspection_transaction", "delete_inspection_transaction", 
                    "delete_work_order_notification", "view_work_order_notification", 
                    "create_work_order", "modify_work_order", "cancel_work_order", "view_work_order", 
                    "create_invoice_work_order", "modify_invoice_work_order",'open_invoice_work_order'
                ],
                "Workshop Group Admin": [
                    "create_inspection_transaction", "modify_inspection_transaction", 
                    "view_inspection_transaction", "delete_inspection_transaction", 
                    "delete_work_order_notification", "view_work_order_notification", 
                    "create_work_order", "modify_work_order", "cancel_work_order", "view_work_order", 
                    "create_invoice_work_order", "modify_invoice_work_order",'open_invoice_work_order'
                ]
            };
            
    
            let selectedRole = o4WteamField7.getValue();
            let permissions = rolePermissions[selectedRole] || [];
    
            // Update userAccessTeam selected items
            let allItems = userAccessTeam.getItems();
           

            if(selectedRole == "Administrator"){
                var itemsToSelect = allItems.filter(function (item) {
                    return !(["00","000"].includes(item.getKey()));
                });
            }else{
                var itemsToSelect = allItems.filter(function (item) {
                    return permissions.includes(item.getKey());
                });
            }
    
            userAccessTeam.setSelectedItems(itemsToSelect);
            // checkMandatoryLocation()
            

        }
    
    });
    var o4WteamField8 = new sap.m.Input({});
    var o4WteamField9 = cityCB.clone();
    o4WteamField9.addEventDelegate({onAfterRendering: function(e) {o4WteamField9.$().find("input").attr("readonly", true);}});
    o4WteamField9.attachChange(function (oEvent) {
        let enteredValue = oEvent.getParameter("value");
        let isValid = o4WteamField9.getItems().some(item => item.getText() === enteredValue);

        if (!isValid) {
            sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list_city"));
            o4WteamField9.setValue("BANDUNG");
        }
    });
    var o4WteamField10 = 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 = o4WteamField10.getItems().some(item => item.getText() === enteredValue);
    
            if (!isValid) {
                sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list_for_Status"));
                o4WteamField10.setValue(oBundle.getText("Active"));
            }
        }
    }).addEventDelegate({onAfterRendering: function(e) {o4WteamField10.$().find("input").attr("readonly", true);}});
    
    var o4WteamField11 = new sap.m.Select({
        items: {
            path: "/levels", // Path in the model
            template: new sap.ui.core.Item({
                key: "{approval_level_id}",
                text: "{approval_level_id}"
            })
        },
        change: function () {
            let selectedItemValue = o4WteamField11.getSelectedKey();
            let filterApprovallevel = approval4WJSONData.filter(function (val) {
                return val.approval_level_id == selectedItemValue;
            });
    
            if (filterApprovallevel.length > 0) {
                o4WteamField12.setValue(filterApprovallevel[0]["approval_amount"]);
            }
        }
    });

    var o4WteamField12 = new sap.m.Input({enabled:false});
    var o4WteamField13 = new sap.m.MultiInput({ showSuggestion: true, fieldWidth: "100%",showValueHelp: true,
        valueHelpOnly: true,
        valueHelpRequest: function () { selectSupplierWS(2,o4WteamField13); }
    });
    var o4WteamField14 = new sap.m.Select({
        placeholder: "Select Location",
        // change: function () {
        //     // if(slotFilterByLocation.getSelectedKey() != 'Select Location'){
        //     //     getSlotMaster(slotFilterByLocation.getSelectedKey());
        //     // }
        // }
    });


   



    // var data = []
    let userAccessData  = {
            shift:[
                {key: "000", Description: oBundle.getText("Remove_All")},
                {key: "00", Description: oBundle.getText("Select_All")},
                // {key: "dashboard", Description: oBundle.getText("Dashboard")},
                {key: "dashboard", Description: oBundle.getText("Dashboard")},
                {key: "download_report", Description: oBundle.getText("Download_report")},
                {key: "create_user_account", Description: oBundle.getText("Create_user_account")},
                {key: "modify_user_account", Description: oBundle.getText("Modify_user_account")},
                {key: "deactive_user_account", Description: oBundle.getText("Deactive_user_account")},
                // {key: "Reset password", Description: oBundle.getText("Reset password")},
                {key: "view_user_account", Description: oBundle.getText("View_user_account")},
                // {key: "Create approval level", Description: oBundle.getText("Create approval level")},
                {key: "modify_approval_level", Description: oBundle.getText("Modify_approval_level")},
                {key: "view_approval_level", Description: oBundle.getText("View_approval_level")},
                // {key: "Delete approval level", Description: oBundle.getText("Delete approval level")},

                //Workshop Access
                {key: "view_workshop", Description: oBundle.getText("View_workshop")},
                {key: "create_workshop", Description: oBundle.getText("Create_workshop")},
                {key: "modify_workshop", Description: oBundle.getText("Modify_workshop")},
                {key: "delete_workshop", Description: oBundle.getText("Delete_workshop")},
                
                //Workshop Group Access
                {key: "view_workshop_group", Description: oBundle.getText("View_workshop_group")},
                {key: "create_workshop_group", Description: oBundle.getText("Create_workshop_group")},
                {key: "modify_workshop_group", Description: oBundle.getText("Modify_workshop_group")},
                {key: "delete_workshop_group", Description: oBundle.getText("Delete_workshop_group")},

                //Supplier
                {key: "view_supplier", Description: oBundle.getText("View_supplier")},
                {key: "create_supplier", Description: oBundle.getText("Create_supplier")},
                {key: "modify_supplier", Description: oBundle.getText("Modify_supplier")},
                {key: "delete_supplier", Description: oBundle.getText("Delete_supplier")},

                //Schedule
                // {key: "view_schedule", Description: oBundle.getText("View schedule")},
                {key: "create_schedule", Description: oBundle.getText("Create_schedule")},
                {key: "modify_schedule", Description: oBundle.getText("Modify_schedule")},
                {key: "delete_schedule", Description: oBundle.getText("Delete_schedule")},
                // {key: "Add role and permission", Description: oBundle.getText("Add role and permission")},
                // {key: "Modify role and permission", Description: oBundle.getText("Modify role and permission")},
                // {key: "Delete role and permission", Description: oBundle.getText("Delete role and permission")},
                // {key: "View role and permission", Description: oBundle.getText("View role and permission")},
                {key: "assign_vehicle", Description: oBundle.getText("Assign_vehicle")},
                {key: "modify_assign_vehicle", Description: oBundle.getText("Modify_assign_vehicle")},
                {key: "view_assign_vehicle", Description: oBundle.getText("View_assign_vehicle")},
                // {key: "Create inspection location", Description: oBundle.getText("Create inspection location")},
                // {key: "Modify inspection location", Description: oBundle.getText("Modify inspection location")},
                // {key: "Delete inspection location", Description: oBundle.getText("Delete inspection location")},
                // {key: "View inspection location", Description: oBundle.getText("View inspection location")},
                {key: "view_inspection_form", Description: oBundle.getText("View_Inspection_form")},
                {key: "create_inspection_form", Description: oBundle.getText("Create_Inspection_form")},
                {key: "modify_inspection_form", Description: oBundle.getText("Modify_Inspection_form")},
                {key: "delete_inspection_form", Description: oBundle.getText("Delete_Inspection_form")},
                // {key: "Create inspection scheduling", Description: oBundle.getText("Create inspection scheduling")},
                // {key: "Modify inspection scheduling", Description: oBundle.getText("Modify inspection scheduling")},
                // {key: "Delete inspection scheduling", Description: oBundle.getText("Delete inspection scheduling")},
                // {key: "View inspection scheduling", Description: oBundle.getText("View inspection scheduling")},
                {key: "create_inspection_transaction", Description: oBundle.getText("Create_Inspection_transaction")},
                {key: "view_inspection_transaction", Description: oBundle.getText("View_Inspection_transaction")},
                {key: "archive_inspection_transaction", Description: oBundle.getText("Archive_Inspection_transaction")},
                // {key: "Modify inspection transaction", Description: oBundle.getText("Modify inspection transaction")},
                // {key: "closed_inspection_transaction", Description: oBundle.getText("Closed Inspection transaction")},
                // {key: "Create inspection notification", Description: oBundle.getText("Create inspection notification")},
                // {key: "Modify inspection notification", Description: oBundle.getText("Modify inspection notification")},
                // {key: "Delete inspection notification", Description: oBundle.getText("Delete inspection notification")},
                // {key: "View inspection notification", Description: oBundle.getText("View inspection notification")},
                // {key: "Create work order notification", Description: oBundle.getText("Create work order notification")},
                // {key: "Modify work order notification", Description: oBundle.getText("Modify work order notification")},
                // {key: "Delete work order notification", Description: oBundle.getText("Delete work order notification")},
                // {key: "View work order notification", Description: oBundle.getText("View work order notification")},
                // {key: "Create regular maintenance schedule", Description: oBundle.getText("Create regular maintenance schedule")},
                // {key: "Modify regular maintenance schedule", Description: oBundle.getText("Modify regular maintenance schedule")},
                // {key: "Delete regular maintenance schedule", Description: oBundle.getText("Delete regular maintenance schedule")},
                // {key: "View regular maintenance schedule", Description: oBundle.getText("View regular maintenance schedule")},
               
                {key: "create_master_data_part_and_labour", Description: oBundle.getText("Create_master_data_part_and_labour")},
                {key: "modify_master_data_part_and_labour", Description: oBundle.getText("Modify_master_data_part_and_labour")},
                {key: "delete_master_data_part_and_labour", Description: oBundle.getText("Delete_master_data_part_and_labour")},
                {key: "view_master_data_part_and_labour", Description: oBundle.getText("View_master_data_part_and_labour")},
                // {key: "Create master data part and labour using bulk upload", Description: oBundle.getText("Create master data part and labour using bulk upload")},
                
                {key: "create_work_order", Description: oBundle.getText("Create_work_order")},
                {key: "cancel_work_order", Description: oBundle.getText("Cancel_work_order")},
                {key: "modify_work_order", Description: oBundle.getText("Modify_work_order")},
                {key: "view_work_order", Description: oBundle.getText("View_work_order")},
                {key: "archive_work_order", Description: oBundle.getText("Archive_work_order")},
                
                {key: "create_invoice_work_order", Description: oBundle.getText("Create_invoice_work_order")},
                {key: "modify_invoice_work_order", Description: oBundle.getText("Modify_invoice_work_order")},
                {key: "open_invoice_work_order", Description: oBundle.getText("Open_invoice_work_order")},
                {key: "invoice_comparision_dashboard", Description: oBundle.getText("Invoice_Comparision_work_order")},
                // {key: "create_mark_as_receipt_work_order", Description: oBundle.getText("Create mark as receipt work order")},
                // {key: "modify_mark_as_receipt_work_order", Description: oBundle.getText("Modify mark as receipt work order")},
                // {key: "attach_supplier_invoice", Description: oBundle.getText("Attach_Supplier_Invoice")},
                {key: "supplier_invoice", Description: oBundle.getText("Supplier_Invoice")},
                {key: "documents", Description: oBundle.getText("Documents")},
                {key: "driver", Description: oBundle.getText("Driver")},
                {key: "holiday", Description: oBundle.getText("Holiday")},
                {key: "location", Description: oBundle.getText("Location Capacity")},
                {key: "inspection_reminder", Description: oBundle.getText("Inspection Reminder")},
                // {key: "Create mark as receipt work order using bulk upload", Description: oBundle.getText("Create mark as receipt work order using bulk upload")},
                // {key: "Create appointment inspection", Description: oBundle.getText("Create appointment inspection")},
                // {key: "Modify appointment inspection", Description: oBundle.getText("Modify appointment inspection")}
            ]
            
            };
    // }
    

    var oModelData = new sap.ui.model.json.JSONModel();
    oModelData.setData(userAccessData);

    var userAccessTeam = new sap.m.MultiComboBox({  
        width:"100%",
        items : {  
            path : "/shift",  
            template : new sap.ui.core.ListItem({ 
                key  : "{key}",   
                text : "{Description}"  
            })
        },
        selectionChange: function(event) {
    
    
        
            var selectedItems = event.getSource().getSelectedItems();
            var selectAllItem = selectedItems.find(function(item) {
                return item.getKey() === "00";
            });
            var removeAllItem = selectedItems.find(function(item) {
                return item.getKey() === "000";
            });

            if (selectAllItem) {
                event.getSource().setSelectedItems(
                    event.getSource().getItems().filter(function(item) {
                        return item.getKey() !== "00" && item.getKey() !== "000";
                    })
                );
            }
    
            if(removeAllItem){
                // Deselect all items if no "select all" item is selected
                event.getSource().removeAllSelectedItems();
            }
        }
    });
    userAccessTeam.setModel(oModelData);


    var worshopGroupTeamDB = new sap.m.MultiInput({ showSuggestion: true, fieldWidth: "100%",
        valueHelpRequest: function () { selectTeamWSGroup(worshopGroupTeamDB); },
        valueHelpOnly: true});
    var worshopTeamDB = new sap.m.MultiInput({ showSuggestion: true, fieldWidth: "100%",autocomplete:true,
        valueHelpRequest: function () { selectTeamWorkshop(1,worshopTeamDB,o4WteamField3); },
        valueHelpOnly: true,
        tokenUpdate: function (oEvent) {
            if (oEvent.getParameter("type") === "removed") {
                o4WteamField3.setValue("");
            }
        }
    });

    var o4WteamField15 = new sap.m.ComboBox({
        value:oBundle.getText("No"),
        selectedKey : "0",
        items:[    
            new sap.ui.core.ListItem({key:"1",text:oBundle.getText("Yes")}),
            new sap.ui.core.ListItem({key:"0",text:oBundle.getText("No")}),
        ],
        change: function (oEvent) {

            let enteredValue = oEvent.getParameter("value");
            let isValid = o4WteamField15.getItems().some(item => item.getText() === enteredValue);
    
            if (!isValid) {
                sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list_for_Status"));
                o4WteamField15.setValue(oBundle.getText("Active"));
            }
        }
    }).addEventDelegate({onAfterRendering: function(e) {o4WteamField15.$().find("input").attr("readonly", true);}});
    


    var oTeamForm4w =  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: oLbl.clone().setText(oBundle.getText("Workshop_Group_Name")),fields: [worshopGroupTeamDB]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Workshop_Number")),fields: [worshopTeamDB]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Workshop_Name")),fields: [o4WteamField3]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("User_Name")),fields: [o4WteamField4]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("User_ID")),fields: [o4WteamField5]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Password")),fields: [o4WteamField6]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Role")),fields: [o4WteamField7]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("User_Access")),fields: [userAccessTeam]}),
                ]
            }),
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Email")),fields: [o4WteamField8]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("City")),fields: [o4WteamField9]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Status")),fields: [o4WteamField10]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Supplier")),fields: [o4WteamField13]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Inspection Location")),fields: [o4WteamField14]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Approval_Level_ID")),fields: [o4WteamField11]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Approval_Amount")),fields: [o4WteamField12]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Workorder_Verification")),fields: [o4WteamField15]}),
                ]
            })
        ]
    });


    var add4WTeamBtn = 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 = worshopGroupTeamDB.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 = worshopTeamDB.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 = o4WteamField13.getTokens();
            
            for (var j = 0; j < supplierTokenList.length; j++) {
                if (supplier_id == "") {
                    supplier_id = supplierTokenList[j].getKey();
                    supplier_name = supplierTokenList[j].getText();
                }
            };
            
            // let workshop_number = worshopTeamDB.getValue();
            let workshop_name = o4WteamField3.getValue();
            let user_name = o4WteamField4.getValue();
            let user_id = o4WteamField5.getValue();
            let password = o4WteamField6.getValue();
            let role = o4WteamField7.getValue();
            
            let email = o4WteamField8.getValue();
            let city = o4WteamField9.getValue();
            let status = o4WteamField10.getValue();
            let approval_level = o4WteamField11.getSelectedKey();
            let approval_amount = o4WteamField12.getValue();
            var location_id = o4WteamField14.getSelectedKey();
            var location_name = o4WteamField14.getSelectedItem().getText();
            var workorder_verification = o4WteamField15.getSelectedKey();
            
            if(o4WteamField7.getSelectedKey() == "0"){
                sap.m.MessageBox.error(oBundle.getText("Select_Role"));
                return;
            }
            if(role == "Supplier"){
                if(!nullCheckAll(supplier_id)){
                    sap.m.MessageBox.error(oBundle.getText("Select_Supplier"));
                    return;
                }
            }
            if(city == "Select City"){
                sap.m.MessageBox.error(oBundle.getText("Please_Select_City")); return;
            }
            var user_access = "";
            for(var i=0;i<userAccessTeam.getSelectedItems().length;i++){
                if(i==0){
                    user_access = user_access + userAccessTeam.getSelectedItems()[i].getKey();
                }else{
                    user_access = user_access +","+ userAccessTeam.getSelectedItems()[i].getKey();
                }
            };
       
            if (validation(user_name , oBundle.getText("User_Name"))) { return; }
            if (validation(user_id , oBundle.getText("User_Id"))) { return; }

            if(location_id == 'Select Location'){
                // if(role != "Workshop"){
                    location_id = '';
                    location_name = '';
                // }else if(nullCheckAll(ws_group_name)){
                //     sap.m.MessageBox.error(oBundle.getText("Select Location"));
                //     return;
                // }
            }

            var prime_location_id = "";
            if(location_id != ''){
                prime_location_id = locationMasterJSONArray.filter(a=> a.location_id == location_id);
                if(prime_location_id.length > 0){
                    prime_location_id = prime_location_id[0]['id']
                }
            }

            const specialSymbolPattern = /[!@#$%^&*(),.?":{}|<>]/; // Special characters
            const numberPattern = /\d/; // At least one digit
            const uppercasePattern = /[A-Z]/; // At least one uppercase letter

            if (!specialSymbolPattern.test(password)) {
                 sap.m.MessageBox.error(oBundle.getText("Password_must_contain_at_least_one_special_symbol"));
                 return;
            }
            if (!numberPattern.test(password)) {
                 sap.m.MessageBox.error(oBundle.getText("Password_must_contain_at_least_one_number"));
                 return;
            }
            if (!uppercasePattern.test(password)) {
                 sap.m.MessageBox.error(oBundle.getText("Password_must_contain_at_least_one_uppercase_letter"));
                 return;
            }
            if (password.length < 12) {
                sap.m.MessageBox.error(oBundle.getText("Use_12_characters_or_more_for_Password"));
                return;
            }

            if (user_id.length < 3) {
                sap.m.MessageBox.error(oBundle.getText("User_ID_characters"));
                return;
            }


            if(user_access == ""){
                sap.m.MessageBox.error(oBundle.getText("Please_select_user_access") );
                return;
            }
            if(approval_level == 'Select Approval Level'){
                approval_level = "";
            }
            if(hasWhiteSpace(email)){
                sap.m.MessageBox.error(oBundle.getText("Email")+" "+oBundle.getText("contain_space"));
                return;
            }
            if(email!=""){
                if (regEmail.test(email) == false) {
                    sap.m.MessageBox.error(oBundle.getText("Email_Invalid"));
                    return ;
                }
            }else{
                sap.m.MessageBox.error(oBundle.getText("Enter_Valid_Email"));
                return ;
            }

            let checkcDuplicateTeam = team4WJSONData.filter(function(value,index){
                return value.user_id.toLowerCase() == user_id.toLowerCase();
            })

            if(checkcDuplicateTeam.length>0){
                sap.m.MessageBox.error(oBundle.getText("Duplicate_User_ID_detected_Please_enter_a_different_User_ID"));
                return ;
            }
            
            let checkcDuplicateEmailTeam = team4WJSONData.filter(function(value,index){
                return value.email == email;
            })

            if(checkcDuplicateEmailTeam.length>0){
                sap.m.MessageBox.error(oBundle.getText("Duplicate_Email_detected_Please_enter_a_different_Email"));
                return ;
            }
           
            busyDialog.open();
            var current_date = getIndonesianTime();
           
            let insertItems = {
                master_email:emailUser,
                ws_group_name:ws_group_name,ws_group_number:ws_group_number, workshop_number:workshop_number, workshop_name:workshop_name,
                user_name:user_name, user_id:user_id, password:password, role:role,user_access:user_access,supplier_id:supplier_id,supplier_name:supplier_name,
                email:email, city:city, status:status, approval_level:approval_level, approval_amount:approval_amount,
                created_date:current_date, created_by:operatedID,location_id:location_id,location_name:location_name,prime_location_id:prime_location_id,
                verification_flag:workorder_verification
            };

            insertFirebase(email, password, insertItems,"1",oDialog)
            // Car_User_Master.insert(insertItems).done(function () {
            //     get4WTeam();
            //     busyDialog.close();
            //     oDialog.close();
            // }, failure);
        }
    });
    var update4WTeamBtn = new sap.m.Button({ 
        visible:false,
        text: oBundle.getText("Update"), 
        icon: "sap-icon://edit",
        press: function(){
            // let ws_group_number = worshopGroupTeamDB.getTokens()[0].getKey();
            // let ws_group_name = worshopGroupTeamDB.getTokens()[0].getText();
            let ws_group_number = "";
            let ws_group_name = "";
            let ws_groupTokenList = worshopGroupTeamDB.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 = worshopTeamDB.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 = o4WteamField13.getTokens();
            
            for (var j = 0; j < supplierTokenList.length; j++) {
                if (supplier_id == "") {
                    supplier_id = supplierTokenList[j].getKey();
                    supplier_name = supplierTokenList[j].getText();
                }
            };

            
            // let workshop_number = worshopTeamDB.getValue();
            let workshop_name = o4WteamField3.getValue();
            let user_name = o4WteamField4.getValue();
            let user_id = o4WteamField5.getValue();
            // let password = o4WteamField6.getValue();
            let role = o4WteamField7.getValue();

            let email = o4WteamField8.getValue();
            let city = o4WteamField9.getValue();
            let status = o4WteamField10.getValue();
            let approval_level = o4WteamField11.getSelectedKey();
            let approval_amount = o4WteamField12.getValue();
            var location_id = o4WteamField14.getSelectedKey() || '';
            var location_name = o4WteamField14.getSelectedItem().getText() || '';
            var workorder_verification = o4WteamField15.getSelectedKey();

            var user_access = "";
            for(var i=0;i<userAccessTeam.getSelectedItems().length;i++){
                if(i==0){
                    user_access = user_access + userAccessTeam.getSelectedItems()[i].getKey();
                }else{
                    user_access = user_access +","+ userAccessTeam.getSelectedItems()[i].getKey();
                }
            };
            
            if (validation(user_name , oBundle.getText("User_Name"))) { return; }
            if (validation(user_id , oBundle.getText("User_Id"))) { return; }
         
            if (user_id.length < 3) {
                sap.m.MessageBox.error(oBundle.getText("User_ID_characters"));
                return;
            }
            if(city == "Select City"){
                sap.m.MessageBox.error(oBundle.getText("Please_Select_City")); return;
            }
            if(location_id == 'Select Location'){
                //if(role != "Workshop"){
                    location_id = '';
                    location_name = '';
                // }else if(nullCheckAll(ws_group_name)){
                //     sap.m.MessageBox.error(oBundle.getText("Select Location"));
                //     return;
                // }
            }

            var prime_location_id = "";
            if(location_id != ''){
                prime_location_id = locationMasterJSONArray.filter(a=> a.location_id == location_id);
                
                if(prime_location_id.length > 0){
                    prime_location_id = prime_location_id[0]['id']
                }
            };
            // const specialSymbolPattern = /[!@#$%^&*(),.?":{}|<>]/; // Special characters
            // const numberPattern = /\d/; // At least one digit
            // const uppercasePattern = /[A-Z]/; // At least one uppercase letter

            // if (!specialSymbolPattern.test(password)) {
            //      sap.m.MessageBox.error(oBundle.getText("Password_must_contain_at_least_one_special_symbol"));
            //      return;
            // }
            // if (!numberPattern.test(password)) {
            //      sap.m.MessageBox.error(oBundle.getText("Password_must_contain_at_least_one_number"));
            //      return;
            // }
            // if (!uppercasePattern.test(password)) {
            //      sap.m.MessageBox.error(oBundle.getText("Password_must_contain_at_least_one_uppercase_letter"));
            //      return;
            // }
            // if (password.length < 12) {
            //     sap.m.MessageBox.error(oBundle.getText("Use_12_characters_or_more_for_Password"));
            //     return;
            // }


            if(user_access == ""){
                sap.m.MessageBox.error(oBundle.getText("Please_select_user_access") ); return;
            };
            if(o4WteamField7.getSelectedText() == "Select Role"){
                sap.m.MessageBox.error(oBundle.getText("Select_Role")); return;
            };
            
            //Email Validation
            if(hasWhiteSpace(email)){
                sap.m.MessageBox.error(oBundle.getText("Email")+" "+oBundle.getText("contain_space")); return;
            };

            if(email!=""){
                if (regEmail.test(email) == false) {
                    sap.m.MessageBox.error(oBundle.getText("Email_Invalid")); return ;
                }
            }else{
                sap.m.MessageBox.error(oBundle.getText("Enter_Valid_Email")); return ;
            };       

            if(role == "Supplier"){
                if(!nullCheckAll(supplier_id)){
                    sap.m.MessageBox.error(oBundle.getText("Select_Supplier")); return;
                }
            };
            if(approval_level == 'Select Approval Level'){
                approval_level = "";
            };

            
            let checkcDuplicateEmailTeam = team4WJSONData.filter(function(value,index){
                return value.email == email && value.id != obj['id'];
            })

            if(checkcDuplicateEmailTeam.length>0){
                sap.m.MessageBox.error(oBundle.getText("Duplicate_Email_detected_Please_enter_a_different_Email"));
                return ;
            }
      
           
            busyDialog.open();
            var updated_date = getIndonesianTime();
           
            let updateItems = {
                id:obj['id'], ws_group_number:ws_group_number,ws_group_name:ws_group_name, workshop_number:workshop_number, workshop_name:workshop_name,
                user_name:user_name, user_id:user_id, role:role,user_access:user_access,supplier_id:supplier_id,supplier_name:supplier_name,
                email:email, city:city, status:status, approval_level:approval_level, approval_amount:approval_amount,//password:password,
                updated_date:updated_date, updated_by:operatedID,location_id:location_id,location_name:location_name, prime_location_id:prime_location_id,
                verification_flag:workorder_verification
            };

            // insertFirebase(email, password, updateItems,"2",oDialog)
            Car_User_Master.update(updateItems).done(function () {
                get4WTeam();
                addHistoryTableData(updateItems["user_id"],"Update","Team",obj,updateItems);
                busyDialog.close();
                oDialog.close();
            }, failure);
        }
    });


    let oDialog = new sap.m.Dialog({ contentWidth: "100%", contentHeight: "50%", draggable: true, resizable: true,
        title: oBundle.getText("Add_Team_Member"),
        content: [oTeamForm4w],
        buttons: [add4WTeamBtn,update4WTeamBtn,
			new sap.m.Button({ text: oBundle.getText("Close"), icon: "sap-icon://decline",press: function () { oDialog.close();}})
		]
    }).open();

    locationTeamData = [...locationMasterActiveJSONArray];//Active and checkpoint yes
    // locationTeamData = [...locationMasterJSONArray];
    if(locationTeamData.length < 1){
        // console.log(locationTeamData)
        locationTeamData.unshift({ location_id: "Select Location", location_name: "Select Location" });
    }
                
    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ levels: locationTeamData });
    oModel.setSizeLimit(locationTeamData.length);
    o4WteamField14.setModel(oModel);

    o4WteamField14.bindItems({
        path: "/levels", template: new sap.ui.core.Item({ key: "{location_id}", text: "{location_name}" })
    });

    if(src == 1){
        oTeamForm4w.getFormContainers()[1].getFormElements()[3].setVisible(false);
        var approvalLevelModel = new sap.ui.model.json.JSONModel();
        approvalLevelModel.setData({ levels: approval4WJSONData });
        o4WteamField11.setModel(approvalLevelModel);
    
        var newItem = new sap.ui.core.ListItem({key: "Select Approval Level", text: oBundle.getText("Select_Approval_Level") });
        o4WteamField11.insertItem(newItem, 0);
        o4WteamField11.setSelectedKey("Select Approval Level");

    }else if(src == 2){
        update4WTeamBtn.setVisible(true);
        add4WTeamBtn.setVisible(false);
        oDialog.setTitle("Update Team Member");

        if(nullCheckAll( obj['ws_group_number'])){
            worshopGroupTeamDB.addToken(new sap.m.Token({ key: obj['ws_group_number'], text: obj['ws_group_name'] }));
        }
        
        if(nullCheckAll(obj['workshop_number'])){
            worshopTeamDB.addToken(new sap.m.Token({ key: obj['workshop_number'], text: obj['workshop_number'] }));
            // worshopTeamDB.setValue(obj['workshop_number']);
            o4WteamField3.setValue(obj['workshop_name']);
        };
        o4WteamField4.setValue(obj['user_name']);
        o4WteamField5.setValue(obj['user_id']);
        o4WteamField5.setEnabled(false);
        // o4WteamField6.setValue(obj['password']);
        o4WteamField7.setValue(obj['role']);
        o4WteamField8.setValue(obj['email']);
        o4WteamField9.setValue(obj['city']);
        o4WteamField10.setValue(obj['status']);
        o4WteamField12.setValue(obj['approval_amount']);
        
        var approvalLevelModel = new sap.ui.model.json.JSONModel();
        approvalLevelModel.setData({ levels: approval4WJSONData });
        o4WteamField11.setModel(approvalLevelModel);
        
        var newItem = new sap.ui.core.ListItem({key: "Select Approval Level", text: oBundle.getText("Select_Approval_Level") });
        o4WteamField11.insertItem(newItem, 0);
        o4WteamField11.setSelectedKey(obj['approval_level']);


        if(obj['role'] == "Supplier"){
            oTeamForm4w.getFormContainers()[1].getFormElements()[3].setVisible(true);
            if(nullCheckAll(obj['supplier_id'])){
                o4WteamField13.addToken(new sap.m.Token({ key: obj['supplier_id'], text: obj['supplier_name'] }));
            }
        }else{
            oTeamForm4w.getFormContainers()[1].getFormElements()[3].setVisible(false);
        };

        let userAcc = obj['user_access'];;
        if(nullCheckAll(userAcc)){
            let array = userAcc.split(',');
            userAccessTeam.setSelectedKeys(array);

        }
        o4WteamField6.setEnabled(false);

        if(nullCheckAll(obj['location_id'])){
            o4WteamField14.setSelectedKey(obj['location_id']);
        }
        // console.log(obj)
        // console.log(nullCheckAll(obj['verification_flag']))
        o4WteamField15.setSelectedKey(
            nullCheckAll(obj['verification_flag']) ? obj['verification_flag'] : "0"
        );
        
    }else if(src == 3){
        oDialog.setTitle("View Team Member");

        if(obj['role'] == "Supplier"){
            oTeamForm4w.getFormContainers()[1].getFormElements()[3].setVisible(true);
            if(nullCheckAll(obj['supplier_id'])){
                o4WteamField13.addToken(new sap.m.Token({ key: obj['supplier_id'], text: obj['supplier_name'] }));
            }
        }
    }

    // function checkMandatoryLocation(){


    //     let ws_group_name = "";
    //     let ws_groupTokenList = worshopGroupTeamDB.getTokens();
    //     for (var j = 0; j < ws_groupTokenList.length; j++) {
    //         if (ws_group_name == "") {
    //             ws_group_name = ws_groupTokenList[j].getText();
    //         }
    //     };

    //     var role = o4WteamField7.getValue();

    //     console.log(nullCheckAll(ws_group_name))
    //     var aContainers = oTeamForm4w.getFormContainers();
    //     var aElements = aContainers[1].getFormElements();
    //     // Loop through the form elements to find the correct label
    //     for (var i = 0; i < aElements.length; i++) {
    //         var sText = aElements[i].getLabel().getText();
    //         console.log(sText)
    //         if (sText === oBundle.getText("Inspection Location")) {

    //             if(role == 'Workshop' && nullCheckAll(ws_group_name)){
    //                 aElements[i].setLabel(reqLbl.clone().setText(sText));
    //             }else{
    //                 aElements[i].setLabel(oLbl.clone().setText(sText));
    //             }
    //         }
    //     }

    // }
};


function insertFirebase(email,password,item,src,dialogue){
  
    firebase.auth().createUserWithEmailAndPassword(email, password).then(function(firebaseUser) {
 
        if(src == 1){
            Car_User_Master.insert(item).done(function () {
               get4WTeam();
               addHistoryTableData(item["user_id"],"Insert","Team");
               busyDialog.close();
               dialogue.close();
           }, failure);
        }else{ 
            Car_User_Master.update(item).done(function () {
                get4WTeam();
                addHistoryTableData(item["user_id"],"Update","Team");
                busyDialog.close();
                oDialog.close();
            }, failure);

        }
 
       }).catch(function(error) {
           var errorMessage = error.message;
           
           if(src == 1){
                Car_User_Master.insert(item).done(function () {
                    addHistoryTableData(item["user_id"],"Insert","Team");
                get4WTeam();
                busyDialog.close();
                dialogue.close();
            }, failure);
            }else{ 
                Car_User_Master.update(item).done(function () {
                    get4WTeam();
                    addHistoryTableData(item["user_id"],"Update","Team");
                    busyDialog.close();
                    oDialog.close();
                }, failure);

            }
            //   busyDialog.close();
            //   sap.m.MessageBox.error(errorMessage);
            //   var errorCode = error.code;
 });
 
}


function displayMenuGrabTeam(event,obj){

    var oMenu = new sap.m.Menu({
        items: [
            // new sap.m.MenuItem({icon: "sap-icon://employee-pane",text: oBundle.getText("Overview"),key: "0"}),
            new sap.m.MenuItem({visible:false, icon: "sap-icon://edit",text: oBundle.getText("Edit"),key: "1"}),
            // new sap.m.MenuItem({icon: "sap-icon://show",text: oBundle.getText("View_Password"),key: "3"}),
            new sap.m.MenuItem({visible:false, icon: "sap-icon://employee",text: oBundle.getText("Inactive_Team_Member"),key: "4"}),
            // new sap.m.MenuItem({icon: "sap-icon://share-2",text: oBundle.getText("Share"),key: "6"}), 
            // new sap.m.MenuItem({icon: "sap-icon://inventory",text: oBundle.getText("Assign_Vehicle"),key: "2"}),
            // new sap.m.MenuItem({icon: "sap-icon://employee",text: oBundle.getText("Block_Team_Member"),key: "4"}),
            // new sap.m.MenuItem({icon: "sap-icon://sys-cancel",text: oBundle.getText("Mark_Inactive"),key: "7"}), 
        ],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
           
            if (oItem == "1") {
                if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('modify_user_account') != -1)){
                    addUpdate4WUser(2, obj);  // update
                }else{
                    sap.m.MessageToast.show("Modify Access not provided.");
                }
            } else if (oItem == "3") { viewPassword(obj['password']);
            } else if (oItem == "4") { blockGrabTeamMember(obj);
            } else if (oItem == "5") { deleteGrabTeamMember(obj['id']);
            }else if (oItem == "6") {
                
                var name = obj['user_name'];
                var userID = obj['user_id'];
                var password = obj['password'];

                var androidLink = "https://play.google.com/store/apps/details?id=com.jrs.oxmaint";
                var iosLink = "https://apps.apple.com/us/app/maintenance-workorder-oxmaint/id1568268027";
                var portalLink = "https://oxmaint.com/portal/employee.html";

                var subject = oBundle.getText("Credentials_of_Heavy_Vehicle_Inspection");
                var message = oBundle.getText("Dear")+" "+name+", <br><br>"+
                              oBundle.getText("Below_is_your_Credentials")+"- <br>"+
                              oBundle.getText("User_ID")+" : "+userID+" <br>"+
                              oBundle.getText("Password")+" : "+password+" <br><br><br>";
                            //   oBundle.getText("Android_App_Link")+" : "+androidLink+" <br>"+
                            //   oBundle.getText("iOS_App_Link")+" : "+iosLink+" <br>"+
                            //   oBundle.getText("Web_Portal_Link")+" : "+portalLink;
                var dialogTitle = oBundle.getText("Share_Credentials_with_Team_Member");
                var layoutHeader = oBundle.getText("User")+" : "+name;
                shareDialog(subject, message,dialogTitle,layoutHeader);
            }
        }
    });

    //Modify
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('modify_user_account') != -1)){
        oMenu.getItems()[0].setVisible(true);
    };
    //Deactivate
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('deactive_user_account') != -1)){
        oMenu.getItems()[1].setVisible(true);
    };
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('delete_user_account') != -1)){
        getDeleteMenu(oMenu,"5");
    };
    if(obj['status'] == 'Active'){
        oMenu.getItems()[1].setText(oBundle.getText("Inactive_Team_Member"));
    }else{
        oMenu.getItems()[1].setText(oBundle.getText("Active_Team_Member"));
    }
    oMenu.openBy(event.getSource());
}




var team4WJSONData = [];
var tempTeam4WJSONData = [];

var skipRowTeam4w = 0;

function get4WTeam(){
    oTable4WGrabTeam.setBusy(true);
    Car_User_Master.select(
        "id",
        "createdAt",
        "updatedAt",
        "deleted",
        "ws_group_number",
        "workshop_number",
        "workshop_name",
        "user_name",
        "user_id",
        // "password",
        "role",
        "user_access",
        "email",
        "city",
        "status",
        "approval_level",
        "approval_amount",
        "created_date",
        "created_by",
        "ws_group_name",
        "updated_date",
        "updated_by",
        "master_email",
        "user_block",
        "supplier_id",
        "supplier_name",
        "location_id",
        "location_name",
        "verification_flag"
      ).where({master_email:emailUser}).skip(skipRowTeam4w).take(1000).orderByDescending("createdAt").read().done(function (results) {
        
        tempTeam4WJSONData = tempTeam4WJSONData.concat(results);

        if(results.length < 2000){
            team4WJSONData = tempTeam4WJSONData;            
            
            var oModel = new sap.ui.model.json.JSONModel();
            oModel.setData({ modelData: results });
            oTable4WGrabTeam.setModel(oModel);
            oTable4WGrabTeam.bindItems({ path: "/modelData", template : team4WGrabTemplate });
            oTable4WGrabTeam.setBusy(false);

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

            skipRowTeam4w = 0
            tempTeam4WJSONData = [];
        
        }else{
            skipRowTeam4w += 2000;
            get4WTeam();
        }
    })

}
// var oTableTeamSelectTemplate = new sap.m.ColumnListItem({
//     cells: [
//             new sap.f.Avatar({src: "{image}",displaySize: "S",displayShape: "Circle",imageFitType: "Cover"}),
//             new sap.m.Label({ text: "{user_name}" }),
//             new sap.m.Label({ text: "{user_id}" }),
//             new sap.m.Label({ text: "{email}" }),
//             new sap.m.Button({type: "Emphasized",icon: "sap-icon://action",text: oBundle.getText("Select"),
//                 press: function (event) {
//                     var model = this.getModel();
//                     var path = event.getSource().getBindingContext().getPath();
//                     var obj = model.getProperty(path);
//                     var notification_email = obj['email'];
//                     if (notification_email != null && notification_email != "") {

//                         if(selectTeamArea=="share_email"){
//                             toEmailField.setValue(notification_email);
//                         }else if(selectTeamArea=="cc_email"){
//                                 bccEmailField.setValue(notification_email);
//                         }
//                         oDialogTeamSelect.close();
//                     } else {
//                         sap.m.MessageBox.error(oBundle.getText("Email_not_available_for_selected_team_member"));
//                     }
//                 }
//         })]
// });
var teamPage4W = new sap.m.Page("team_page_4w", {
    title:oBundle.getText("4W_Team_Management"),
    showHeader:true,
    enableScrolling:true,
    content : [oTable4WGrabTeam] 
}); 


function blockGrabTeamMember(obj) {

    let userBlockDB1 = new sap.m.ComboBox();
    userBlockDB1.setWidth("100%");
    userBlockDB1.addItem(new sap.ui.core.ListItem({text:oBundle.getText("Active")}));
    userBlockDB1.addItem(new sap.ui.core.ListItem({text:oBundle.getText("Inactive")}));
    userBlockDB1.setValue(obj["status"]);
    userBlockDB1.addEventDelegate({
        onAfterRendering: function(e) {
            userBlockDB1.$().find("input").attr("readonly", true);
        }
    });


    var oDialog = new sap.m.Dialog({
        title: oBundle.getText("Inactive_Team_Member"),
        state: sap.ui.core.ValueState.Error,
        content: [userBlockDB1],
        buttons: [
            new sap.m.Button({text: oBundle.getText("Done"),icon: "sap-icon://accept",
                press: function () {
                        busyDialog.open();
                        var updateItems = { id: obj['id'],status: userBlockDB1.getValue()};
                        Car_User_Master.update(updateItems).done(function () {
                            get4WTeam();
                            addHistoryTableData(obj["user_id"],"Update","Team",obj,updateItems);
                            oDialog.close();
                            busyDialog.close();
                        }, failureUser);
                }
            }),
            new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",press: function () {oDialog.close();}
            })
		]
    }).open();
    if(obj['status'] != 'Active'){
        oDialog.setTitle(oBundle.getText("Active_Team_Member"));
    }
}

function deleteGrabTeamMember(mid) {

    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_User_Master.del({ id: mid }).done(function () {
					            get4WTeam();
                                oDialog.close();
                                busyDialog.close();
					        });
					    }
					}),
					new sap.m.Button({text: oBundle.getText("Cancel"),icon: "sap-icon://decline",
					    press: function () {
					        oDialog.close();
					    }
					})
				]
    }).open();

}

function selectTeamWSGroup(input){
    var oSelectDialog = new sap.m.SelectDialog({ contentWidth: "50%", draggable: true,
        resizable: true, rememberSelections: true, multiSelect: false,
        title: oBundle.getText("Select_Workshop_Group"),
        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("ws_group_number", sap.ui.model.FilterOperator.Contains, sSearchValue),
                    new sap.ui.model.Filter("ws_group_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) {
            input.removeAllTokens();
            var tokenList = input.getTokens();
            var aContexts = oEvent.getParameter("selectedContexts");
            if (aContexts && aContexts.length) {
                aContexts.map(function (oContext) { 
                    let ws_group_number =  oContext.getObject()['ws_group_number'];
                    let ws_group_name =  oContext.getObject()['ws_group_name'];

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

                });
            }
        }
    });

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

    let tokenList = input.getTokens();
    let resultTokenList = workshopmaster4WJSONData.filter(function (obj, index) {
        for (var j = 0; j < tokenList.length; j++) {
            if (tokenList[j].getKey() == obj.ws_group_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"));

}

function selectTeamWorkshop(src,input1,input2){
    var oSelectDialog = new sap.m.SelectDialog({ contentWidth: "50%", draggable: true,
        resizable: true, rememberSelections: true, multiSelect: false,
        title: oBundle.getText("Select_Workshop"),
        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("workshop_number", sap.ui.model.FilterOperator.Contains, sSearchValue),
                    new sap.ui.model.Filter("workshop_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 == 3 || src == 1 || src == 4){
                input1.removeAllTokens();
            }
        
            var tokenList = input1.getTokens();
            var aContexts = oEvent.getParameter("selectedContexts");
            if (aContexts && aContexts.length) {
                aContexts.map(function (oContext) { 
                    let workshop_number =  oContext.getObject()['workshop_number'];
                    let workshop_name =  oContext.getObject()['workshop_name'];

                    var insertFlag = true;
                    for (var j = 0; j < tokenList.length; j++) {
                        if (tokenList[j].getKey() == workshop_number) { insertFlag = false; }
                    }
                    if (tokenList.length == 0 || insertFlag) {
                        if(src == 1){
                            input1.addToken(new sap.m.Token({ key: workshop_number, text: workshop_number }));
                            // input1.setValue(workshop_number);
                            input2.setValue(workshop_name);
                        }else if(src == 2){
                            input1.addToken(new sap.m.Token({ key: workshop_number, text: workshop_number }));
                        }else if(src == 3){ // Workorder Creagte
                            input1.addToken(new sap.m.Token({ key: workshop_number, text: workshop_name }));
                            filterWorkorderPartWorkshop();
                            var wsFilter = workshop4WJSONData.filter(function (a, b) {
                            return a.workshop_number == workshop_number;
                            });
                        
                            oTFWOCost4.setValue(wsFilter[0]["tax_percentage"]);
                        }else if(src == 4){ // Part Master scxreen filter
                            input1.addToken(new sap.m.Token({ key: workshop_number, text: workshop_name }));
                            getPartsDetailsWorkshop(workshop_number);
                        }
                    }

                });
            }
        }
    });

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

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

}


function viewPassword(password) {

    var oDialog = new sap.m.Dialog({
        title: oBundle.getText("Password"),
        state: sap.ui.core.ValueState.Success,
        content: [new sap.m.Label({ text: oBundle.getText("Password") +" - "+password })],
        buttons: [
			new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",press: function () {oDialog.close();}})
		]
    }).open();

}