
var workorderSearch = new sap.m.SearchField({
    placeholder: oBundle.getText("Search"),
    width: "200px",
    selectOnFocus: false,
    layoutData: new sap.ui.layout.GridData({ span: "L4 M6 S12" }),
    search: function (event) {
        if (event.getParameter("clearButtonPressed")) {
            workorderSearch.setValue("");
        } 
    },
    liveChange: function (event) {
        var oBinding = oTableWorkorder.getBinding("items");
        var searchStr = this.getValue();
        if (oBinding) {
            var oFilters = [
                new sap.ui.model.Filter("wo_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("wo_title", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("wo_memo", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("city", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("license_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("vehicle_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("chassis_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("engine_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("assigned_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("model", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("make", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("vehicle_color", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("rental_company_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("leasing_company_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("assigned_id", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("assigned_name", 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("ws_group_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("workshop_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        
                        ];
            var filterObjWo = new sap.ui.model.Filter(oFilters, false);
            oBinding.filter(filterObjWo);
        } else {
            oBinding.filter([]);
        }
    }
});

// var oTableWorkorder = 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("License_Plate"), 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("Wo_Number"),design: sap.m.LabelDesign.Bold})}),
//             new sap.m.Column({width:"130px",header: new sap.m.Label({wrapping:true,textAlign:"Center",wrapping:true,text: oBundle.getText("Created_Date"),design: sap.m.LabelDesign.Bold}),
//             sortIndicator:"Descending",hAlign: "Center"}),
//             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,hAlign: "Center",width:"110px"}),
//             new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Workshop_Name"), design: sap.m.LabelDesign.Bold}),
//             minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Center",width:"110px"}),
//             new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("City"), design: sap.m.LabelDesign.Bold}),
//             minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
//             new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Status"), design: sap.m.LabelDesign.Bold}),
//             minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
//             new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Rental_Company_Name"), design: sap.m.LabelDesign.Bold}),
//             minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
//             new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Leasing_Company_Name"), design: sap.m.LabelDesign.Bold}),
//             minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
//             new sap.m.Column({header: new sap.m.Label({wrapping:false, text: oBundle.getText("Memo"), design: sap.m.LabelDesign.Bold}),
//             minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left",width:"120px"}),
//         ],
var oTableWorkorder = new sap.m.Table({
    growing: true,
    growingThreshold: 25,
    growingScrollToLoad: false,
    noDataText: oBundle.getText("No_Data"),
    growingTriggerText: oBundle.getText("More"),
    sticky: [sap.m.Sticky.ColumnHeaders, sap.m.Sticky.HeaderToolbar, sap.m.Sticky.InfoToolbar],
    columns: [
        // new sap.m.Column({
        //     width: "80px",
        //     header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Action"), design: sap.m.LabelDesign.Bold }),
        //     minScreenWidth: "Phone",
        //     demandPopin: true,
        //     popinDisplay: "Inline"
        // }),
        // new sap.m.Column({
        //     header: new sap.m.Label({wrapping:true,  text: oBundle.getText("License_Plate"), design: sap.m.LabelDesign.Bold }),
        //     minScreenWidth: "Phone",
        //     demandPopin: true,
        //     popinDisplay: "Inline"
        // }),
        // new sap.m.Column({
        //     header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Wo_Number"), design: sap.m.LabelDesign.Bold }),
        //     minScreenWidth: "Phone",
        //     demandPopin: true,
        //     popinDisplay: "Inline"
        // }),
        // new sap.m.Column({
        //     header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Created_Date"), design: sap.m.LabelDesign.Bold }),
        //     width: "110px",
        //     sortIndicator: "Descending",
        //     hAlign: "Center",
        //     minScreenWidth: "Desktop",
        //     demandPopin: true,
        //     popinDisplay: "Inline"
        // }),
        // new sap.m.Column({
        //     header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Workshop_Group_Name"), design: sap.m.LabelDesign.Bold }),
        //     width: "120px",
        //     hAlign: "Center",
        //     minScreenWidth: "Tablet",
        //     demandPopin: true,
        //     popinDisplay: "Inline"
        // }),
        // new sap.m.Column({
        //     header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Workshop_Name"), design: sap.m.LabelDesign.Bold }),
        //     width: "120px",
        //     hAlign: "Center",
        //     minScreenWidth: "Tablet",
        //     demandPopin: true,
        //     popinDisplay: "Inline"
        // }),
        // new sap.m.Column({
        //     header: new sap.m.Label({wrapping:true,  text: oBundle.getText("City"), design: sap.m.LabelDesign.Bold }),
        //     hAlign: "Center",
        //     minScreenWidth: "Desktop",
        //     demandPopin: true,
        //     popinDisplay: "Inline"
        // }),
        // new sap.m.Column({
        //     header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Status"), design: sap.m.LabelDesign.Bold }),
        //     hAlign: "Center",
        //     minScreenWidth: "Desktop",
        //     demandPopin: true,
        //     popinDisplay: "Inline"
        // }),
        // new sap.m.Column({
        //     header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Rental_Company_Name"), design: sap.m.LabelDesign.Bold }),
        //     hAlign: "Center",
        //     minScreenWidth: "Desktop",
        //     demandPopin: true,
        //     popinDisplay: "Inline"
        // }),
        // new sap.m.Column({
        //     header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Leasing_Company_Name"), design: sap.m.LabelDesign.Bold }),
        //     hAlign: "Center",
        //     minScreenWidth: "Desktop",
        //     demandPopin: true,
        //     popinDisplay: "Inline"
        // }),
        // new sap.m.Column({
        //     header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Memo"), design: sap.m.LabelDesign.Bold }),
        //     width: "120px",
        //     hAlign: "Left",
        //     minScreenWidth: "Desktop",
        //     demandPopin: true,
        //     popinDisplay: "Inline"
        // })
        new sap.m.Column({
            // width: "80px",
            header: new sap.m.Label({
                text: oBundle.getText("Action"),
                wrapping: true,
                design: sap.m.LabelDesign.Bold
            }),
            minScreenWidth: "Phone",
            demandPopin: false,
            popinDisplay: "Inline"
        }),
        new sap.m.Column({
            // width: "100px",
            header: new sap.m.Label({
                text: oBundle.getText("License_Plate"),
                wrapping: true,
                design: sap.m.LabelDesign.Bold
            }),
            minScreenWidth: "Phone",
            demandPopin: true,
            popinDisplay: "Inline"
            
        }),
        new sap.m.Column({
            // width: "100px",
            header: new sap.m.Label({
                text: oBundle.getText("Wo_Number"),
                wrapping: true,
                design: sap.m.LabelDesign.Bold
            }),
            minScreenWidth: "Phone",
            demandPopin: true,
            popinDisplay: "Inline"
        }),
        new sap.m.Column({
            // width: "110px",
            header: new sap.m.Label({
                text: oBundle.getText("Created_Date"),
                wrapping: true,
                design: sap.m.LabelDesign.Bold
            }),
            sortIndicator: "Descending",
            hAlign: "Center",
            minScreenWidth: "Desktop",
            demandPopin: true,
            popinDisplay: "Inline"
        }),
        new sap.m.Column({
            // width: "120px",
            header: new sap.m.Label({
                text: oBundle.getText("Workshop_Group_Name"),
                wrapping: true,
                design: sap.m.LabelDesign.Bold
            }),
            hAlign: "Center",
            minScreenWidth: "Desktop",
            demandPopin: true,
            popinDisplay: "Inline"
        }),
        new sap.m.Column({
            // width: "120px",
            header: new sap.m.Label({
                text: oBundle.getText("Workshop_Name"),
                wrapping: true,
                design: sap.m.LabelDesign.Bold
            }),
            hAlign: "Center",
            minScreenWidth: "Desktop",
            demandPopin: true,
            popinDisplay: "Inline"
        }),
        new sap.m.Column({
            // width: "90px",
            header: new sap.m.Label({
                text: oBundle.getText("City"),
                wrapping: false,
                design: sap.m.LabelDesign.Bold
            }),
            hAlign: "Center",
            minScreenWidth: "Desktop",
            demandPopin: true,
            popinDisplay: "Inline"
        }),
        new sap.m.Column({
            // width: "90px",
            header: new sap.m.Label({
                text: oBundle.getText("Status"),
                wrapping: true,
                design: sap.m.LabelDesign.Bold
            }),
            hAlign: "Center",
            minScreenWidth: "Desktop",
            demandPopin: true,
            popinDisplay: "Inline"
        }),
        new sap.m.Column({
            // width: "150px",
            header: new sap.m.Label({
                text: oBundle.getText("Rental_Company_Name"),
                wrapping: true,
                design: sap.m.LabelDesign.Bold
            }),
            hAlign: "Center",
            minScreenWidth: "Desktop",
            demandPopin: true,
            popinDisplay: "Inline"
        }),
        new sap.m.Column({
            // width: "150px",
            header: new sap.m.Label({
                text: oBundle.getText("Leasing_Company_Name"),
                wrapping: true,
                design: sap.m.LabelDesign.Bold
            }),
            hAlign: "Center",
            minScreenWidth: "Desktop",
            demandPopin: true,
            popinDisplay: "Inline"
        }),
        new sap.m.Column({
            // width: "120px",
            header: new sap.m.Label({
                text: oBundle.getText("Memo"),
                wrapping: true,
                design: sap.m.LabelDesign.Bold
            }),
            hAlign: "Left",
            minScreenWidth: "Desktop",
            demandPopin: true,
            popinDisplay: "Inline"
        })
    ],

        infoToolbar:new sap.m.Toolbar({visible: false,
            content: [
                new sap.m.Label({text: ""}),
                new sap.m.ToolbarSpacer(),
                new sap.ui.core.Icon({ src : "sap-icon://clear-filter",
                    press: function (oEvent) {
                        var parent = oEvent.getSource().getParent().getParent();
                        parent.getBinding("items").filter([]);
                        parent.getInfoToolbar().setVisible(false);
                }})
            ]
        }),
        headerToolbar:new sap.m.OverflowToolbar({
            content: [   
                        //new sap.m.Title({level:"Auto",text: oBundle.getText("Workorder History")}),
                        // new sap.m.Button({
                        //     id:"createWorkorderID",
                        //     type: sap.m.ButtonType.Emphasized,
                        //     icon: "sap-icon://add-equipment",
                        //     text: oBundle.getText("Create_Workorder"),
                        //     press: function () {
                        //             if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('create_work_order') != -1)){
                        //                 if(workshop4WJSONData.length > 0){

                        //                     addPageSrc = "1";
                        //                     // oAppWoRequest.removePage(addWOPage);
                        //                     oAppWorkOrder.addPage(addWOPage);
                        //                     oAppWorkOrder.to("add_wo_page");
                        //                     addWOPage.setTitle(oBundle.getText("Maintenance_Workorder"));
                        //                     iniWorkOrder();
                        //                     workorderForm1.getFormContainers()[0].getFormElements()[5].setVisible(false);
                        //                     btnWO1.setText(oBundle.getText("Create_WorkOrder"));
                        //                 }else{
                        //                     sap.m.MessageBox.error("Please wait while the Workshop Data is loading.");
                        //                 }
                        //             }else{
                        //                 sap.m.MessageToast.show("Create Access not provided.");
                        //             }
                               
                        //     }
                        // }),
                        new sap.m.Button({
                            id:"BulkUpdateWorkorderID",
                            type: sap.m.ButtonType.Emphasized,
                            icon: "sap-icon://add-equipment",
                            text: oBundle.getText("Bulk_Approve"),
                            press: function () {
                                var approval_level_code = sessionStorage.getItem("oxmaint_approval_level");
                                var filterDataBulk = [];
                                if(approval_level_code == oBundle.getText('G3')){
                                    filterDataBulk = grabPendingWOJSONArray.filter(function(obj,eve){ return !nullCheckAll(obj.approval1); });
                                }else if(approval_level_code == oBundle.getText('G4')){
                                    filterDataBulk = grabPendingWOJSONArray.filter(function(obj,eve){ return !nullCheckAll(obj.approval2) && nullCheckAll(obj.approval1); });
                                }else if(approval_level_code == oBundle.getText('G5')){
                                    filterDataBulk = grabPendingWOJSONArray.filter(function(obj,eve){ return !nullCheckAll(obj.approval3) && nullCheckAll(obj.approval2); });
                                }else if(approval_level_code == oBundle.getText('G6')){
                                    filterDataBulk = grabPendingWOJSONArray.filter(function(obj,eve){ return !nullCheckAll(obj.approval4) && nullCheckAll(obj.approval3); });
                                }else if(approval_level_code == oBundle.getText('G7')){
                                    filterDataBulk = grabPendingWOJSONArray.filter(function(obj,eve){ return !nullCheckAll(obj.approval5) && nullCheckAll(obj.approval4); });
                                }
                                // console.log(filterDataBulk);
                                bulkCheckWorkorderApprove(filterDataBulk,approval_level_code);
                            }
                        }),
                        // new sap.m.Button({
                        //     type: sap.m.ButtonType.Emphasized,
                        //     icon: "sap-icon://add-equipment",
                        //     text: oBundle.getText("Create Invoice"),
                        //     press: function () {
                        //         createGrabInvoice(1);
                        //     }
                        // }),
                        new sap.m.ToolbarSpacer(),
                        workorderSearch,
                        // new sap.m.Button({ 
                        //     type: sap.m.ButtonType.Emphasized,
                        //     text:oBundle.getText("Multi Filter"),
                        //     icon: 'sap-icon://add-filter',
                        //     press: function () {
                        //         funMultiFilterOpenWO(grabPendingWOJSONArray,oTableWorkorder);
                        //     }
                        // }),
                        // new sap.m.Button({icon: "sap-icon://sort",press: function () {
                        //         VSDWorkorder.open();
                        // }}),
                        new sap.m.Button({icon: "sap-icon://filter",press: function () {
                            funMultiFilterOpenWO(1,grabPendingWOJSONArray,oTableWorkorder,workorderTemplate);
                        }}),
                        // new sap.m.Button({text:"Export",icon: "sap-icon://excel-attachment",press: function () {
                        //     if(subscription_status != 'Inactive' && subscription_status != 'Cancelled'){
                        //         workorderExcelExport();
                        //     }else{
                        //         sap.m.MessageBox.error(oBundle.getText("Your_subscription_is_inactive_please_buy_subscription"));
                        //         return;
                        //     }
                        // }})
                    ]
        })
    });

var workorderTemplate = new sap.m.ColumnListItem({
    cells: [
        new sap.m.Button({
            type: "Emphasized",
            icon: "sap-icon://action",
            text: "",
            press: function (event) {
                
                var model = this.getModel();
                var path = event.getSource().getBindingContext().getPath();
                var obj = model.getProperty(path);
                displayMenuWorkOrder(event,obj);
            }
        }),
        // new sap.m.Label({ wrapping: true, text: "{license_number}" }),
        // new sap.m.Label({wrapping:true,text: "{wo_number}"}),
        new sap.m.VBox({
            items:[new sap.m.Label({ wrapping: true, text: "{license_number}" }),
                    new sap.m.Label({ wrapping: true, text: "{chassis_number}" }).addStyleClass("sapUiTinyMarginTop"),
            ]
        }).addStyleClass("sapUiTinyMargin"),
        new sap.m.VBox({
            items:[
                new sap.m.Label({wrapping:true,text: "{wo_number}"}),
                new sap.m.Label({ wrapping: true, text: "{wo_title}",tooltip:"{wo_title}"}).addStyleClass("sapUiTinyMarginTop"),
        ]}).addStyleClass("sapUiTinyMargin"),
        new sap.m.VBox({
            items:[
                new sap.m.Label({wrapping:true,text: "{created_date}"}),
                // new sap.tnt.InfoLabel({
                //     text: {
                //         // path: "invoice_number",
                //         parts: [{ path: "invoice_number", type: new sap.ui.model.type.String() },
                //             { path: "wo_status", type: new sap.ui.model.type.String()}],
                //         formatter: function (status,wo_status) {
                //             if(wo_status == 'Closed'){
                //                 if(nullCheckAll(status)){
                //                     this.setColorScheme(3);
                //                     return "Under Review"
                //                 }else{
                //                     this.setColorScheme(1);
                //                     return "Open Invoice"
                //                 }
                //             }else{
                //                 this.setVisible(false);
                //             }
                //         }
                //     }
                // }),
                new sap.tnt.InfoLabel({
                    text: {
                        parts: [
                            { path: "invoice_number", type: new sap.ui.model.type.String() },
                            { path: "wo_status", type: new sap.ui.model.type.String()}
                        ],
                        formatter: function (status, wo_status) {
                            if (wo_status === 'Closed') {
                                if (nullCheckAll(status)) {
                                    this.setColorScheme(3);
                                    return "Under\nReview";
                                } else {
                                    this.setColorScheme(1);
                                    return "Open\nInvoice";
                                }
                            } else {
                                this.setVisible(false);
                            }
                        }
                    },
                    tooltip: "{invoice_number}", // Optional: show full text on hover
                    width: "100%",               // Optional: allow full width
                })
                
        ]}).addStyleClass("sapUiTinyMargin"),
        // new sap.m.Label({wrapping:true,text: "{created_date}"}),
        new sap.m.Label({ wrapping: true, text: "{ws_group_name}" }),
        new sap.m.Label({ wrapping: true, text: "{workshop_name}" }),
        // new sap.m.VBox({
        //     items:[new sap.m.Label({ wrapping: true, text: "{ws_group_name}" }),
        //             new sap.m.Label({ wrapping: true, text: "{ws_group_number}" }).addStyleClass("sapUiTinyMarginTop"),
        //     ]
        // }).addStyleClass("sapUiTinyMargin"),
        // new sap.m.VBox({
        //     items:[new sap.m.Label({ wrapping: true, text: "{workshop_name}" }),
        //             new sap.m.Label({ wrapping: true, text: "{workshop_number}" }).addStyleClass("sapUiTinyMarginTop"),
        //     ]
        // }).addStyleClass("sapUiTinyMargin"),
        new sap.m.Label({ wrapping: true, text: "{city}" }),
        new sap.tnt.InfoLabel({
            text: {
                path: "wo_status",
                formatter: function (status) {
                    if (status == "Pending Approval") {
                        this.setColorScheme(9);
                    }else if (status == "Reject") { 
                        this.setColorScheme(8);
                    }else if (status == "Open") { 
                        this.setColorScheme(1);
                    }else if (status == "Completed") { 
                        this.setColorScheme(6);
                    }else if (status == "Closed") { 
                        this.setColorScheme(3);
                    }else if (status == "Invoiced") { 
                        this.setColorScheme(3);
                    }else if (status == "Cancelled") { 
                        this.setColorScheme(3);
                    }
                    return status;
                }
            }
        }),
        new sap.m.Label({ wrapping: true, text: "{rental_company_name}" }),
        new sap.m.Label({ wrapping: true, text: "{leasing_company_name}" }),
        // new sap.m.Button({icon: "sap-icon://employee",
        //     text: {path: "assigned_id",
        //         formatter: function (value) {
            //             var oArray = [];
            //             if (value != null && value != "") {
                //                 oArray = value.split("^");
                //             }
                //             if (oArray.length > 0) {
        //                 this.setType(sap.m.ButtonType.Accept);
        //                 return (oArray.length);
        //             } else {
        //                 this.setType(sap.m.ButtonType.Reject);
        //                 return "0";
        //             }
        //         }
        //     },
        //     press: function (event) {
            //         var model = this.getModel();
            //         var path = event.getSource().getBindingContext().getPath();
            //         var obj = model.getProperty(path);
            
            //         viewAssignedTeam(obj['assigned_id'],obj['assigned_name']);
            //     }
            // }),
        new sap.m.Label({ wrapping: true, text: "{wo_memo}" }),
        // new sap.m.Label({
        //     text: {
        //             path: "wo_memo",
        //             wrapping:true,
        //             formatter: function (remark) {
        //                 if (remark == null || remark == "") {
        //                 }else{
        //                     return remark.replace(/\^/g, ", ");
        //                 }
        //             }
        //         },tooltip: {
        //             path: "wo_memo",
        //             formatter: function (remark) {
        //                 if (remark == null || remark == "") {
        //                 }else{
        //                     return remark.replace(/\^/g, ", ");
        //                 }
        //             }}}),
        ],
    highlight: {
        path: "created_date",
        formatter: function (createdDate) {
            if(createdDate!=null && createdDate!=""){
                if(getDate() == createdDate.split(" ")[0] ){ return "Success";}
                return "None";
            }
        }
    }
});

 function viewAssignedTeam(assigned_id,assigned_name){
    
        var oTableAssignedView = new sap.ui.table.Table({
            editable : false, 
            width : "100%",
            visibleRowCount :5	   
            });
            
            oTableAssignedView.setSelectionMode(sap.ui.table.SelectionMode.Single);
            oTableAssignedView.setSelectionBehavior(sap.ui.table.SelectionBehavior.RowOnly);
    
            oTableAssignedView.addColumn(new sap.ui.table.Column({
                label: new sap.ui.commons.Label({text:oBundle.getText("User_ID")}),
                template: new sap.ui.commons.TextView().bindProperty("text", "assigned_id"),
                width:"100%"
            }));
            oTableAssignedView.addColumn(new sap.ui.table.Column({
                label: new sap.ui.commons.Label({text:oBundle.getText("Name")}),
                template: new sap.ui.commons.TextView().bindProperty("text", "assigned_name"),
                width:"100%"
            }));
             
            var assignedArray = [];
            var assignedNameArray = [];
            if (assigned_id != null && assigned_id != "") {
                assignedArray = assigned_id.split("^");
                assignedNameArray = assigned_name.split("^");
            } 
    
            var aDataAssigned =[];
             
            if (assignedArray.length > 0) {
    
                  for (var i = 0; i < assignedArray.length; i++) {
                    aDataAssigned.push({ assigned_id: assignedArray[i],assigned_name: assignedNameArray[i] });
                  }
    
                  var oModelAssign = new sap.ui.model.json.JSONModel();
                  oModelAssign.setData({ modelData: aDataAssigned });
                  oTableAssignedView.setModel(oModelAssign);
                  oTableAssignedView.bindRows("/modelData");
    
                  var oDialog = new sap.m.Dialog({
                      draggable: true,
                      icon: "sap-icon://employee",
                      title: oBundle.getText("Assigned"),
                      state: sap.ui.core.ValueState.Success,
                      content: [oTableAssignedView],
                      buttons: [
                            new sap.m.Button({
                                text: oBundle.getText("Close"),
                                icon: "sap-icon://decline",
                                press: function () {
                                    oDialog.close();
                                }
                            })
                        ]
                  }).open();
    
              } else { 
                    sap.m.MessageBox.error(oBundle.getText("Workorder_not_assigned"),{title: oBundle.getText("Alert")});
              }
    }

 var VSDWorkorderFilter = new sap.m.ViewSettingsDialog({
			confirm: function (oEvent) {
				var p = oEvent.getParameters();
				if (p.presetFilterItem) {
					var aFilters = new sap.ui.model.Filter("wo_status", sap.ui.model.FilterOperator.EQ, p.presetFilterItem.getKey());
					oTableWorkorder.getBinding("items").filter(aFilters);
				}else{
				    oTableWorkorder.getBinding("items").filter([]);
				}
				oTableWorkorder.getInfoToolbar().setVisible(!!p.filterString);
				oTableWorkorder.getInfoToolbar().getContent()[0].setText(p.filterString);
			},
            presetFilterItems:[new sap.m.ViewSettingsItem({key: "1",text: oBundle.getText("Initiated")}),
                               new sap.m.ViewSettingsItem({key: "2",text: oBundle.getText("In_Progress")}),
                               new sap.m.ViewSettingsItem({key: "3",text: oBundle.getText("On_Hold")}),
                               new sap.m.ViewSettingsItem({key: "4",text: oBundle.getText("Complete")}),
                               new sap.m.ViewSettingsItem({key: "5",text: oBundle.getText("Rework")}),
                               new sap.m.ViewSettingsItem({key: "6",text: oBundle.getText("Postponed")})
    ]});

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

                  var sortType = sap.ui.core.SortOrder.Descending;
                  if (this.getSortDescending()) {
                      sortType = sap.ui.core.SortOrder.Descending;
                  } else {
                      sortType = sap.ui.core.SortOrder.Ascending;
                  }

                  oTableWorkorder.getColumns()[1].setSortIndicator(sap.ui.core.SortOrder.None);
                  oTableWorkorder.getColumns()[2].setSortIndicator(sap.ui.core.SortOrder.None);
                  oTableWorkorder.getColumns()[3].setSortIndicator(sap.ui.core.SortOrder.None);
                  oTableWorkorder.getColumns()[4].setSortIndicator(sap.ui.core.SortOrder.None);
                  oTableWorkorder.getColumns()[5].setSortIndicator(sap.ui.core.SortOrder.None);
                  oTableWorkorder.getColumns()[6].setSortIndicator(sap.ui.core.SortOrder.None);

                  if (key == "1") {
                      oTableWorkorder.getColumns()[1].setSortIndicator(sortType);
                  } else if (key == "2") {
                      oTableWorkorder.getColumns()[2].setSortIndicator(sortType);
                  } else if (key == "3") {
                      oTableWorkorder.getColumns()[3].setSortIndicator(sortType);
                  } else if (key == "4") {
                      oTableWorkorder.getColumns()[4].setSortIndicator(sortType);
                  } else if (key == "5") {
                      oTableWorkorder.getColumns()[5].setSortIndicator(sortType);
                  } else if (key == "6") {
                      oTableWorkorder.getColumns()[6].setSortIndicator(sortType);
                  } 

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

                              var strDate1 = a;
                              var strDate2 = b;

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

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

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

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

                              var cost1 = 0;
                              var cost2 = 0;

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

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

                                return 0;
                          };
                      }
                      oTableWorkorder.getBinding("items").sort(oSorter);
                  }
              }
          },
          sortItems:[new sap.m.ViewSettingsItem({
                  text: oBundle.getText("Wo_Number"),
                  selected: true,
                  customData: new sap.ui.core.CustomData({
                      key:"1",
                      value: new sap.ui.model.Sorter("wo_number", false)
                  })
              }),
              new sap.m.ViewSettingsItem({
                  text: oBundle.getText("Created_Date"),
                  customData: new sap.ui.core.CustomData({
                      key:"2",
                      value: new sap.ui.model.Sorter("created_date", false)
                  })
              }),
              new sap.m.ViewSettingsItem({
                  text: oBundle.getText("Vehicle_Number"),
                  customData: new sap.ui.core.CustomData({
                      key:"3",
                      value: new sap.ui.model.Sorter("vehicle_number", false)
                  })
              }),
              new sap.m.ViewSettingsItem({
                  text: oBundle.getText("Status"),
                  customData: new sap.ui.core.CustomData({
                      key:"5",
                      value: new sap.ui.model.Sorter("wo_status", false)
                  })
              }),
              new sap.m.ViewSettingsItem({
                  text: oBundle.getText("Priority"),
                  customData: new sap.ui.core.CustomData({
                      key:"6",
                      value: new sap.ui.model.Sorter("wo_priority", false)
                  })
              })
          ]
      });
      
function displayMenuWorkOrder(event,obj){
    
    var oMenu = new sap.m.Menu({ title: oBundle.getText("Option"), width: "200px",
        items: [
                // new sap.m.MenuItem({icon: "sap-icon://user-settings",text: oBundle.getText("Worker_Dashboard"),key: "7"}),
                new sap.m.MenuItem({icon: "sap-icon://show",text: oBundle.getText("View"),key: "1"}),
                // new sap.m.MenuItem({icon: "sap-icon://duplicate",text: oBundle.getText("Duplicate_WO"),key: "9"}),
                // new sap.m.MenuItem({icon: "sap-icon://share-2",text: oBundle.getText("Share"),key: "3"}),  
                // new sap.m.MenuItem({icon: "sap-icon://share-2",text: oBundle.getText("Approval 6"),key: "15"}),  
                // new sap.m.MenuItem({icon: "sap-icon://share-2",text: oBundle.getText("Approval 2"),key: "11"}),  
                // new sap.m.MenuItem({icon: "sap-icon://share-2",text: oBundle.getText("Approval 3"),key: "12"}),  
                // new sap.m.MenuItem({icon: "sap-icon://share-2",text: oBundle.getText("Approval 4"),key: "13"}),  
                // new sap.m.MenuItem({icon: "sap-icon://share-2",text: oBundle.getText("Approval 5"),key: "14"}),  
        ],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
            if (oItem == "1") {
                workorderViewGrab(obj,"1");
            } else if (oItem == "2") {
                if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('modify_work_order') != -1)){
                    addPageSrc = "1";
                    // oAppWoRequest.removePage(addWOPage);
                    oAppWorkOrder.addPage(addWOPage);

                    iniUpdateWorkOrder(obj);
                    oAppWorkOrder.to("add_wo_page");
                    addWOPage.setTitle(oBundle.getText("Maintenance_Workorder"));
                    btnWO2.setText(oBundle.getText("Update_WorkOrder"));
                }else{
                    sap.m.MessageToast.show("Modify Access not provided.");
                }

            } else if (oItem == "3") {
                var vehicle_number = obj['vehicle_number'];
                var vehicle_name = obj['vehicle_name'];
                var wo_number = obj['wo_number'];
                var reportLink = obj['pdf_url'];

                var created_date = obj['created_date'];

                var assigned_name = obj['assigned_name'];
                if(assigned_name != null){
                   assigned_name = assigned_name.replace(/\^/g, ", ");
                }

                var wo_status = getStatusText(obj['wo_status']);
                var wo_priority = getPriorityText(obj['wo_priority']);
                
                var subject = oBundle.getText("Sharing_HVI_Workorder")+" #" + " " + wo_number;
                var message = oBundle.getText("Vehicle_Number")+" : "+vehicle_number+"<br>"+
                              oBundle.getText("Vehicle_Name")+" : "+vehicle_name+"<br>"+
                              oBundle.getText("Created_Date")+" : "+created_date+"<br>"+
                              oBundle.getText("Status")+" : "+wo_status+"<br>"+
                              oBundle.getText("Priority")+" : "+wo_priority+"<br>"+
                              oBundle.getText("Assigned")+" : "+assigned_name+"<br>"+
                              oBundle.getText("Workorder_Link")+" : "+reportLink;
                var dialogTitle = oBundle.getText("Share_Workorder_with_Team_Member");
                var layoutHeader = oBundle.getText("Workorder")+"# "+wo_number;

                shareDialog(subject, message,dialogTitle,layoutHeader);
            } else if (oItem == "4"){
               archiveWorkorder(obj['id'],"archive",obj['wo_status']);
            } else if (oItem == "5"){
                archiveWorkorder(obj['id'],"unarchive",obj['wo_status']);
            }else if (oItem == "8"){
                closeWorkorder(obj['id']);
            } else if (oItem == "6"){
                deleteWorkOrder(obj['id']);
            // }else if (oItem == "7") {
            //     sideNavigation.setSelectedKey("p31");
            //     navContainer.to("p31");
            //     // oLayoutVehicle.to("vehicle_page");
                
            //     initWOrkorderDashboard(obj);
            //     oAppWorkOrder.to("wo_execution");
            }else if(oItem == "9"){
                sap.m.MessageBox.show(oBundle.getText("Do_you_want_to_Duplicate"),
                sap.m.MessageBox.Icon.INFORMATION,
                oBundle.getText("Alert"),
                [sap.m.MessageBox.Action.YES, sap.m.MessageBox.Action.NO],
                function (bConfirmed) {
                    if (bConfirmed == "YES") {
                        busyDialog.open();
                        duplicateWoData(obj);
                    }
                });
            } else if (oItem == "10"){
                workorderViewGrab(obj,"2","Approval1");
            } else if (oItem == "11"){
                workorderViewGrab(obj,"2","Approval2");
            } else if (oItem == "12"){
                workorderViewGrab(obj,"2","Approval3");
            } else if (oItem == "13"){
                workorderViewGrab(obj,"2","Approval4");
            } else if (oItem == "14"){
                workorderViewGrab(obj,"2","Approval5");
            } else if (oItem == "15"){
                
                var comment = new sap.m.TextArea({width:"100%",value: "",height:"70px",rows : 2, 
                    placeholder:"Enter Remark(mandatory)",
                    wrapping : sap.ui.core.Wrapping.on,
                    liveChange: function (oEvent) {
                        var sText = oEvent.getParameter('value');
                        //var parent = oEvent.getSource().getParent();
                        cancelBtn.setEnabled(sText.length > 0);
                }});

                const cancelBtn = new sap.m.Button({text: oBundle.getText("Cancel WO"),
                    enabled:false,type:"Reject",
                    press: function () {
                        commentData = comment.getValue();

                        busyDialog.open();
                        Car_Workorder.update({ id: obj['id'],wo_status:"Cancelled" }).done(function () {
                            Car_Workorder_Status.insert({ master_email:emailUser, wo_number:obj['wo_number'], wo_id: obj['id'], wo_status: "Cancelled", 
                                changed_date: created_date, changed_by: operatedID,note:commentData
                            }).done(function () { });
                            let currentWOSection = oAppWorkOrderPageLayout.getSelectedSection();
                            if(currentSectionId=="GWO1"){  // Pending
                                getPendingWorkorder();
                            }else if (currentWOSection == "GWO6") { //Reject
                              getRejectWorkorder();
                            } else if(currentWOSection == "GWO11"){ //Need Verification
                              getVerificationWorkorder();
                            }

                            oDialog.close();
                            busyDialog.close();
                        });
                    }
                });

                var created_date = getIndonesianTime();
                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 cancel Workorder?") }),comment],
                    buttons: [
                                cancelBtn,
                                new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",
                                    press: function () {
                                        oDialog.close();
                                    }
                                })
                            ]
                }).open();
            } else if (oItem == "16"){
                workorderViewGrab(obj,"3")
            }else if(oItem == '17'){
                updateGrabInvoice(1,obj);
            }else if(oItem == '18'){
                // verifyWorkorder(obj);
                workorderViewGrab(obj,"2","Approval1");
            }
        }
    });

   var menuItem =  oMenu.getItems();

   let currentSectionId = oAppWorkOrderPageLayout.getSelectedSection();
   if(currentSectionId != 'GW10'){

       if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('archive_work_order') != -1)){
           if(obj['archive'] == "1"){
               // menuItem[0].setVisible(false);
               oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://sap-box",text: oBundle.getText("Unarchive"),key: "5"}));
           }else{
               oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://sap-box",text: oBundle.getText("Archive"),key: "4"}));
           }
       };
    
    //    console.log(obj['wo_status'])
       if(obj['wo_status'] == 'Need Verification' && obj['created_by'] != operatedID && obj['updated_by'] != operatedID && oxmaint_wo_verification == "1"){
            oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://approvals",text: oBundle.getText("Verify"),key: "18"}));
       }
       // if(obj['wo_status']=="Reject"){
       //     oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://decline",text: oBundle.getText("Cancel_Workorder"),key: "15"}));
       // }
       if(obj['wo_status']=="Open"){
           oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://accept",text: oBundle.getText("Complete"),key: "16"}));
       }
       if((obj['wo_status']=="Need Verification" || obj['wo_status']=="Pending Approval" || obj['wo_status']=="Open" || obj['wo_status']=="Completed" || obj['wo_status']=="Reject") && obj['archive'] == '0' && hvi_account_access_value.indexOf('modify_work_order') != -1){
           // new sap.m.MenuItem({icon: "sap-icon://edit",text: oBundle.getText("Update"),key: "2"}),
           oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://edit",text: oBundle.getText("Update"),key: "2"}));
       }
       
       //Approvals 
    
       if(obj['wo_status']=="Pending Approval" && !nullCheckAll(obj['approval1']) && oxmaint_approval_level == "G3" && obj['archive'] != '1'){
           oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://accept",text: oBundle.getText("Approval_1"),key: "10"}));
       }
    
       if(obj['wo_status']=="Pending Approval"  && !nullCheckAll(obj['approval2'])  && nullCheckAll(obj['approval1']) && oxmaint_approval_level == "G4" && obj['archive'] != '1'){
           oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://accept",text: oBundle.getText("Approval_2"),key: "11"}));
       }
       if(obj['wo_status']=="Pending Approval" && !nullCheckAll(obj['approval3'])  && obj['approval2'] == "1"  && oxmaint_approval_level == "G5" && obj['archive'] != '1'){
           oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://accept",text: oBundle.getText("Approval_3"),key: "12"}));
       }
       if(obj['wo_status']=="Pending Approval" && !nullCheckAll(obj['approval4'])  && nullCheckAll(obj['approval3']) && oxmaint_approval_level == "G6" && obj['archive'] != '1'){
           oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://accept",text: oBundle.getText("Approval_4"),key: "13"}));
       }
       if(obj['wo_status']=="Pending Approval"  && !nullCheckAll(obj['approval5'])  && nullCheckAll(obj['approval4']) && oxmaint_approval_level == "G7" && obj['archive'] != '1'){
           oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://accept",text: oBundle.getText("Approval_5"),key: "14"}));
       }
       if((obj['wo_status'] == "Reject" || obj['wo_status'] == "Pending Approval" || obj['wo_status'] == "Need Verification"  ) && hvi_login_type == "2" && hvi_account_access_value.indexOf('cancel_work_order') != -1 ){
           oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://accept",text: oBundle.getText("Cancel Workorder"),key: "15"}));
       }
       
       if(obj['wo_status'] == "Closed" && nullCheckAll(obj['invoice_number']) && !nullCheckAll(obj['grn_number']) && hvi_account_access_value.indexOf('modify_invoice_work_order') != -1 && obj['archive'] == '0'){
           oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://accept",text: oBundle.getText("Update Invoice Parts"),key: "17"}));
       }
   }

     
    //  getDeleteMenu(oMenu,"6");
     oMenu.openBy(event.getSource());
};
function displayMenuWorkOrderViewOnly(event,obj){
    // console.log("Hello")
    var oMenu = new sap.m.Menu({ title: oBundle.getText("Option"), width: "200px",
        items: [new sap.m.MenuItem({icon: "sap-icon://show",text: oBundle.getText("View"),key: "1"})],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
            if (oItem == "1") {
                workorderViewGrab(obj,"1");
            }
        }
    });

     oMenu.openBy(event.getSource());
};
  

function workorderExcelExport(){
   
        var xlsHeader = [oBundle.getText("Wo_Number"), 
                         oBundle.getText("WO_Title"), 
                         oBundle.getText("Date"),
                         oBundle.getText("Vehicle_Number"),
                         oBundle.getText("Vehicle_Name"),
                         oBundle.getText("Status"),
                         oBundle.getText("Priority"),
                         oBundle.getText("Total_Cost"),
                         oBundle.getText("Memo")
            ];
 
        var dataObject = [];
        var tableItem = oTableWorkorder.getItems();
        for(var i=0;i<tableItem.length;i++){
            var item = tableItem[i].getBindingContext().getObject();
               dataObject.push({"1":item.wo_number,
                                "2":item.wo_title,
                                "3":item.created_date,
                                "4":item.vehicle_number,
                                "5":item.vehicle_name,
                                "6":getStatusText(item.wo_status),
                                "7":getPriorityText(item.wo_priority),
                                "8":item.total_wo_cost,
                                "9":item.wo_memo
                                });
        }

        var createXLSLFormatObj = [];

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

        var filename = "WOExport.xlsx";
        var sheet_name = "Data";

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

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

  
 var ArchiveWOTable = oTableWorkorder.clone();

 var workorderSearchArchive = new sap.m.SearchField({
        placeholder: oBundle.getText("Search"),
        width: "300px", selectOnFocus: false,
        layoutData: new sap.ui.layout.GridData({ span: "L4 M6 S12" }),
        search: function (event) {
            if (event.getParameter("clearButtonPressed")) {
                workorderSearchArchive.setValue("");
            }
        },
        liveChange: function (event) {

            var oBinding = ArchiveWOTable.getBinding("items");
            var searchStr = this.getValue();
            if (oBinding) {
                var oFilters =[
                    new sap.ui.model.Filter("wo_number", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("wo_title", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("wo_memo", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("city", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("license_number", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("vehicle_name", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("chassis_number", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("engine_number", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("assigned_name", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("model", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("make", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("vehicle_color", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("rental_company_name", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("leasing_company_name", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("assigned_id", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("assigned_name", 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("ws_group_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("workshop_number", sap.ui.model.FilterOperator.Contains, searchStr),
            ];
                filterObjWo = new sap.ui.model.Filter(oFilters, false);
                oBinding.filter(filterObjWo);
            } else {
                oBinding.filter([]);
            }
        }
    });

 ArchiveWOTable.setHeaderToolbar(new sap.m.Toolbar({
    content: [
                // new sap.m.Label({text: oBundle.getText("ARCHIVE_WORKORDER")}),
                new sap.m.ToolbarSpacer(),
                workorderSearchArchive
            ]
    }));

function archiveWorkorder(WOID,type,status) {

    var archive = "0";
    var dialogMsg = new sap.m.Label({ text: oBundle.getText("Do_you_want_to_archive")+"?" });

   
    var btn = new sap.m.Button({
            text: oBundle.getText("Archive"),
            icon: "sap-icon://sap-box",
            press: function () {
                busyDialog.open();
                
                Car_Workorder.update({ id: WOID,archive:archive }).done(function () {
                    busyDialog.close();
                    oDialog.close();
                    funGetArchiveWO();

                    if(status == "Pending Approval"){
                        getPendingWorkorder();
                    }else if(status == "Open"){
                        getOpenWorkorder();
                    }else if(status == "Completed"){
                        getCompletedWorkorder();
                    }else if(status == "Closed"){
                        getClosedWorkorder();
                    }else if(status == "GRN"){
                        getGrnWorkorder();
                    }else if(status == "Reject"){
                        getRejectWorkorder();
                    }else if(status == "Cancelled"){
                        getCancelledWorkorder();
                    }
                    // getAllWorkorderDetails();
                    
                }, failure);
            }
        });

     var oDialog = new sap.m.Dialog({
        title: oBundle.getText("Information"),
        state: sap.ui.core.ValueState.Information,
        content: [dialogMsg],
        buttons: [
					btn,
					new sap.m.Button({
					    text: oBundle.getText("Cancel"),
					    icon: "sap-icon://decline",
					    press: function () {
					        oDialog.close();
					    }
					})
				]
    }).open();

    if(type=="archive"){
        archive = "1";
        dialogMsg.setText(oBundle.getText("Do_you_want_to_archive")+"?");
        btn.setText(oBundle.getText("Archive"));
    }else{
        archive = "0";
        dialogMsg.setText(oBundle.getText("Do_you_want_to_unarchive")+"?");
        btn.setText(oBundle.getText("Unarchive"));
    }


}

function deleteWorkOrder(WOID) {

     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_Workorder.del({ id: WOID }).done(function () {
                                 busyDialog.close();
                                oDialog.close();
                                
                                getPendingWorkorder();
                                // funGetWorkorder();
                                // funWoRequest()
                            }, failure);
					    }
					}),
					new sap.m.Button({
					    text: oBundle.getText("Cancel"),
					    icon: "sap-icon://decline",
					    press: function () {
					        oDialog.close();
					    }
					})
				]
    }).open();
}
 
  
var workorderJSONArray = [];
/*
var totalWoJSONArray = [];
var completedWoJSONArray = [];
var initiatedWoJSONArray = [];
var inProgressWoJSONArray = [];
var onHoldWoJSONArray = [];
var reworkWoJSONArray = [];
var postpondWoJSONArray = [];

function funGetWorkorder() {

    totalWoJSONArray = [];
    completedWoJSONArray = [];
    initiatedWoJSONArray = [];
    inProgressWoJSONArray = [];
    onHoldWoJSONArray = [];
    reworkWoJSONArray = [];
    postpondWoJSONArray = [];

    oTableWorkorder.setBusy(true);
    oTableWorkorderDue.setBusy(true);
    oPieChartWorkorderStatus.setBusy(true);
    oPieChartWorkorderPriority.setBusy(true);
   
    if(hvi_location_id=="Default-001"){

        HVI_Workorder.where(filterQueryWorkorderOpen1, emailUser).
                take(1000).orderByDescending("createdAt").read().done(function (result) {
                    var results=funFilterJsonByVehicleAnsUser(result);
        
                    var oModel = new sap.ui.model.json.JSONModel();
                    oModel.setData({ modelData: results });
                    oTableWorkorder.setModel(oModel);
                
                    oTableWorkorder.bindItems({ path: "/modelData", template : workorderTemplate});
                    oTableWorkorder.setBusy(false);
    
                    
                   // setWorkorderData(result);
        });
    }else{

        HVI_Workorder.where(filterQueryWorkorderOpen2, emailUser,hvi_location_id).
                take(1000).orderByDescending("createdAt").read().done(function (result) {

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

    HVI_Workorder.where(queryWorkorder(1)).take(2000).orderByDescending("createdAt").read().done(function (result) {
        setWorkorderData(result);
    });

    //funGetCompletedWO();
    //funGetArchiveWO();
}

function setWorkorderData(result){

    var results=funFilterJsonByVehicleAnsUser(result);
        
    workorderJSONArray = results;

    var priority1 = 0;
    var priority2 = 0;
    var priority3 = 0;
    var priority4 = 0;
    var priority5 = 0;

    var totalWoCount = 0;
    var woStatusCount1 = 0;
    var woStatusCount2 = 0;
    var woStatusCount3 = 0;
    var woStatusCount4 = 0;
    var woStatusCount5 = 0;
    var woStatusCount6 = 0;

    var woRequestStatus1 = 0;
    var woRequestStatus2 = 0;
    wolistItem.setInfo(results.length);

    //Total Inprogress WO
    var filterInProgress = results.filter((value)=> value.wo_status == "2");
    tileContent1.setValue(filterInProgress.length)
    tileContent1.data("customArray", filterInProgress);

    //Unique Assigned Team
    const uniqueTeamSet = new Set();
    filterInProgress.forEach(item => {
        if(nullCheckAll(item.assigned_id)){
            const teamMemberName = item.assigned_id.split("^");
            for(i=0;i<teamMemberName.length;i++){
                uniqueTeamSet.add(teamMemberName[i]);
            }
        }
    });
    tileContent2.data("customArray", uniqueTeamSet);
    tileContent2.setValue(uniqueTeamSet.size)

    //Unique Asset List
    const uniqueVehicleSet = new Set();
    filterInProgress.forEach(item => {
        uniqueVehicleSet.add(item.vehicle_number);
    });
    tileContent3.data("customArray", uniqueVehicleSet);
    tileContent3.setValue(uniqueVehicleSet.size)

    const overDueWO = [];
    for (var i = 0; i < results.length; i++) {

        var created_date = results[i]['created_date'];
        var  oDate = new Date(created_date.split(" ")[0]);
        if(nullCheckAll(results[i]['due_date']) && !nullCheckAll(results[i]['completion_date'])){
            if(new Date(results[i]['due_date']) < new Date()){
                console
                overDueWO.push(results[i]);
            }
        }
        if(segmentedDate1 <= oDate && oDate <= segmentedDate2){

            totalWoCount = totalWoCount+1;
            totalWoJSONArray.push(results[i]);

            var order_status = results[i]['wo_status'];
            if(results[i]['approval_request'] == '1' && results[i]['approved'] == '1' && order_status != '4' && order_status != '7'){
                woRequestStatus1 += 1;
            }
            if(results[i]['approval_request'] == '1' && results[i]['approved'] == '1' && (order_status == '4' || order_status == '7')){
                woRequestStatus2 += 1;
            }
            if (order_status == "4") {
                woStatusCount1 = woStatusCount1 + 1;
                completedWoJSONArray.push(results[i]);
            } else if (order_status == "1") {
                woStatusCount2 = woStatusCount2 + 1;
                initiatedWoJSONArray.push(results[i]);
            } else if (order_status == "2") {
                woStatusCount3 = woStatusCount3 + 1;
                inProgressWoJSONArray.push(results[i]);
            } else if (order_status == "3") {
                woStatusCount4 = woStatusCount4 + 1;
                onHoldWoJSONArray.push(results[i]);
            } else if (order_status == "5") {
                woStatusCount5 = woStatusCount5 + 1;
                reworkWoJSONArray.push(results[i]);
            } else if (order_status == "6") {
                woStatusCount6 = woStatusCount6 + 1;
                postpondWoJSONArray.push(results[i]);
            }

            var order_priority = results[i]['wo_priority'];

            if (order_priority == "1") {
                priority1 = priority1 + 1;
            } else if (order_priority == "2") {
                priority2 = priority2 + 1;
            } else if (order_priority == "3") {
                priority3 = priority3 + 1;
            } else if (order_priority == "4") {
                priority4 = priority4 + 1;
            } else if (order_priority == "5") {
                priority5 = priority5 + 1;
            }
        }
    }

    woStatuslistItem1.setInfo(totalWoCount);
    woStatuslistItem2.setInfo(woStatusCount1);
    woStatuslistItem3.setInfo(woStatusCount2);
    woStatuslistItem4.setInfo(woStatusCount3);
    woStatuslistItem5.setInfo(woStatusCount4);
    woStatuslistItem6.setInfo(woStatusCount5);
    woStatuslistItem7.setInfo(woStatusCount6);
    
    requestlistItem4.setInfo(woRequestStatus1);
    requestlistItem5.setInfo(woRequestStatus2);
    
    
    var oDataWoStatus = [];
    oDataWoStatus.push({ status: oBundle.getText("Initiated"), count: woStatusCount2});
    oDataWoStatus.push({ status: oBundle.getText("In_Progress"), count: woStatusCount3});
    oDataWoStatus.push({ status: oBundle.getText("On_Hold"), count: woStatusCount4});
    oDataWoStatus.push({ status: oBundle.getText("Rework"), count: woStatusCount5});
    oDataWoStatus.push({ status: oBundle.getText("Postponed"), count: woStatusCount6});

    var oModelPieChartWoStatus = new sap.ui.model.json.JSONModel();
    oModelPieChartWoStatus.setData({ modelData: oDataWoStatus });
    oPieChartWorkorderStatus.setModel(oModelPieChartWoStatus);
    oPieChartWorkorderStatus.setBusy(false);

     var oDataWoPriority = [];
    oDataWoPriority.push({ priority: oBundle.getText("Low"), count: priority1});
    oDataWoPriority.push({ priority: oBundle.getText("Medium"), count: priority2});
    oDataWoPriority.push({ priority: oBundle.getText("High"), count: priority3});
    oDataWoPriority.push({ priority: oBundle.getText("Emergency"), count: priority4});

    var oModelPieChartWoPriority = new sap.ui.model.json.JSONModel();
    oModelPieChartWoPriority.setData({ modelData: oDataWoPriority });
    oPieChartWorkorderPriority.setModel(oModelPieChartWoPriority);
    oPieChartWorkorderPriority.setBusy(false);


    var oModel1 = new sap.ui.model.json.JSONModel();
    oModel1.setData({ modelData: overDueWO });
    oTableWorkorderDue.setModel(oModel1);

    oTableWorkorderDue.bindItems({ path: "/modelData", template : workorderTemplate});
    oTableWorkorderDue.setBusy(false);

}
*/
function funGetArchiveWO() {

    ArchiveWOTable.setBusy(true);

    Car_Workorder.where(filterQueryGrabArchiveWorkorder).includeTotalCount().take(2000).orderByDescending("createdAt").read().done(function (result) {
        
        var results = filterGrabVehicle(result);
        
        for (var i = 0; i < results.length; i++) {
            results[i]['SerialNo'] = parseInt(i + 1);
        }
    
        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        oModel.setSizeLimit(results.length);
       
         ArchiveWOTable.setModel(oModel);
         ArchiveWOTable.bindItems({ path: "/modelData", template : workorderTemplate});
         ArchiveWOTable.setBusy(false);
    });
}

// function workorderView(obj,src){
    
    
//     var editBtn = new sap.m.Button({ text: oBundle.getText("Edit"), 
//         icon: "sap-icon://edit",
//         press: function (e) {
//             oDialog.close();
//             if(src=="2"){
//                 addPageSrc = "2";
//                 oAppWorkOrder.removePage(addWOPage);
//                 // oAppWoRequest.addPage(addWOPage);
//                 addWOPage.setTitle(oBundle.getText("Update_Request"));
//                 btnWO2.setText(oBundle.getText("Update_Request"));

//                 iniUpdateWorkOrder(obj);
//                 // oAppWoRequest.to("add_wo_page");
//             }else{
//                 if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('modify_work_order') != -1)){
//                     sideNavigation.setSelectedKey("p31");
//                     navContainer.to("p31");

//                     addPageSrc = "1";
//                     // oAppWoRequest.removePage(addWOPage);
//                     oAppWorkOrder.addPage(addWOPage);
//                     addWOPage.setTitle(oBundle.getText("Maintenance_Workorder"));
//                     btnWO2.setText(oBundle.getText("Update_WorkOrder"));

//                     iniUpdateWorkOrder(obj);
//                     oAppWorkOrder.to("add_wo_page");
//                 }else{
//                     sap.m.MessageToast.show("Modify Access not provided.");
//                 }
//             }
                 
//         }
//     });

//     var wo_status = new sap.m.ObjectStatus({title: oBundle.getText("Status")});
//     var wo_priority = new sap.m.ObjectStatus({title: oBundle.getText("Priority"),text:obj['wo_priority']});
//     var wo_type = new sap.m.ObjectStatus({title: oBundle.getText("WO_Type"),text:obj['wo_type']});

//     if(obj['wo_status']=="2" || obj['wo_status']=="10"){
//         wo_status.setState("Success");
//     }else if(obj['wo_status']=="3"){
//         wo_status.setState("Warning");
//     }else if(obj['wo_status']=="4"){
//         wo_status.setState("Information");
//     }else if(obj['wo_status']=="5" || obj['wo_status']=="6" || obj['wo_status']=="8"){
//         wo_status.setState("Error");
//     }else{
//         wo_status.setState("None");
//     }
//    wo_status.setText(getStatusText(obj['wo_status']));

   
   
//      if(obj['wo_priority']=="1" || obj['wo_priority']=="2"){
//         wo_priority.setState("None");
//     }else if(obj['wo_priority']=="3"){
//         wo_priority.setState("Warning");
//     }else if(obj['wo_priority']=="4" || obj['wo_priority']=="5"){
//         wo_priority.setState("Error");
//     }
// 	wo_priority.setText(getPriorityText(obj['wo_priority']));	
          
//     var custom1 = new sap.m.ObjectStatus({visible:false,text:obj['custom1']});
//     var custom2 = new sap.m.ObjectStatus({visible:false,text:obj['custom2']});
//     var custom3 = new sap.m.ObjectStatus({visible:false,text:obj['custom3']});
//     var custom4 = new sap.m.ObjectStatus({visible:false,text:obj['custom4']});
//     var custom5 = new sap.m.ObjectStatus({visible:false,text:obj['custom5']});
                         

//     // if (customJSONArray.length > 0) {
//     //     if (customJSONArray[0]['wo_flag1'] == "1") { 
//     //         custom1.setTitle(customJSONArray[0]['wo_field1']);
//     //         custom1.setVisible(true);
//     //     }
//     //     if (customJSONArray[0]['wo_flag2'] == "1") { 
//     //         custom2.setTitle(customJSONArray[0]['wo_field2']);
//     //         custom2.setVisible(true);
//     //     }
//     //     if (customJSONArray[0]['wo_flag3'] == "1") { 
//     //         custom3.setTitle(customJSONArray[0]['wo_field3']);
//     //         custom3.setVisible(true);
//     //     }
//     //     if (customJSONArray[0]['wo_flag4'] == "1") { 
//     //         custom4.setTitle(customJSONArray[0]['wo_field4']);
//     //         custom4.setVisible(true);
//     //     }
//     //     if (customJSONArray[0]['wo_flag5'] == "1") { 
//     //         custom5.setTitle(customJSONArray[0]['wo_field5']);
//     //         custom5.setVisible(true);
//     //     }
//     // }

//  var oTableTaskView = oTableWOTaskItem.clone();
//  oTableTaskView.destroyInfoToolbar();
//  oTableTaskView.setMode("None");
//  oTableTaskView.addColumn(new sap.m.Column({ header: TableHeader.clone().setText(oBundle.getText("Added_Date"))}));
//  oTableTaskView.addColumn(new sap.m.Column({ header: TableHeader.clone().setText(oBundle.getText("Added_By"))}));

//  var oTemplateTaskView = oTableTaskItemTemplate.clone();
//  oTemplateTaskView.setType("Inactive");
//  oTemplateTaskView.addCell(new sap.m.Label({wrapping:true,text: "{added_date}"}));
//  oTemplateTaskView.addCell(new sap.m.Label({wrapping:true,text: "{added_by}"}));


//  var oTablePartsView = oTablePartsItemWO.clone();
//  oTablePartsView.destroyInfoToolbar();
//  oTablePartsView.setMode("None");
//  oTablePartsView.addColumn(new sap.m.Column({ header: TableHeader.clone().setText(oBundle.getText("Added_Date"))}));
//  oTablePartsView.addColumn(new sap.m.Column({ header: TableHeader.clone().setText(oBundle.getText("Added_By"))}));

//  var oTemplatePartsView = oTablePartsItemWOTemplate.clone();
//  oTemplatePartsView.setType("Inactive");
//  oTemplatePartsView.addCell(new sap.m.Label({wrapping:true,text: "{added_date}"}));
//  oTemplatePartsView.addCell(new sap.m.Label({wrapping:true,text: "{added_by}"}));


// //  var oTableLaborView = oTableLaborItemWO.clone();
// //  oTableLaborView.destroyInfoToolbar();
// //  oTableLaborView.setMode("None");
// //  oTableLaborView.addColumn(new sap.m.Column({ header: TableHeader.clone().setText(oBundle.getText("Added_Date"))}));
// //  oTableLaborView.addColumn(new sap.m.Column({ header: TableHeader.clone().setText(oBundle.getText("Added_By"))}));

// //  var oTemplateLaborView = oTableLaborItemWOTemplate.clone();
// //  oTemplateLaborView.setType("Inactive");
// //  oTemplateLaborView.addCell(new sap.m.Label({wrapping:true,text: "{added_date}"}));
// //  oTemplateLaborView.addCell(new sap.m.Label({wrapping:true,text: "{added_by}"}));


//  var oTableAdditionalCost = oTableWOAdditionalCost.clone();
//  oTableAdditionalCost.destroyInfoToolbar();
//  oTableAdditionalCost.setMode("None");

//  var oTemplateAdditionalCost = oTableWOAdditionalCostTemplate.clone();
//  oTemplateAdditionalCost.setType("Inactive");
 
//  var oTableAttachment = oTableWOAttachment.clone();
//  oTableAttachment.destroyInfoToolbar();
//  oTableAttachment.setMode("None");

//  var oTemplateAttachment = oTableAttachmentTemplate.clone();
//  oTemplateAttachment.setType("Inactive");

//  var oTableRemark = oTableWORemark.clone();
//  oTableRemark.destroyInfoToolbar();
//  oTableRemark.setMode("None");

//  var oTemplateRemark = oTableWORemarkTemplate.clone();
//  oTemplateRemark.setType("Inactive");

// //  var oTableTimeLog = oTableWOTimeLog.clone();
// //  oTableTimeLog.destroyInfoToolbar();
// //  oTableTimeLog.setMode("None");

// //  var oTemplateTimeLog = oTableWOTimeLogTemplate.clone();
// //  oTemplateTimeLog.setType("Inactive");

//  var taskProgress = new sap.m.ProgressIndicator({
//             width: "100%",
//             percentValue: 0,
//             displayValue: "0 of 0 Task",
//             state: "Success"
//         });

//  HVI_WO_Task.where({ master_email: emailUser, wo_id: obj['id'] }).read().done(function (results) {
//         var oModel = new sap.ui.model.json.JSONModel();
//         oModel.setData({ modelData: results });
//         oTableTaskView.setModel(oModel);
//         oTableTaskView.bindItems({ path: "/modelData",template: oTemplateTaskView});


//         var total_task = results.length;
//         var taskItems = results.filter(function (obj, index) {
//             return (obj.task_status === "4");
//         });
//         var completed_task = taskItems.length;
//         var percents = (completed_task/total_task) * 100;

//         percents = twoDecimal(percents);

//         taskProgress.setPercentValue(percents);
//         taskProgress.setDisplayValue(completed_task + " of " + total_task + " Task"+" ("+percents+"%)");

//     });

// HVI_WO_Parts.where({ master_email: emailUser, wo_id: obj['id'] }).read().done(function (results) {
//         var oModel = new sap.ui.model.json.JSONModel();
//         oModel.setData({ modelData: results });
//         oTablePartsView.setModel(oModel);
//         oTablePartsView.bindItems({ path: "/modelData",template: oTemplatePartsView});
//     });

// // HVI_WO_Labor.where({ master_email: emailUser, wo_id: obj['id'] }).read().done(function (results) {
// //         var oModel = new sap.ui.model.json.JSONModel();
// //         oModel.setData({ modelData: results });
// //         oTableLaborView.setModel(oModel);
// //         oTableLaborView.bindItems({ path: "/modelData",template: oTemplateLaborView});
// //     });

// HVI_WO_AdditionalCost.where({ master_email: emailUser, wo_id: obj['id'] }).read().done(function (results) {
//         var oModel = new sap.ui.model.json.JSONModel();
//         oModel.setData({ modelData: results });
//         oTableAdditionalCost.setModel(oModel);
//         oTableAdditionalCost.bindItems({ path: "/modelData",template: oTemplateAdditionalCost});
//     });

// HVI_WO_Attachment.where({ master_email: emailUser, wo_id: obj['id'] }).read().done(function (results) {
//         var oModel = new sap.ui.model.json.JSONModel();
//         oModel.setData({ modelData: results });
//         oTableAttachment.setModel(oModel);
//         oTableAttachment.bindItems({ path: "/modelData",template: oTemplateAttachment});
//     });

// HVI_WO_Remark.where({ master_email: emailUser, wo_id: obj['id'] }).read().done(function (results) {
//         var oModel = new sap.ui.model.json.JSONModel();
//         oModel.setData({ modelData: results });
//         oTableRemark.setModel(oModel);
//         oTableRemark.bindItems({ path: "/modelData",template: oTemplateRemark});
//     });

// HVI_WO_TimeLog.where({ master_email: emailUser, wo_id: obj['id'] }).read().done(function (results) {
//         var oModel = new sap.ui.model.json.JSONModel();
//         oModel.setData({ modelData: results });
        
//         var oSorter = new sap.ui.model.Sorter("user_id", false, function(oContext){
// 		var user_id = oContext.getProperty("user_id");
//         var user_name = oContext.getProperty("user_name");
// 		    return {
// 			    key: user_id, 
// 			    text: user_name+"("+user_id+")"
// 		    }
// 	    });
        
//         oTableTimeLog.setModel(oModel);
//         oTableTimeLog.bindItems({path: "/modelData",
// 		    template : oTemplateTimeLog,
//             sorter: oSorter
// 	    });
//     });

// var woTimeLineView = new sap.suite.ui.commons.Timeline({//textHeight:"500px",width:"300px",height:"1200px",
//     width:"100%",
//     enableScroll:false,
//     showHeaderBar:false,
//     showIcons:false
//     //axisOrientation:"Horizontal"
// });

// woTimeLineView.setBusy(true);
// HVI_WO_Status.where({ master_email: emailUser, wo_id: obj['id'] }).read().done(function (results) {
//         var oModel = new sap.ui.model.json.JSONModel();
//         oModel.setData({ modelData: results });
       
//         var temp =  new sap.suite.ui.commons.TimelineItem({width:"50px",
//             dateTime: "{changed_date}",
//             userNameClickable:true,
//             //title: "Technician",
//             userPicture: "Images/icon1.png",
//             text: "{changed_by}",
//             icon: "sap-icon://notes",
//             userName: {path: "wo_status",
//                  formatter: function (status) {

//                             if (status == "0" || status == "1" || status == "7" || status == "9") {
//                                 this.setUserPicture("Images/icon1.png");
//                             }else if (status == "2" || status == "10") { 
//                                 this.setUserPicture("Images/icon2.png");
//                             }else if (status == "3") { 
//                                 this.setUserPicture("Images/icon3.png");
//                             }else if (status == "4") { 
//                                 this.setUserPicture("Images/icon4.png");
//                             }else if (status == "5" || status == "6" || status == "8" ) { 
//                                 this.setUserPicture("Images/icon5.png");
//                             }
//                             return getStatusText(status);
//                         }
//              }
//         });
//         woTimeLineView.bindAggregation("content",{ path: "/modelData",
//             template: temp
//         });

//         woTimeLineView.setModel(oModel);
//         woTimeLineView.setBusy(false);
//     });


//      var oChartStacked = new sap.viz.ui5.controls.VizFrame({
// 	            'width': '300px',
// 	            'height': '180px',
// 	              'vizType' : 'stacked_column',
// 	              'uiConfig' : {
//                   'applicationSet': 'fiori'
//                 },
//                 feeds:[
//                     new sap.viz.ui5.controls.common.feeds.FeedItem({
// 		            'uid' : "axisLabels",
// 		            'type' : "Dimension",
// 		            'values' : ["Cost"]
// 	              }),
//                     new sap.viz.ui5.controls.common.feeds.FeedItem({
// 		            'uid' : "valueAxis",
// 		            'type' : "Measure",
// 		            'values' : ["Estimated","Overdue","Current",]
// 	              })
//                 ],
//                 vizProperties:{
//                   title: {text:oBundle.getText("Estimated_Vs_Current"), visible: false },
//                   valueAxis: { title: { visible: false} },
//                   categoryAxis: { title: { visible: false} },
//                   plotArea: { 
//                       dataLabel: { showTotal:true,visible: true },
//                       isRoundCorner: true,
//                       animation: { dataLoading: true },
//                       drawingEffect: sap.viz.ui5.types.VerticalBar_drawingEffect.glossy,
//                       series: [
//                                 { dataContext: { "measureNames": "Estimated" }, "stack": "a" },
//                                 { dataContext: { "measureNames": "Current" }, "stack": "b" },
//                                 { dataContext: { "measureNames": "Overdue" }, "stack": "b" }
//                     ]}
//                 },
//                 dataset:new sap.viz.ui5.data.FlattenedDataset({
// 		            'dimensions' : [{
// 			            'name' : 'Cost',
// 			            'value' : "{cost}"
// 		            }],
// 		            'measures' : [{
// 		              'name' : 'Estimated', 
// 		              'value' : '{estimated}' 
// 		            },{
// 		              'name' : 'Current', 
// 		              'value' : '{current}' 
// 		            },{
// 		              'name' : 'Overdue', 
// 		              'value' : '{overdue}' 
// 		            }
//                      ],
// 		            'data' : {
// 		              'path' : "/modelData"
// 		            }
// 	              })
//               });;
//       //var oDataStackedChart = [];
//      //oDataStackedChart.push({ cost: "Cost", estimated: parseFloat(estimated_cost),current: parseFloat(total_wo_cost),overdue: overdue_cost});

//     //var oModelStackedChart = new sap.ui.model.json.JSONModel();
//    // oModelStackedChart.setData({ modelData: oDataStackedChart });
//    // oChartStacked.setModel(oModelStackedChart);
//     //var HarveyBallChart = HarveyBallMicroChart.clone();
//     //HarveyBallChart.setTotal(parseFloat(estimated_time));
//    // HarveyBallChart.getItems()[0].setFraction(parseFloat(total_time));
    
//    // HVICore.getElementById('overdue_time_id').setText(overdue_time+" "+"Hrs");

//   /*
//  var relativeTimeView =	new sap.m.ObjectStatus({
// 	    title: "Due",
//         inverted:true,
// 	    text: {
// 			    path: '/dtValue',
// 			    type: 'sap.ui.model.type.DateTime',
// 			    formatOptions: {
// 				    relative: true,
// 				    relativeScale: 'auto'
// 		}},
// 	    icon: "sap-icon://fob-watch",
// 	    state: "Success"   
// 	});

//      var time_data = {"dtValue" : new Date("08-Apr-2019 09:09 PM")}//obj['due_date']
//      var oModelRelative = new sap.ui.model.json.JSONModel(time_data);
//      relativeTimeView.setModel(oModelRelative);
// */

//      var estimated_cost = obj['estimated_cost'];
//      var total_wo_cost = obj['total_wo_cost'];

//      var overdue_cost = "";
//      if(nullCheck(total_wo_cost)&&nullCheck(estimated_cost)){
//          overdue_cost = parseFloat(total_wo_cost) - parseFloat(estimated_cost);
//          overdue_cost = twoDecimal(overdue_cost)+"";
//      }
     
//     var estimated_time = obj['estimated_time'];
//     var total_time = obj['total_time'];

//     var overdue_time = "";
//     if(nullCheck(total_time)&&nullCheck(estimated_time)){
//          overdue_time = parseFloat(total_time) - (parseFloat(estimated_time)*60);
//      }
    
//      var currency = " "+sessionStorage.getItem('oxmaint_currency');

//      var costOverRun = new sap.m.ObjectStatus({title:oBundle.getText("Cost_Overrun"),text: overdue_cost+currency,icon: "sap-icon://lead",state: "Error"});
//      var timeOverRun = new sap.m.ObjectStatus({title:oBundle.getText("Time_Overrun"),text: getHourMinutes(overdue_time),icon: "sap-icon://fob-watch",state: "Error"});
     
   
//      if(overdue_cost==""){
//         costOverRun.setState("Success");
//         costOverRun.setText(oBundle.getText("NA"));
//      }else if(overdue_cost==0){
//         costOverRun.setState("Success");
//      }else if(overdue_cost>0){
//         costOverRun.setState("Error");
//      }else if(overdue_cost<0){
//         overdue_cost = overdue_cost+"";
//         overdue_cost = overdue_cost.replace("-","");
//         costOverRun.setState("Success");
//         costOverRun.setTitle(oBundle.getText("Cost_difference"));
//         costOverRun.setText(overdue_cost+currency);
//      }

//      if(overdue_time==""){
//         timeOverRun.setState("Success");
//         timeOverRun.setText(oBundle.getText("NA"));
//      }else if(overdue_time==0){
//         timeOverRun.setState("Success");
//      }else if(overdue_time>0){
//         timeOverRun.setState("Error");
//      }else if(overdue_time<0){
//         overdue_time = overdue_time+"";
//         overdue_time = overdue_time.replace("-","");
//         timeOverRun.setState("Success");
//         timeOverRun.setTitle(oBundle.getText("Time_difference"));
//         timeOverRun.setText(getHourMinutes(overdue_time));
//      }


//     var dueDate = obj['due_date'];
//     var completionDate = obj['completion_date'];
//     var diffDays = dateDiffInDays(dueDate,completionDate)+"";

//     var overDueDays =   new sap.m.ObjectStatus({title:oBundle.getText("Overdue"),text: diffDays +" Days",icon: "sap-icon://calendar",state: "Error"});

//     if(diffDays<0){
//         diffDays = diffDays.replace("-","");
//         overDueDays.setTitle(oBundle.getText("Early"));
//         overDueDays.setState("Success");
//         overDueDays.setText(diffDays+" "+oBundle.getText("Days"));
//     }else if(diffDays==0){
//         overDueDays.setState("Success");
//     }
    
//     if(nullCheck(estimated_time)){
//         estimated_time = estimated_time + "H";
//     }

// var assigned_name = obj['assigned_name'];
// if(assigned_name!=null){
//    assigned_name = assigned_name.replace(/\^/g, ", ");
// }

// var inspectionBread = new sap.m.Breadcrumbs();

// var link_inspection = obj['link_inspection'];
// if(link_inspection!=null){
//     link_inspection = link_inspection.split("^");
//     for(var i=0;i<link_inspection.length;i++){
//         inspectionBread.addLink(new sap.m.Link({text:link_inspection[i],
//         press:function (event) {
//              var report_number = this.getText();
//              var result = inspectionJSONArray.filter(function (obj, index) {
//                  return (obj.report_no == report_number);
//              });
//             if(result.length>0){
//                 historyView(result[0]);
//             }else{
//                 sap.m.MessageBox.error(oBundle.getText("Report_not_available_might_be_deleted"));
//             } 
//         }
//      }));
//     }
// }

// var workorderBread = new sap.m.Breadcrumbs();

// var link_workorder = obj['link_workorder'];
// if(link_workorder!=null){
//     link_workorder = link_workorder.split("^");
//     for(var i=0;i<link_workorder.length;i++){
//         workorderBread.addLink(new sap.m.Link({text:link_workorder[i],
//         press:function (event) {
//              var wo_number = this.getText();
//              var result = workorderJSONArray.filter(function (obj, index) {
//                  return (obj.wo_number == wo_number);
//              });
//             if(result.length>0){
//                 workorderView(result[0],"1");
//             }else{
//                 sap.m.MessageBox.error(oBundle.getText("Workorder_not_available_might_be_deleted"));
//             } 
//         }
//         }));
//     }
// }

//  var approvalBlock = new sap.ui.layout.VerticalLayout();

//  var approval_request = new sap.m.ObjectStatus({title: oBundle.getText("Approval_Request")});
//  if(obj['approval_request'] == "1" && obj['wo_status']!="8"){
//      approval_request.setText(oBundle.getText("Yes"));
//      approvalBlock.addContent(approval_request);
//      approvalBlock.addContent(new sap.m.ObjectStatus({title: oBundle.getText("Approved_By"),text:obj['approved_by']}));
//      approvalBlock.addContent(new sap.m.ObjectStatus({title: oBundle.getText("Approved_Date"),text:obj['approved_date']}));
//      approvalBlock.addContent(new sap.m.ObjectStatus({title: oBundle.getText("Approver_Remark"),text:obj['approved_remark']}));
//  }else if(obj['approval_request'] == "1" && obj['wo_status']=="8"){
//      approval_request.setText(oBundle.getText("Yes"));
//      approvalBlock.addContent(approval_request);
//      approvalBlock.addContent(new sap.m.ObjectStatus({title: oBundle.getText("Rejected_By"),text:obj['approved_by']}));
//      approvalBlock.addContent(new sap.m.ObjectStatus({title: oBundle.getText("Rejection_Date"),text:obj['approved_date']}));
//      approvalBlock.addContent(new sap.m.ObjectStatus({title: oBundle.getText("Approver_Remark"),text:obj['approved_remark']}));
//  }else{
//      approval_request.setText(oBundle.getText("No"));
//      approvalBlock.addContent(approval_request);
//  }


// var oPageLayout = new sap.uxap.ObjectPageLayout({ headerContentPinnable: true, preserveHeaderStateOnScroll: true,
//     useIconTabBar: true,
//     headerContent: [
//         new sap.ui.layout.VerticalLayout({content: [
//             new sap.m.ObjectStatus({title: oBundle.getText("License_Number"),text:obj['vehicle_number']}),
//             new sap.m.ObjectStatus({title: oBundle.getText("Vehicle_Name"),text:obj['vehicle_name']}),
//             new sap.m.ObjectStatus({title: oBundle.getText("Model"),text:obj['vehicle_model']}),
//             new sap.m.ObjectStatus({title: oBundle.getText("Meter_Reading"),text:obj['meter_reading']}),
//         ]}),
//         new sap.ui.layout.VerticalLayout({content: [wo_status,wo_priority,wo_type]}),
//         new sap.ui.layout.VerticalLayout({content: [
//             new sap.m.ObjectStatus({title: oBundle.getText("Start_Date"),text:obj['start_date']}),
//             new sap.m.ObjectStatus({title: oBundle.getText("Due_Date"),text:obj['due_date']}),
//             new sap.m.ObjectStatus({title: oBundle.getText("Completion_Date"),text:obj['completion_date']}),
//             overDueDays      
//         ]}),
//         new sap.ui.layout.VerticalLayout({content: [
//             new sap.m.ObjectStatus({title: oBundle.getText("Estimated_Time"),text:estimated_time}),
//             new sap.m.ObjectStatus({title: oBundle.getText("Total_Time"),text:getHourMinutes(obj['total_time'])}),
//             timeOverRun
//             ]}),
//         new sap.ui.layout.VerticalLayout({content: [
//             new sap.m.ObjectStatus({title: oBundle.getText("Estimated_Cost"),text:obj['estimated_cost']+currency}),
//             new sap.m.ObjectStatus({title: oBundle.getText("Total_WO_Cost"),text:obj['total_wo_cost']+currency}),
//             costOverRun
//             ]}),
//     ],
//     sections: [
//     new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("General_Details"),
//       subSections: new sap.uxap.ObjectPageSubSection({
//        blocks: [
//         new sap.ui.layout.BlockLayout({
//             content: [
//              new sap.ui.layout.BlockLayoutRow({
//                 content: [
//                    new sap.ui.layout.BlockLayoutCell({ width: 7,content: [
//                       new sap.ui.layout.BlockLayout({
//                          content: [
//                               new sap.ui.layout.BlockLayoutRow({
//                                  content: [
//                                     new sap.ui.layout.BlockLayoutCell({ width: 5,content: [
//                                        new sap.ui.layout.VerticalLayout({content: [

//                                             new sap.m.ObjectStatus({title: oBundle.getText("Assigned"),text:assigned_name}).addStyleClass("sapUiTinyMarginBottom"),
//                                             new sap.ui.layout.HorizontalLayout({
//                                                 content: [new sap.m.ObjectStatus({title: oBundle.getText("Link_Inspection")}),inspectionBread    
//                                             ]}),
//                                             new sap.m.ObjectStatus({title: oBundle.getText("Link_Inspection_Date"),text:obj['link_inspection_date']}),
//                                             new sap.ui.layout.HorizontalLayout({
//                                                 content: [new sap.m.ObjectStatus({title: oBundle.getText("Link_Workorder")}),workorderBread    
//                                             ]}),
//                                             new sap.m.ObjectStatus({title: oBundle.getText("Memo"),text:obj['wo_memo']}),
                                            
//                                             ]}),
                                                      
//                                        ]}),
//                                     new sap.ui.layout.BlockLayoutCell({ width: 5,content: [
//                                         new sap.ui.layout.VerticalLayout({content: [
//                                             new sap.m.ObjectStatus({title: oBundle.getText("Parts_Material_Cost"),text:obj['total_parts_cost']+currency}).addStyleClass("sapUiTinyMarginBottom"),
//                                             new sap.m.ObjectStatus({title: oBundle.getText("Total_Labor_Cost"),text:obj['total_labor_cost']+currency}).addStyleClass("sapUiTinyMarginBottom"),
//                                             new sap.m.ObjectStatus({title: oBundle.getText("Additional_Cost"),text:obj['additional_cost']+currency}).addStyleClass("sapUiTinyMarginBottom"),
//                                             new sap.m.ObjectStatus({title: oBundle.getText("Tax")+" ("+obj['tax']+"%)",text:obj['tax_value']+currency}).addStyleClass("sapUiTinyMarginBottom"),
//                                             new sap.m.ObjectStatus({title: oBundle.getText("Total_WO_Cost"),text:obj['total_wo_cost']+currency}).addStyleClass("sapUiTinyMarginBottom"),
//                                         ]}),

//                                         ]})
// 							      ]}),
//                               new sap.ui.layout.BlockLayoutRow({
//                                 content: [
//                                     new sap.ui.layout.BlockLayoutCell({ width: 5,content: [ approvalBlock]}),
//                                     new sap.ui.layout.BlockLayoutCell({ width: 5,content: [
//                                     new sap.ui.layout.VerticalLayout({width: "100%",content: [
//                                     new sap.m.ObjectStatus({title: oBundle.getText("Task_Completed")}), taskProgress ]}),

//                                     ]})
// 							  ]}),
//                               new sap.ui.layout.BlockLayoutRow({
//                                  content: [
//                                     new sap.ui.layout.BlockLayoutCell({ width: 5,content: [
//                                         new sap.ui.layout.VerticalLayout({content: [
//                                             new sap.m.ObjectStatus({title: oBundle.getText("Created_Date"),text:obj['created_date']}),
//                                             new sap.m.ObjectStatus({title: oBundle.getText("Created_By"),text:obj['created_by']}),
//                                             new sap.m.ObjectStatus({title: oBundle.getText("Last_Updated_Date"),text:obj['updated_date']}),
//                                             new sap.m.ObjectStatus({title: oBundle.getText("Last_Updated_By"),text:obj['updated_by']}),
//                                         ]}),

//                                         ]}),
//                                     new sap.ui.layout.BlockLayoutCell({ width: 5,content: [
//                                     new sap.ui.layout.VerticalLayout({width: "100%",content: [custom1,custom2,custom3,custom4,custom5 ]}),

//                                  ]})
// 							]}),
//                           ]})
//                       ]}),
//                    new sap.ui.layout.BlockLayoutCell({ width: 3,content: [woTimeLineView]})
// 				]}),
//          ]})

//     ]})}),
//     // new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("Task_Details"),
//     //     subSections: new sap.uxap.ObjectPageSubSection({
//     //         blocks: [oTableTaskView]
//     //     })}),
//     new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("Task_Part_&_Labor_Details"),
//         subSections: new sap.uxap.ObjectPageSubSection({
//             blocks: [oTablePartsView]
//         })}),
//     // new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("Labor_Details"),
//     //     subSections: new sap.uxap.ObjectPageSubSection({
//     //         blocks: [oTableLaborView]
//     //     })}),
//     new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("Additional_Cost"),
//         subSections: new sap.uxap.ObjectPageSubSection({
//             blocks: [oTableAdditionalCost]
//         })}),
//         new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("Attachments"),
//         subSections: new sap.uxap.ObjectPageSubSection({
//             blocks: [oTableAttachment]
//         })}),
//         new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("Remark"),
//         subSections: new sap.uxap.ObjectPageSubSection({
//             blocks: [oTableRemark]
//         })}),
//         new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("Time_Log"),
//         subSections: new sap.uxap.ObjectPageSubSection({
//             blocks: [oTableTimeLog]
//         })}),          
//     ]
// });

// var approvedButton = new sap.m.Button({visible:false,text: oBundle.getText("Approved"),icon: "sap-icon://accept",type:"Accept",
// 				        press: function () {setApproval(obj,"1",oDialog);}
// 					});
// var declinedButton = new sap.m.Button({visible:false,text: oBundle.getText("Reject"),icon: "sap-icon://cancel",type:"Reject",
// 				        press: function () {setApproval(obj,"2",oDialog);}
// 					});
                    
// var downloadBtn = new sap.m.Button({ text: oBundle.getText("Download"), 
//     type: sap.m.ButtonType.Emphasized,
//     icon: "sap-icon://download",
//     press: function (e) {
//         if(obj['wo_status']=="4"){
//             var pdf_url = obj['pdf_url'];
//             window.open(pdf_url, "_blank");
//         }else{
//             // generateWOPDFView(obj,oTableTaskView,oTablePartsView,oTableLaborView,oTableAdditionalCost,"1"); 
//         }
//     }
// });

// if(src=="2"){
//     approvedButton.setVisible(true);
//     declinedButton.setVisible(true);
//     downloadBtn.setVisible(false);
// }


//  var oDialog = new sap.m.Dialog({contentWidth:"100%",contentHeight:"100%",draggable:true, resizable: true,
//         title: oBundle.getText("Workorder_Number")+" : "+obj['wo_number'],
//         content: [oPageLayout],
//         buttons: [approvedButton,declinedButton,downloadBtn,editBtn,
// 				new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",
// 				press: function () {oDialog.close();}
// 				})
// 			]
//     }).open();
// }

function setApproval(obj,src,parentDialog,approval_level){

    // let emailTeamDB = new sap.m.Input({ enabled: true });
    let emailTeamDB = new sap.m.MultiInput({
        showValueHelp: true, showSuggestion: true, valueHelpOnly: true,
        fieldWidth: "100%",
        valueHelpRequest: function () {
          getMailNextApproverDialog(1,emailTeamDB,approval_level);
        },
        suggestionItemSelected: function (oEvent) {
          var tokenList = this.getTokens();
          var selectedItem = oEvent.getParameter("selectedItem");
          if (selectedItem) {
            var insertFlag = true;
            for (var i = 0; i < tokenList.length; i++) {
              if (tokenList[i].getKey() == selectedItem.getKey()) {
                insertFlag = false;
              }
            }
            if (tokenList.length == 0 || insertFlag) {
                emailTeamDB.addToken(
                new sap.m.Token({
                  key: selectedItem.getKey(),
                  text: selectedItem.getText(),
                })
              );
              // insetLaborTable(selectedItem.getKey(), selectedItem.getText());
            }
          }
        },
      });
      
    var oFormSendEmail4w =  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("Select Email")),fields: [emailTeamDB]}),
                ]
            }),
        ]
    });




    var approvalLimit = oxmaint_approval_array;
    var woCostEstimation = obj['total_wo_cost'];
    
    let nextBiggerOrEqualIndex = -1;

    for (let ind = 0; ind < approvalLimit.length; ind++) {
        if (parseInt(approvalLimit[ind]) >= woCostEstimation) {
            // console.log(approvalLimit[ind] )
            nextBiggerOrEqualIndex = ind + 1;
            // console.log("Index of next equal or bigger number:", nextBiggerOrEqualIndex);
            break;
        }
    }

    if (nextBiggerOrEqualIndex === -1) {
        nextBiggerOrEqualIndex = 5;
        // console.log("No number in the array is equal to or bigger than the estimation.");
    }
    

    var comment = new sap.m.TextArea({width:"100%",value: obj['approved_remark'],height:"70px",rows : 2, 
            wrapping : sap.ui.core.Wrapping.on,
            liveChange: function (oEvent) {
                var sText = oEvent.getParameter('value');
                //var parent = oEvent.getSource().getParent();
                declinedButton.setEnabled(sText.length > 0);
        }});

    var approved_by = operatedID;
    var approved_date = getIndonesianTime();
      

    let approved = '0';
    let wo_status = 'Pending Approval';
    if(approval_level == "Approval"+nextBiggerOrEqualIndex){
        approved = '1';
        wo_status = 'Open';
    }
    var approvedButton = new sap.m.Button({visible:false,text: oBundle.getText("Approved"),icon: "sap-icon://accept",type:"Accept",
			press: function () {
                var approved_remark = comment.getValue();
                parentDialog.close();
                // oDialog.close();



                    const selectedWorkorders = [{
                        id: obj.id,
                        wo_number: obj.wo_number,
                        wo_status: obj.wo_status,
                        total_wo_cost: parseFloat(obj.total_wo_cost)
                      }];
                    
                    const selectedWorkordersEmail = [{
                            license_number: obj.license_number,
                            wo_number: obj.wo_number,
                            wo_title: obj.wo_title,
                            created_date: obj.created_date,
                            ws_group_name: obj.ws_group_name,
                            workshop_name: obj.workshop_name,
                            city: obj.city,
                            rental_company_name: obj.rental_company_name,
                            leasing_company_name: obj.leasing_company_name
                    }];
    

                    const tokens = emailTeamDB.getTokens();
                    const selectedApprovers = tokens.length > 0
                        ? tokens.map(token => token.getKey()).join(",")
                        : '';


                    const amount_value = sessionStorage.getItem("oxmaint_approval_amount");
                    const approval_value = sessionStorage.getItem("oxmaint_approval_level");
    
                    if(selectedWorkorders.length <= 0){
                        sap.m.MessageToast.show("Select a workorder to approve.");
                        return
                    }



                const UpdateItem = {
                    amount_value,
                    approval_value,
                    selectedWorkorders,
                    selectedApprovers,
                    selectedWorkordersEmail,
                    approved_remark
                };

                workorderBulkApproval(UpdateItem,oDialog);
                return

                if(approved == 1 && approval_level != "Approval5"){ insertStatus("Open");
                }else if(approved == 0){ insertStatus("Approved"); }
                
                function insertStatus(status) {
                    Car_Workorder_Status.insert({
                        master_email: emailUser,
                        wo_number: obj['wo_number'],
                        wo_id: obj['id'],
                        wo_status: status,
                        changed_date: approved_date,
                        changed_by: approved_by,
                        note: approved_remark
                    }).done(function () {
                        // Optional success handler
                    });
                };

                if(approval_level == 'Approval1'){
                    Car_Workorder.update({
                        id:obj['id'],approval1:'1', approver1:approved_by, approval1_date:approved_date,
                        approved:approved, wo_status:wo_status
                    }).done(function () {
                        getPendingWorkorder();
                    }); 
                }else if (approval_level == 'Approval2'){
                    Car_Workorder.update({
                        id:obj['id'],approval2:'1', approver1:approved_by, approval2_date:approved_date,
                        approved:approved, wo_status:wo_status
                    }).done(function () {
                        getPendingWorkorder();
                    }); 
                }else if (approval_level == 'Approval3'){
                    Car_Workorder.update({
                        id:obj['id'],approval3:'1', approver3:approved_by, approval3_date:approved_date,
                        approved:approved, wo_status:wo_status
                    }).done(function () {
                        getPendingWorkorder();
                    }); 
                }else if (approval_level == 'Approval4'){
                    if(portal_type_flag == '2W'){
                        Car_Workorder.update({
                            id:obj['id'],approval5:'1', approver5:approved_by, approval5_date:approved_date,
                            approved:"1", wo_status:"Open"
                        }).done(function () {
                            Car_Workorder_Status.insert({ master_email:emailUser, wo_number:obj['wo_number'], wo_id: obj['id'], wo_status: "Open", 
                                changed_date: approved_date, changed_by: approved_by, note:approved_remark
                            }).done(function () { });
                            getPendingWorkorder();
                        }); 
                    }else{
                        Car_Workorder.update({
                            id:obj['id'], approval4:'1',approver4:approved_by, approval4_date:approved_date,
                            approved:approved, wo_status:wo_status
                        }).done(function () {
                            getPendingWorkorder();
                        }); 
                    }
                }else if (approval_level == 'Approval5'){
                    Car_Workorder.update({
                        id:obj['id'],approval5:'1', approver5:approved_by, approval5_date:approved_date,
                        approved:"1", wo_status:"Open"
                    }).done(function () {
                        Car_Workorder_Status.insert({ master_email:emailUser, wo_number:obj['wo_number'], wo_id: obj['id'], wo_status: "Open", 
                            changed_date: approved_date, changed_by: approved_by, note:approved_remark
                        }).done(function () { });
                        getPendingWorkorder();
                    }); 

                }

               

                let email = "";
                let emailApprovalWoTokenList = emailTeamDB.getTokens();

                for (var j = 0; j < emailApprovalWoTokenList.length; j++) {
                if (email === "") {
                    email = emailApprovalWoTokenList[j].getKey();
                }
                }
                if(nullCheckAll(email)){
                    sendEmailToNextApprover(email,obj);
                }
               
        }});
    var declinedButton = new sap.m.Button({enabled:false,visible:false,text: oBundle.getText("Reject"),icon: "sap-icon://cancel",type:"Reject",
                press: function () {
                    
                var approved_remark = comment.getValue();
                if (textFieldValidation(comment, approved_remark)) { return; }

                parentDialog.close();
                oDialog.close();
                Car_Workorder_Status.insert({master_email:emailUser, wo_number:obj['wo_number'], wo_id: obj['id'], wo_status: "Reject",
                    changed_date: approved_date, changed_by: approved_by, note:approved_remark
                }).done(function () { });

                if(approval_level == 'Approval1'){
                    Car_Workorder.update({
                        id:obj['id'],approval1:'0', approver1:approved_by, approval1_date:approved_date,
                        approved:"0", wo_status:"Reject", approved_remark1:approved_remark,
                    }).done(function () {
                        getPendingWorkorder();
                    }); 
                }else if (approval_level == 'Approval2'){
                    Car_Workorder.update({
                        id:obj['id'],approval2:'0', approver1:approved_by, approval2_date:approved_date,
                        approved:"0", wo_status:"Reject", approved_remark2:approved_remark
                    }).done(function () {
                        getPendingWorkorder();
                    }); 
                }else if (approval_level == 'Approval3'){
                    Car_Workorder.update({
                        id:obj['id'],approval3:'0', approver3:approved_by, approval3_date:approved_date,
                        approved:"0", wo_status:"Reject", approved_remark3:approved_remark
                    }).done(function () {
                        getPendingWorkorder();
                    }); 
                }else if (approval_level == 'Approval4'){
                    Car_Workorder.update({
                        id:obj['id'], approval4:'0',approver4:approved_by, approval4_date:approved_date,
                        approved:"0", wo_status:"Reject", approved_remark4:approved_remark
                    }).done(function () {
                        getPendingWorkorder();
                    }); 
                }else if (approval_level == 'Approval5'){
                    Car_Workorder.update({
                        id:obj['id'],approval5:'0', approver5:approved_by, approval5_date:approved_date,
                        approved:"0", wo_status:"Reject", approved_remark5:approved_remark
                    }).done(function () {
                        getPendingWorkorder();
                    }); 

                }


                getCompletedWorkorder();
                // Car_Workorder.update({id:obj['id'],approved_by:approved_by,approved_date:approved_date,wo_status:"5",
                //     approved_remark:approved_remark}).done(function () {
                //         funGetWorkorder();
                //         funWoRequest();
                // }); 
        }});

    if(src=="1"){
        comment.setPlaceholder("Put your comment here");
        approvedButton.setVisible(true);
        declinedButton.setVisible(false);
        oFormSendEmail4w.setVisible(true);
    }else{
        comment.setPlaceholder("Put your comment here (required)");
        approvedButton.setVisible(false);
        declinedButton.setVisible(true);
        oFormSendEmail4w.setVisible(false);
    }

    var oDialog = new sap.m.Dialog({contentWidth:"40%",draggable:true, resizable: true,
            title: oBundle.getText("Workorder_Number")+" : "+obj['wo_number'],
            content: [oFormSendEmail4w,comment],
            buttons: [approvedButton,declinedButton,
					new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",
				    press: function () {oDialog.close();}
					})
				]
    }).open();

}

function generateWOPDFView(obj,oTableTaskView,oTablePartsView,oTableLaborView,oTableAdditionalCost,src){

    var task_name = "";
    var task_status = "";
    var task_type = "";
    var task_note = "";
    var task_assigned = "";

     var Tasklist = oTableTaskView.getItems();
     for (var i = 0; i < Tasklist.length; i++) {
            var oContext = Tasklist[i].getBindingContext().getObject();   
             task_name = task_name + oContext.task_name + "^";
             task_type = task_type + oContext.task_type + "^";
             task_note = task_note + oContext.workorder_note + "^";
             task_assigned = task_assigned + oContext.assigned_name + "^";
              if (src == "2") {
                 task_status = task_status + oBundle.getText("Complete") + "^";
             }else{
                 task_status = task_status + getTaskStatusText(oContext.task_status) + "^";
             }   
        }  

    var parts_number = "";
    var parts_name = "";
    var parts_qty = "";
    var parts_total_cost = "";
    var parts_note = "";

     var partslist = oTablePartsView.getItems();
     for (var i = 0; i < partslist.length; i++) {
            var oContext = partslist[i].getBindingContext().getObject();   
             parts_number = parts_number + oContext.part_number + "^";
             parts_name = parts_name + oContext.parts_name + "^";
             parts_qty = parts_qty + oContext.parts_qty+" "+oContext.parts_unit + "^";
             parts_total_cost = parts_total_cost + oContext.total_cost + "^";
             parts_note = parts_note + oContext.note + "^";    
        }  

    var labor_name = "";
    var labor_code = "";
    var labor_rate = "";
    var labor_time = "";
    var labor_cost = "";
    var labor_note = "";
    
     var laborlist = oTableLaborView.getItems();
     for (var i = 0; i < laborlist.length; i++) {
            var oContext = laborlist[i].getBindingContext().getObject();   
             labor_name = labor_name + oContext.labor_name + "^";
             labor_code = labor_code + oContext.labor_code + "^";
             labor_rate = labor_rate + oContext.labor_rate + "^";
             labor_cost = labor_cost + oContext.labor_cost + "^";
             labor_note = labor_note + oContext.labor_note + "^";

             var time = oContext.labor_time;
             if (nullCheck(time)) {
                labor_time = labor_time + getHourMinutes(time) + "^";  
             } else {
                labor_time = labor_time + "" + "^";  
             }  
        }  
     

    var description = "";
    var additional_cost = "";
 
     var additionallist = oTableAdditionalCost.getItems();
     for (var i = 0; i < additionallist.length; i++) {
            var oContext = additionallist[i].getBindingContext().getObject();   
             description = description + oContext.description + "^";
             additional_cost = additional_cost + oContext.cost + "^";
      }  

     task_name = task_name.slice(0, -1);
     task_status = task_status.slice(0, -1);
     task_type = task_type.slice(0, -1);
     task_assigned = task_assigned.slice(0, -1);
     task_note = task_note.slice(0, -1);
     
     parts_number = parts_number.slice(0, -1);
     parts_name = parts_name.slice(0, -1);
     parts_qty = parts_qty.slice(0, -1);
     parts_total_cost = parts_total_cost.slice(0, -1);
     parts_note = parts_note.slice(0, -1);

     labor_name = labor_name.slice(0, -1);
     labor_code = labor_code.slice(0, -1);
     labor_rate = labor_rate.slice(0, -1);
     labor_time = labor_time.slice(0, -1);
     labor_cost = labor_cost.slice(0, -1);
     labor_note = labor_note.slice(0, -1);

     description = description.slice(0, -1);
     additional_cost = additional_cost.slice(0, -1);
     labor_note = labor_note.slice(0, -1);


    var assigned_name = obj['assigned_name'];
    if(assigned_name != null){
       assigned_name = assigned_name.replace(/\^/g, ", ");
    }
    var link_inspection = obj['link_inspection'];
    if(link_inspection != null){
       link_inspection = link_inspection.replace(/\^/g, ", ");
    }
    var link_workorder = obj['link_workorder'];
    if(link_workorder != null){
       link_workorder = link_workorder.replace(/\^/g, ", ");
    }
    
    var total_time = getHourMinutes(obj['total_time']);

    busyDialog.open();

    var wo_url = "https://oxmaint.com/pdf/pdf2_en/workorder.php";
     if(languageCode == 'PT' || languageCode == 'pt'){
        wo_url = "https://oxmaint.com/pdf/pdf2_pt/workorder.php";
     }else if(languageCode == 'ES' || languageCode == 'es'){
        wo_url = "https://oxmaint.com/pdf/pdf2_es/workorder.php";
     }else if(languageCode == 'JA' || languageCode == 'ja'){
        wo_url = "https://oxmaint.com/pdf/pdf2_ja/workorder.php";
     }else{
        wo_url = "https://oxmaint.com/pdf/pdf2_en/workorder.php";
     }
    

     $.ajax({
         type: "POST",
         url: wo_url,
         data: {
             "logoUrl": sessionStorage.getItem('oxmaint_logo'),
             "email": obj['master_email'],
             "woNumber": obj['wo_number'],
             "wo_title": obj['wo_title'],
             "woDate": obj['created_date'],
             
             "woStatus": getStatusText(obj['wo_status']),
             "woPriority": getPriorityText(obj['wo_priority']),
             "wo_type": obj['wo_type'],
             "createdBy": obj['created_by'],

             "woAssign": assigned_name,
             "link_inspection": link_inspection,
             "link_workorder": link_workorder,

             "start_date": obj['start_date'],
             "due_date": obj['due_date'],
             "completion_date": obj['completion_date'],

             "estimated_time": obj['estimated_time'],
             "total_time": total_time,

             "vehicleNumber": obj['vehicle_number'],
             "vehicleName": obj['vehicle_name'],
             "vehicle_model": obj['vehicle_model'],
             "meterReading": obj['meter_reading'],

             "materialCost": obj['total_parts_cost'],
             "laborCharge": obj['total_labor_cost'],
             "additional_total_cost": obj['additional_cost'],
             "tax": obj['tax'],
             "tax_value": obj['tax_value'],
             "totalCost": obj['total_wo_cost'],
             "estimated_cost": obj['estimated_cost'],

             "memo": obj['wo_memo'],
             "blob": obj['pdf_name'] + ".pdf",

             "task_name": task_name,
             "task_status": task_status,
             "task_type": task_type,
             "task_note": task_note, 
             "task_assigned": task_assigned,

             "parts_number": parts_number,
             "parts_name": parts_name,
             "parts_qty": parts_qty,
             "parts_total_cost": parts_total_cost,
             "parts_note": parts_note,

             "labor_name": labor_name,
             "labor_code": labor_code,
             "labor_rate": labor_rate,
             "labor_time": labor_time,
             "labor_cost": labor_cost,
             "labor_note": labor_note,

             "description": description,
             "additional_cost": additional_cost,

             "customFeildValue1": obj['custom1'],
             "customFeildValue2": obj['custom2'],
             "customFeildValue3": obj['custom3'],
             "customFeildValue4": obj['custom4'],
             "customFeildValue5": obj['custom5'],

             "customFeildFlag1": wo_flag1,
             "customFeildFlag2": wo_flag2,
             "customFeildFlag3": wo_flag3,
             "customFeildFlag4": wo_flag4,
             "customFeildFlag5": wo_flag5,

             "customFeildName1": wo_field1,
             "customFeildName2": wo_field2,
             "customFeildName3": wo_field3,
             "customFeildName4": wo_field4,
             "customFeildName5": wo_field5,
             "subscription":oxmaint_subscription
         },
         success: function (data) {
             busyDialog.close();

             if (src == "1") {
                 var pdf_url = obj['pdf_url'];
                 window.open(pdf_url, "_blank");
             }else {
                 oAppWorkOrder.backToTop();
                 sap.m.MessageToast.show("Workorder Completed", { my: "center center", at: "center center"});
             }   
         }
     });
}

function sendEmailToNextApprover(email,obj){
    $.ajax({
        url: `${jrs_go_api_url_name}/integration/email/sendWorkorderItems`,
        method: 'POST',
        headers: {
            'X-API-Key': jrs_go_api_key,
            'Content-Type': 'application/json'
        },
        data: JSON.stringify({
            "to": email,
            "workorder_items":obj 
            // [
            //     {
            //     "license_number": obj['license_number'],
            //     "wo_number": obj['wo_number'],
            //     "wo_title": obj['wo_title'],
            //     "created_date":  obj['created_date'],
            //     "ws_group_name":  obj['ws_group_name'],
            //     "workshop_name":  obj['workshop_name'],
            //     "city":  obj['city'],
            //     "rental_company_name":  obj['rental_company_name'],
            //     "leasing_company_name":  obj['leasing_company_name']
            //     }
            // ]
        }),
        success: function(response) {
            busyDialog.close();
            sap.m.MessageToast.show("Email sent successfully!");
        },
        error: function(xhr, status, error) {
            busyDialog.close();
            console.error("Email sending failed:", error);
            sap.m.MessageBox.error(
                xhr.responseJSON?.message || 
                "Failed to send email. Please try again."
            );
        }
    });

}


function getMailNextApproverDialog(src, InputValue,approval_level) {
    console.log(approval_level)
    var oSelectDialog = new sap.m.SelectDialog({
      contentWidth: "50%", draggable: true,
      resizable: true, rememberSelections: true, multiSelect: false,
      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( "user_name", sap.ui.model.FilterOperator.Contains, sSearchValue),
            new sap.ui.model.Filter( "email", sap.ui.model.FilterOperator.Contains, sSearchValue),
            new sap.ui.model.Filter( "user_id", sap.ui.model.FilterOperator.Contains, sSearchValue),
            new sap.ui.model.Filter( "role", sap.ui.model.FilterOperator.Contains, sSearchValue),
          ];
          var filterObj = new sap.ui.model.Filter(oFilters, false);
          oBinding.filter(filterObj);
        } else {
          oBinding.filter([]);
        }
      },
      confirm: function (oEvent) {
       
          InputValue.removeAllTokens();
          var tokenList = InputValue.getTokens();
          var aContexts = oEvent.getParameter("selectedContexts");
          if (aContexts && aContexts.length) {
            aContexts.map(function (oContext) {
              var name = oContext.getObject()["user_name"];
              var emailId = oContext.getObject()["email"];
  
              var insertFlag = true;
              for (var j = 0; j < tokenList.length; j++) {
                if (tokenList[j].getKey() == emailId) {
                  insertFlag = false;
                }
              }
              if (tokenList.length == 0 || insertFlag) {
                InputValue.addToken( new sap.m.Token({ key: emailId, text: name }));
              }
            });
          }
      },
    });
  
    
    oSelectDialog._getOkButton().setText(oBundle.getText("Select"));
    oSelectDialog.setTitle(oBundle.getText("Select_Next_Approver_Mail"));
    
  
    var oItemTemplate = new sap.m.StandardListItem({
      title: "{user_name}",
      description: "{email}",
      icon: "{image}",
      type: "Active",
      info: {
        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");
          }
        },
      },
    });
  
    var result = [];
  

    var nextApprover = "G4";
    if(approval_level == "Approval1"){ nextApprover = "G4";
    }else if(approval_level == "Approval2"){ nextApprover = "G5";
    }else if(approval_level == "Approval3"){ nextApprover = "G6";
    }else if(approval_level == "Approval4"){ nextApprover = "G7";
    }else if(approval_level == "Approval0"){ nextApprover = "G3";
    }else{
        nextApprover = "G9"
    }

    result = team4WJSONData.filter(function (obj, index) {
        return obj.approval_level == nextApprover;
    });
   
    result.sort(function (a, b) {
      a = a.user_name.toLowerCase();
      b = b.user_name.toLowerCase();
      return a < b ? -1 : a > b ? 1 : 0;
    });
  
    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ modelData: result });
    oSelectDialog.setModel(oModel);
    oSelectDialog.bindAggregation("items", "/modelData", oItemTemplate);
    oSelectDialog.open();
  
    oSelectDialog._getCancelButton().setText(oBundle.getText("Cancel"));
  };


function bulkCheckWorkorderApprove(dataArray,approval_level_code) {
    const oTableApprove = new sap.m.Table({
        growing: true,
        growingThreshold: 25,
        mode: sap.m.ListMode.MultiSelect,
        sticky: [sap.m.Sticky.ColumnHeaders, sap.m.Sticky.HeaderToolbar],
        noDataText: oBundle.getText("No_Data"),
        columns: [
            new sap.m.Column({ width: "120px", header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Workorder_Number"), design: sap.m.LabelDesign.Bold }), sortIndicator: "Descending" }),
            new sap.m.Column({ width: "130px", header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Workorder_Title"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Desktop", popinDisplay: "Inline", demandPopin: true }),
            new sap.m.Column({ width: "130px", header: new sap.m.Label({ wrapping: true, text: oBundle.getText("License_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_Number"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true, hAlign: "Left", width: "120px" }),
            new sap.m.Column({ header: new sap.m.Label({wrapping: true, text: oBundle.getText("Workshop_Name"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true, hAlign: "Left", width: "120px" }),
            new sap.m.Column({ header: new sap.m.Label({wrapping: true, text: oBundle.getText("Workshop_Group_Number"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true, hAlign: "Left", width: "120px" }),
            new sap.m.Column({ header: new sap.m.Label({wrapping: true, text: oBundle.getText("Workshop_Group_Name"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true, hAlign: "Left", width: "120px" }),
        ],
        headerToolbar: new sap.m.OverflowToolbar({
            content: [
                new sap.m.ToolbarSpacer(),
                new sap.m.SearchField({
                    width: "300px",
                    placeholder: oBundle.getText("Search"),
                    liveChange: function (oEvent) {

                        var oBinding = oTableApprove.getBinding("items");
                        var searchStr = this.getValue();
                        if (oBinding) {
                            var oFilters = [
                                new sap.ui.model.Filter("ws_group_name", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("ws_group_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("license_number", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("workshop_number", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("wo_number", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("wo_title", sap.ui.model.FilterOperator.Contains, searchStr),
                            ];
                            var filterObj = new sap.ui.model.Filter(oFilters, false);
                            oBinding.filter(filterObj);
                        } else {
                            oBinding.filter([]);
                        }
                    }
                }),
                new sap.m.Button({
                    icon: "sap-icon://filter",
                    type: "Transparent",
                    press: function() {
                        clearFiltersSupplierInv();
                        populateSuppInvFilterDropdowns();
                        oSupplierInvFilterDialog.open();
                    }
                })
            ]
        })
    });

    const oItemTemplate = new sap.m.ColumnListItem({
        cells: [
            new sap.m.Text({ wrapping: true, text: "{wo_number}" }),
            new sap.m.Text({ wrapping: true, text: "{wo_title}" }),
            new sap.m.Text({ wrapping: true, text: "{license_number}" }),
            new sap.m.Text({ wrapping: true, text: "{workshop_number}" }),
            new sap.m.Text({ wrapping: true, text: "{workshop_name}" }),
            new sap.m.Text({ wrapping: true, text: "{ws_group_number}" }),
            new sap.m.Text({ wrapping: true, text: "{ws_group_name}" }),
        ]
    });

    var oSupplierInvFilterDialog = new sap.m.Dialog({
        title: "Multi Filter Workorder",
        contentWidth: "40%",
        content: [
            new sap.m.VBox({
                width: "100%",
                items: [
                    new sap.m.Label({ text: "Workshop Group:", design: "Bold", required: false }),
                    new sap.m.ComboBox({ 
                        width: "94%",
                        placeholder: "Select Workshop Group"
                    }),
                    
                    new sap.m.Label({ text: "Workshop:", design: "Bold", required: false }),
                    new sap.m.ComboBox({ 
                        width: "94%",
                        placeholder: "Select Workshop Group"
                    }),
                    
                    new sap.m.Label({ text: "License Number:", design: "Bold", required: false }),
                    new sap.m.ComboBox({ 
                        width: "94%",
                        placeholder: "Select License Number"
                    }),
                    
                    new sap.m.Label({ text: "City:", design: "Bold", required: false }),
                    new sap.m.ComboBox({ 
                        width: "94%",
                        placeholder: "Select City"
                    }),
                    
                    new sap.m.Label({ text: "Rental Company:", design: "Bold", required: false }),
                    new sap.m.ComboBox({ 
                        width: "94%",
                        placeholder: "Select Rental Company"
                    }),
                    
                    new sap.m.Label({ text: "Leasing Company:", design: "Bold", required: false }),
                    new sap.m.ComboBox({ 
                        width: "94%",
                        placeholder: "Select Leasing Company"
                    }),
                    new sap.m.Label({ text: "Verificator:", design: "Bold", required: false }),
                    new sap.m.ComboBox({ 
                        width: "94%",
                        placeholder: "Select Verificator Name"
                    }),
                ]
            }).addStyleClass("sapUiSmallMargin")
        ],
        buttons: [
            new sap.m.Button({
                icon: "sap-icon://clear-filter",
                text: "Clear Filter",
                press: function() {
                    clearFiltersSupplierInv();
                }
            }),
            new sap.m.Button({
                icon: "sap-icon://decline",
                text: "Cancel",
                press: function() {
                    oSupplierInvFilterDialog.close();
                }
            }),
            new sap.m.Button({
                icon: "sap-icon://filter",
                text: "Apply Filter",
                type: "Emphasized",
                press: function() {
                    var aFilters = [];
                    
                    // Get ComboBoxes (only first two fields now)
                    var aComboBoxes = oSupplierInvFilterDialog.getContent()[0].getItems().filter(function(item) {
                        return item instanceof sap.m.ComboBox;
                    });
                    
                    
                    // Add filters for ComboBox fields (Workshop Group and License Number)
                    var comboBoxFields = ["ws_group_name","workshop_name", "license_number","city","rental_company_name","leasing_company_name","verified_by"];
                    aComboBoxes.forEach(function(oComboBox, index) {
                        var sValue = oComboBox.getSelectedKey();
                        if (sValue) {
                            aFilters.push(new sap.ui.model.Filter(
                                comboBoxFields[index],
                                sap.ui.model.FilterOperator.EQ,
                                sValue
                            ));
                        }
                    });
                    
                    
                    var oBinding = oTableApprove.getBinding("items");
                    if (oBinding) {
                        if (aFilters.length > 0) {
                            var oCombinedFilter = new sap.ui.model.Filter({
                                filters: aFilters,
                                and: true
                            });
                            oBinding.filter(oCombinedFilter);
                        } else {
                            oBinding.filter([]);
                        }
                    }
                    
                    oSupplierInvFilterDialog.close();
                }
            })
        ]
    }).addStyleClass("sapUiSizeCompact");
    // Add this function to populate filter dropdowns
    function populateSuppInvFilterDropdowns() {
        try {
            var oModel = oTableApprove.getModel();
            if (!oModel) return;
            
            var aData = oModel.getProperty("/modelData");
            if (!aData) return;

            // Get unique workshop groups
            var uniqueWorkshopGroups = [...new Set(aData
                .map(item => item.ws_group_name)
                .filter(item => item && item.trim() !== "")
            )].sort();
            
            // Get unique workshop Name
            var uniqueWorkshopName = [...new Set(aData
                .map(item => item.workshop_name)
                .filter(item => item && item.trim() !== "")
            )].sort();

            // Get unique license plates
            var uniqueLicensePlates = [...new Set(aData
                .map(item => item.license_number)
                .filter(item => item && item.trim() !== "")
            )].sort();
        
            // Get unique City
            var uniqueCityName = [...new Set(aData
                .map(item => item.city)
                .filter(item => item && item.trim() !== "")
            )].sort();
             
            // Get unique Rental COmpany Name
            var uniqueRenatalCompany = [...new Set(aData
                .map(item => item.rental_company_name)
                .filter(item => item && item.trim() !== "")
            )].sort();
        
            // Get unique  leasing COmpany Name
            var uniqueLeasingCompany = [...new Set(aData
                .map(item => item.leasing_company_name)
                .filter(item => item && item.trim() !== "")
            )].sort();
           
            // Get unique verified name
            var uniqueVerifiedBy = [...new Set(aData
                .map(item => item.verified_by)
                .filter(item => item && item.trim() !== "")
            )].sort();
        
            // Get unique Supplier invoice number
            // var uniqueSupplierInvoiceNumber = [...new Set(aData
            //     .map(item => item.supplier_invoice_number)
            //     .filter(item => item && item.trim() !== "")
            // )].sort();

            // Get the ComboBoxes
            var comboBoxes = oSupplierInvFilterDialog.getContent()[0].getItems()
                .filter(item => item instanceof sap.m.ComboBox);
            
            var oWorkshopGroupComboBox = comboBoxes[0];
            var oWorkshopComboBox = comboBoxes[1];
            var oLicensePlateComboBox = comboBoxes[2];
            // var oInvoiceNumberComboBox = comboBoxes[3];
            var oCityComboBox = comboBoxes[3];
            var oRentalComboBox = comboBoxes[4];
            var oLeasingComboBox = comboBoxes[5];
            var oVerifiedComboBox = comboBoxes[6];

            // Clear existing items
            oWorkshopGroupComboBox.removeAllItems();
            oWorkshopComboBox.removeAllItems();
            oLicensePlateComboBox.removeAllItems();
            // oInvoiceNumberComboBox.removeAllItems();
            oCityComboBox.removeAllItems();
            oRentalComboBox.removeAllItems();
            oLeasingComboBox.removeAllItems();
            oVerifiedComboBox.removeAllItems();


            // Add items to Workshop Group ComboBox
            uniqueWorkshopGroups.forEach(function(group) {
                oWorkshopGroupComboBox.addItem(new sap.ui.core.Item({
                    key: group,
                    text: group
                }));
            });
           
            uniqueWorkshopName.forEach(function(group) {
                oWorkshopComboBox.addItem(new sap.ui.core.Item({
                    key: group,
                    text: group
                }));
            });

            // Add items to License Plate ComboBox
            uniqueLicensePlates.forEach(function(group) {
                oLicensePlateComboBox.addItem(new sap.ui.core.Item({
                    key: group,
                    text: group
                }));
            });
            
            uniqueCityName.forEach(function(group) {
                oCityComboBox.addItem(new sap.ui.core.Item({
                    key: group,
                    text: group
                }));
            });
            uniqueRenatalCompany.forEach(function(group) {
                oRentalComboBox.addItem(new sap.ui.core.Item({
                    key: group,
                    text: group
                }));
            });
            uniqueLeasingCompany.forEach(function(group) {
                oLeasingComboBox.addItem(new sap.ui.core.Item({
                    key: group,
                    text: group
                }));
            });
       
            uniqueVerifiedBy.forEach(function(group) {
                oVerifiedComboBox.addItem(new sap.ui.core.Item({
                    key: group,
                    text: group
                }));
            });
        


        } catch (error) {
            console.error("Error populating filter dropdowns:", error);
        }
    };
    // Add this function to clear filters
    function clearFiltersSupplierInv() {
        try {
            var aComboBoxes = oSupplierInvFilterDialog.getContent()[0].getItems().filter(function(item) {
                return item instanceof sap.m.ComboBox;
            });
            
            // Clear ComboBoxes
            aComboBoxes.forEach(function(oComboBox) {
                oComboBox.setSelectedKey("");
            });
            
            
            // Clear table filters
            var oBinding = oTableApprove.getBinding("items");
            if (oBinding) {
                oBinding.filter([]);
            }
            sap.m.MessageToast.show("All filters have been cleared");
        } catch (error) {
            console.error("Error clearing filters:", error);
            sap.m.MessageBox.error("Error clearing filters. Please try again.");
        }
    }



    // const oDialog = new sap.m.Dialog({
    //     title: oBundle.getText("Approve_Workorders") +" "+ approval_level_code,
    //     contentWidth: "100%",
    //     contentHeight: "50%",
    //     resizable: true,
    //     draggable: true,
    //     content: [oTableApprove],
    //     buttons: [
    //         new sap.m.Button({
    //             text: oBundle.getText("Approve_Selected"),
    //             type: "Emphasized",
    //             press: function () {
    //                 const selectedItems = oTableApprove.getSelectedItems();
    //                 // const selectedWorkorders = selectedItems.map(item => item.getBindingContext().getObject());
    //                 const selectedWorkorders = selectedItems.map(item => {
    //                     const data = item.getBindingContext().getObject();
    //                     return {
    //                         id: data.id,
    //                         wo_number: data.wo_number,
    //                         wo_status: data.wo_status,
    //                         total_wo_cost: data.total_wo_cost
    //                     };
    //                 });
                    
                    
    //                 // Replace this with actual approval logic
    //                 var amount_value =  sessionStorage.getItem("oxmaint_approval_amount");
    //                 var approval_value =  sessionStorage.getItem("oxmaint_approval_level");
    //                 console.log("Approved Workorders:", selectedWorkorders);
    //                 var UpdateItem = {
    //                     amount_value,
    //                     approval_value,
    //                     selectedWorkorders,
    //                 }
    //                 // console.log(UpdateItem)
    //                 workorderBulkApproval(UpdateItem)
    //                 sap.m.MessageToast.show(`${selectedWorkorders.length} workorders approved.`);

    //                 oDialog.close();
    //             }
    //         }),
    //         new sap.m.Button({
    //             text: oBundle.getText("Cancel"),
    //             icon: "sap-icon://decline",
    //             press: function () {
    //                 oDialog.close();
    //             }
    //         })
    //     ]
    // });

    var approval_level = '';
    if(approval_level_code == 'G3'){approval_level = 'Approval1';}
    else if(approval_level_code == 'G4'){approval_level = 'Approval2';}
    else if(approval_level_code == 'G5'){approval_level = 'Approval3';}
    else if(approval_level_code == 'G6'){approval_level = 'Approval4';}
    else if(approval_level_code == 'G7'){approval_level = 'Approval5';}

    let emailTeamDB = new sap.m.MultiInput({
        showValueHelp: true,
        showSuggestion: true,
        valueHelpOnly: true,
        fieldWidth: "100%",
        placeholder: "Select next approver...",
        valueHelpRequest: function () {
            getMailNextApproverDialog(1, emailTeamDB, approval_level);
        },
        suggestionItemSelected: function (oEvent) {
            var tokenList = this.getTokens();
            var selectedItem = oEvent.getParameter("selectedItem");
            if (selectedItem) {
                var insertFlag = true;
                for (var i = 0; i < tokenList.length; i++) {
                    if (tokenList[i].getKey() === selectedItem.getKey()) {
                        insertFlag = false;
                    }
                }
                if (tokenList.length === 0 || insertFlag) {
                    emailTeamDB.addToken(
                        new sap.m.Token({
                            key: selectedItem.getKey(),
                            text: selectedItem.getText(),
                        })
                    );
                }
            }
        }
    });
    var commentBulkApprove = new sap.m.TextArea({width:"100%",value:"",height:"70px",rows : 2, 
        wrapping : sap.ui.core.Wrapping.on,
        placeholder:"Enter Remark",
        liveChange: function (oEvent) {
            var sText = oEvent.getParameter('value');
            //var parent = oEvent.getSource().getParent();
            // verifyRejectBtn.setEnabled(sText.length > 0);
    }});
    const oDialog = new sap.m.Dialog({
        title: oBundle.getText("Approve_Workorders") + " " + approval_level_code,
        contentWidth: "70%",
        contentHeight: "70%",
        resizable: true,
        draggable: true,
        content: [
            new sap.m.VBox({
                height:"100%",
                items: [
                    // Fixed Header Area
                    new sap.m.Text({ 
                        text: "Select Next Approver(s):", 
                        wrapping: true 
                    }),
                    emailTeamDB,
                    new sap.m.Text({ 
                        text: "Remark:", 
                        wrapping: true 
                    }),
                    commentBulkApprove,
                    
                    // Scrollable Table Area
                    new sap.m.ScrollContainer({
                        height: "100%",
                        vertical: true,
                        horizontal: false,
                        content: [
                            oTableApprove
                        ]
                    }).addStyleClass("sapUiSmallMarginTop")
                ],
                fitContainer: true,
                renderType: "Bare"
            }).addStyleClass("sapUiContentPadding")
        ],
        buttons: [
            new sap.m.Button({
                text: oBundle.getText("Approve_Selected"),
                type: "Emphasized",
                press: function () {
                    const selectedItems = oTableApprove.getSelectedItems();
                    const selectedWorkorders = selectedItems.map(item => {
                        const data = item.getBindingContext().getObject();
                        return {
                            id: data.id,
                            wo_number: data.wo_number,
                            wo_status: data.wo_status,
                            total_wo_cost: parseFloat(data.total_wo_cost)
                        };
                    });
    
                    const selectedWorkordersEmail = selectedItems.map(item => {
                        const data = item.getBindingContext().getObject();
                        return {
                            license_number: data.license_number,
                            wo_number: data.wo_number,
                            wo_title: data.wo_title,
                            created_date: data.created_date,
                            ws_group_name: data.ws_group_name,
                            workshop_name: data.workshop_name,
                            city: data.city,
                            rental_company_name: data.rental_company_name,
                            leasing_company_name: data.leasing_company_name
                        };
                    });
                    // const tokens = emailTeamDB.getTokens();
                    // const selectedApprovers = tokens.map(token => ({
                    //     key: token.getKey(),
                    //     name: token.getText()
                    // }));
    
                    const tokens = emailTeamDB.getTokens();
                    const selectedApprovers = tokens.length > 0
                        ? tokens.map(token => token.getKey()).join(",")
                        : '';


                    const amount_value = sessionStorage.getItem("oxmaint_approval_amount");
                    const approval_value = sessionStorage.getItem("oxmaint_approval_level");
    
                    if(selectedWorkorders.length <= 0){
                        sap.m.MessageToast.show("Select a workorder to approve.");
                        return
                    }
                    const UpdateItem = {
                        amount_value,
                        approval_value,
                        selectedWorkorders,
                        selectedApprovers,
                        selectedWorkordersEmail,
                        approved_remark
                    };
    
                    workorderBulkApproval(UpdateItem,oDialog);
                }
            }),
            new sap.m.Button({
                text: oBundle.getText("Cancel"),
                icon: "sap-icon://decline",
                press: function () {
                    oDialog.close();
                }
            })
        ]
    });
    


    const oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ modelData: dataArray });
    oTableApprove.setModel(oModel);
    oTableApprove.bindItems("/modelData", oItemTemplate);

    oDialog.open();
}
