function workorderViewGrab(obj,src,approval_level){
    
    
    var editBtn = new sap.m.Button({ text: oBundle.getText("Edit"), 
        visible:false,
        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_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(obj['wo_status']);

   
          
    
    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"))}));
    oTablePartsView.addColumn(new sap.m.Column({ header: TableHeader.clone().setText(oBundle.getText("Part_Type"))}));

    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}"}));
    oTemplatePartsView.addCell(new sap.m.Label({wrapping:true,text: "{part_type}"}));
    // oTemplatePartsView.addCell(
    // new sap.m.Link({ emphasized: true,
    //     text: {
    //         path: "attachment_url",
    //         formatter: function (attachment_url) {
    //             if(!nullCheckAll(attachment_url)){
    //                 this.setVisible(false);
    //             }else{
    //                 return "View"
    //             }
    //         }
    //     },
    //     press: function (event) {
    //         var model = this.getModel();
    //         var path = event.getSource().getBindingContext().getPath();
    //         var obj = model.getProperty(path);
    //         window.open(obj['attachment_url'], "_blank");
    //     }
    // }))


    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 oTableWorkorderGrabView = new sap.m.Table({
        noDataText: oBundle.getText("No_Data"),
        columns: [ 
            
            new sap.m.Column({ header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Action"), design: sap.m.LabelDesign.Bold }),
                minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
            new sap.m.Column({ header: new sap.m.Label({ wrapping: true, text: oBundle.getText("WO_Number"), design: sap.m.LabelDesign.Bold }),
                minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
            new sap.m.Column({ header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Created_Date"), design: sap.m.LabelDesign.Bold }),
                minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
            new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("Status"), design: sap.m.LabelDesign.Bold }),
                minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true
            }),
            new sap.m.Column({ header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Workshop_Group_Name"), design: sap.m.LabelDesign.Bold }),
                minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
            new sap.m.Column({ header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Workshop_Name"), design: sap.m.LabelDesign.Bold }),
                minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
            new sap.m.Column({ header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Part_Name"), design: sap.m.LabelDesign.Bold }),
                minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
            new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("Quantity"), design: sap.m.LabelDesign.Bold }),
                minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
            new sap.m.Column({ header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Part_Cost"), 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("Labor_Cost"), design: sap.m.LabelDesign.Bold }),
                minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true
            }),
            new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("Total_Cost"), design: sap.m.LabelDesign.Bold }),
                minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true
            }),
            new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("Note"), design: sap.m.LabelDesign.Bold }),
                minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true
            })
        ],
        infoToolbar:new sap.m.Toolbar({
            content: [new sap.m.Title({text: oBundle.getText("WORKORDER_HISTORY"),level:"H2"}),
                    new sap.m.ToolbarSpacer(),
                    new sap.m.SearchField({
                        placeholder: oBundle.getText("Search"),
                        width: "300px",
                        liveChange: function (event) {
                            var oBinding = oTableWorkorderGrabView.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("part_name", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("part_qty", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("part_cost", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("labor_item_cost", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("total_cost", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("note", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("workshop_number", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("workshop_name", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("ws_group_number", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("ws_group_name", sap.ui.model.FilterOperator.Contains, searchStr),
                                ];
                                var filterObj = new sap.ui.model.Filter(oFilters, false);
                                oBinding.filter(filterObj);
                            } else {
                                oBinding.filter([]);
                            }
                        }
                
                    }),
            ]
        })
    });
    var grabViewWoTemplate = 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 objRow = model.getProperty(path);
                    console.log(objRow)
                    getAttachedWorkorder(objRow['wo_number']);
                    // let filterWO = grab4WAllWoJSONArray.filter(function(val,ind){
                    //     return  val.wo_number == objRow['wo_number'];
                    // })
                    // if(filterWO.length > 0){
                    //     workorderViewGrab(filterWO[0],"1");
                    // }else{
                    //     sap.m.MessageToast.show("Workorder Not Available.");
                    // }

                
                }
            }),
            new sap.m.Label({ wrapping: true, text: "{wo_number}"}),
            new sap.m.Label({ wrapping: true, text: "{added_date}"}),
            new sap.m.Label({ wrapping: true, text: "{wo_status}"}),
            // new sap.m.Label({ 
            //     wrapping: true, 
            //     text: {
            //         path: "wo_number",
            //         formatter: function (wo_number) {
            //             var history_status = grab4WAllWoJSONArray.filter(a=>a.wo_number == wo_number);
            //             if(history_status.length > 0){
            //                 return history_status[0]['wo_status'];
            //             }else{
            //                 return "";
            //             }
            //         }
            //     }}),
            new sap.m.Label({ wrapping: true, text: "{ws_group_name}" }),
            // new sap.m.VBox({
            // items:[new sap.m.Label({ wrapping: true, text: "{ws_group_number}" }),
            //         new sap.m.Label({ wrapping: true, text: "{ws_group_name}" }),
            // ]}),
            new sap.m.Label({ wrapping: true, text: "{workshop_name}" }),
            // new sap.m.VBox({
            // items:[new sap.m.Label({ wrapping: true, text: "{workshop_number}" }),
            //         new sap.m.Label({ wrapping: true, text: "{workshop_name}" }),
            // ]}),
            new sap.m.Label({ wrapping: true, text: "{part_name}"}),
            
            new sap.m.Label({ wrapping: true, text: "{parts_qty}"}),
            new sap.m.Label({ wrapping: true, text: {
                path: "parts_cost",
                formatter: function (parts_cost) {
                    return formatToIDR(parts_cost);
            }}}),
            new sap.m.Label({ wrapping: true, text:  {
                path: "labor_item_cost",
                formatter: function (labor_item_cost) {
                    return formatToIDR(labor_item_cost);
            }}}),
            new sap.m.Label({ wrapping: true, text: {
                path: "total_cost",
                formatter: function (total_cost) {
                    return formatToIDR(total_cost);
            }}}),
            
            new sap.m.Label({ wrapping: true, text: "{note}"}),
    ]
    });

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

    Car_Workorder_Part.where({master_email:emailUser, wo_id: obj['id'] }).read().done(function (results) {
        if(results.length < 1){
            approvedButton.setEnabled(false);
            verifyBtn.setEnabled(false);
            completeButton.setEnabled(false);
        }
        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        oTablePartsView.setModel(oModel);
        oTablePartsView.bindItems({ path: "/modelData",template: oTemplatePartsView});
        var aSections = oPageLayout.getSections();
        if (aSections && aSections.length > 0) {
            aSections[1].setTitle(`${results.length} Service Needed`);
        }
    });


    Car_Workorder_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});
    });

    Car_Workorder_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});
    });
    // Car_Workorder_Part.where({ master_email:emailUser, license_number:obj['license_number'] }).orderByDescending("createdAt").read().done(function (results) {
    //     var oModel = new sap.ui.model.json.JSONModel();
    //     oModel.setData({ modelData: results });
    //     oTableWorkorderGrabView.setModel(oModel);
    //     oTableWorkorderGrabView.bindItems({ path: "/modelData",template: grabViewWoTemplate});
    // });
    

    var resultData = getWorkorderHistoryByLicenseNumber(obj['license_number'],oTableWorkorderGrabView,grabViewWoTemplate);
    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ modelData: resultData });
    oTableWorkorderGrabView.setModel(oModel);
    oTableWorkorderGrabView.bindItems({ path: "/modelData",template: grabViewWoTemplate});

    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.setSort(false);
    woTimeLineView.setBusy(true);
    Car_Workorder_Status.where({master_email:emailUser, wo_id: obj['id'] }).orderByDescending("createdAt").read().done(function (results) {

        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        // console.log(results)
        var temp =  new sap.suite.ui.commons.TimelineItem({width:"50px",
            dateTime: "{changed_date}",
            userNameClickable:true,
            // title: {path: "changed_by",
            //     formatter: function (changed_by) {
            //         var filterTeamID = team4WJSONData.filter(a=>a.user_id == changed_by);
            //         return filterTeamID.length > 0 ? filterTeamID[0]['user_name'] : changed_by;
            //     }
            // },
            title: {
                path: "changed_by",
                formatter: function (changed_by) {
                    var filterTeamID = team4WJSONData.filter(a => a.user_id == changed_by);
                    if (filterTeamID.length > 0) {
                        var user = filterTeamID[0];
                        var userName = user['user_name'];
                        var levelMap = {
                            "G3": "Level 1",
                            "G4": "Level 2",
                            "G5": "Level 3",
                            "G6": "Level 4",
                            "G7": "Level 5"
                        };
                        var level = levelMap[user['approval_level']] || "";
                        return level ? `${userName} - ${level}` : userName;
                    } else {
                        return changed_by;
                    }
                }
            },
            userPicture: "Images/icon1.png",
            // text: "{wo_status}" + "{note}",
            text: {
                parts: ["wo_status", "note"],
                formatter: function (wo_status, note) {
                    return wo_status + " : " + (note ? note : "");
                }
            },
            
            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 currency = "IDR"

   

    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();
                
                Car_Inspection.where({ master_email: emailUser, report_number: report_number })
                .take(1)
                .orderByDescending("createdAt")
                .read()
                .done(function (results) {
                    if(results.length > 0){
                        historyView(results[0]);
                    }else{
                        sap.m.MessageBox.error(oBundle.getText("Report_not_available_might_be_deleted"));
                    } 
                });
                // 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);
    // }

    let regular_service = ""
    if(obj['regular_service'] == "Yes"){
        regular_service = ` (${obj['service_km']}  KM)`;
    }

    // var supplier_grn_number = new sap.m.ObjectStatus({title: oBundle.getText("Supplier_GRN_Number"),text:obj['supplier_grn_number']});
    // var supplier_grn_date = new sap.m.ObjectStatus({title: oBundle.getText("Supplier_GRN_Date"),text:obj['supplier_grn_date']});
    // var supplier_grn_note = new sap.m.ObjectStatus({title: oBundle.getText("Supplier_GRN_Note"),text:obj['supplier_grn_note']});



    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_Plate"),text:obj['license_number']}),
                new sap.m.ObjectStatus({title: oBundle.getText("Chassis_Number"),text:obj['chassis_number']}),
                new sap.m.ObjectStatus({title: oBundle.getText("Model"),text:obj['model']}),
                new sap.m.ObjectStatus({title: oBundle.getText("Odometer"),text:obj['meter_reading']}),
                new sap.m.ObjectStatus({title: oBundle.getText("Regular_Service"),text:obj['regular_service'] + regular_service}),
                wo_status,
                new sap.m.ObjectStatus({title: oBundle.getText("Invoice Number"),text:obj['invoice_number']}),
                // new sap.m.ObjectStatus({title: oBundle.getText("Meter_Reading"),text:obj['meter_reading']}),
            ]}),
            // new sap.ui.layout.VerticalLayout({content: [wo_status,wo_type]}),
            new sap.ui.layout.VerticalLayout({content: [
                new sap.m.ObjectStatus({title: oBundle.getText("city"),text:obj['city']}),
                new sap.m.ObjectStatus({title: oBundle.getText("Engine_Number"),text:obj['engine_number']}),
                new sap.m.ObjectStatus({title: oBundle.getText("Make"),text:obj['make']}),
                new sap.m.ObjectStatus({title: oBundle.getText("Color"),text:obj['vehicle_color']}),
                new sap.m.ObjectStatus({title: oBundle.getText("GRN_Number"),text:obj['grn_number']}),
                new sap.m.ObjectStatus({title: oBundle.getText("GRN_Date"),text:obj['grn_date']}),
                new sap.m.ObjectStatus({title: oBundle.getText("GRN_Note"),text:obj['grn_note']}),
                // overDueDays      
            ]}),
            new sap.ui.layout.VerticalLayout({content: [
                new sap.m.ObjectStatus({title: oBundle.getText("Workshop_Group_Name"),text:obj['ws_group_name']}),
                new sap.m.ObjectStatus({title: oBundle.getText("Workshop_Name"),text:obj['workshop_name']}),
                new sap.m.ObjectStatus({title: oBundle.getText("Rental_Company_Name"),text:obj['rental_company_name']}),
                new sap.m.ObjectStatus({title: oBundle.getText("Leasing_Company_Name"),text:obj['leasing_company_name']}),
                new sap.m.ObjectStatus({title: oBundle.getText("Supplier_GRN_Number"),text:obj['supplier_grn_number']}),
                new sap.m.ObjectStatus({title: oBundle.getText("Supplier_GRN_Date"),text:obj['supplier_grn_date']}),
                new sap.m.ObjectStatus({title: oBundle.getText("Supplier_GRN_Note"),text:obj['supplier_grn_note']}),
                // overDueDays      
            ]}),
            
        ],
        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.m.ObjectStatus({title: oBundle.getText("Link Schedule"),text:obj['link_schedule']}),
                                                // 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:formatToIDR(obj['total_parts_cost'])+" "+currency}).addStyleClass("sapUiTinyMarginBottom"),
                                                new sap.m.ObjectStatus({title: oBundle.getText("Total_Labor_Cost"),text:formatToIDR(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("VAT")+" ("+obj['tax']+"%)",text:formatToIDR(obj['tax_value'])+" "+currency}).addStyleClass("sapUiTinyMarginBottom"),
                                                new sap.m.ObjectStatus({title: oBundle.getText("Total_WO_Cost"),text:formatToIDR(obj['total_wo_cost'])+" "+currency}).addStyleClass("sapUiTinyMarginBottom"),
                                            ]}),

                                            ]
                                        }),
                                        // new sap.ui.layout.BlockLayoutCell({ width: 5,content: [
                                        //     new sap.ui.layout.VerticalLayout({content: [
                                        //         new sap.m.ObjectStatus({title: oBundle.getText("Approval Note G3"),text:obj['approved_remark1']}).addStyleClass("sapUiTinyMarginBottom"),
                                        //         new sap.m.ObjectStatus({title: oBundle.getText("Approval Note G4"),text:obj['approved_remark2']}).addStyleClass("sapUiTinyMarginBottom"),
                                        //         new sap.m.ObjectStatus({title: oBundle.getText("Approval Note G5"),text:obj['approved_remark3']}).addStyleClass("sapUiTinyMarginBottom"),
                                        //         new sap.m.ObjectStatus({title: oBundle.getText("Approval Note G6"),text:obj['approved_remark4']}).addStyleClass("sapUiTinyMarginBottom"),
                                        //         new sap.m.ObjectStatus({title: oBundle.getText("Approval Note G7"),text:obj['approved_remark5']}).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']
                                                    text: (function(created_by) {
                                                        var filterTeamID = team4WJSONData.filter(a => a.user_id == created_by);
                                                        return filterTeamID.length > 0 ? filterTeamID[0]['user_name'] : created_by;
                                                    })(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']
                                                    text: (function(updated_by) {
                                                        var filterTeamID = team4WJSONData.filter(a => a.user_id == updated_by);
                                                        return filterTeamID.length > 0 ? filterTeamID[0]['user_name'] : updated_by;
                                                    })(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("Service_Needed"),
            subSections: new sap.uxap.ObjectPageSubSection({
                blocks: [oTablePartsView]
            })}),
            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("History"),
            subSections: new sap.uxap.ObjectPageSubSection({
                blocks: [oTableWorkorderGrabView]
            })}),     
        ]
    });
   

    if(obj['supplier_wo_flag'] == 'Workshop'){
        oPageLayout.getHeaderContent()[2].getContent()[4].setVisible(false);
        oPageLayout.getHeaderContent()[2].getContent()[5].setVisible(false);
        oPageLayout.getHeaderContent()[2].getContent()[6].setVisible(false);
    }
    if(!nullCheckAll(obj['invoice_number']) || (['Closed','GRN'].includes(obj['status']))){
    // if(!nullCheckAll(obj['invoice_number'])){
        oPageLayout.getHeaderContent()[0].getContent()[6].setVisible(false);
    }
    var approvedButton = new sap.m.Button({visible:false,text: oBundle.getText("Approved"),icon: "sap-icon://accept",type:"Accept",
                            press: function () {setApproval(obj, "1", oDialog, approval_level);}
                        });
    var declinedButton = new sap.m.Button({visible:false,text: oBundle.getText("Reject"),icon: "sap-icon://cancel",type:"Reject",
                            press: function () {setApproval(obj, "2", oDialog, approval_level);}
                        });
    var completeButton = new sap.m.Button({visible:false,text: oBundle.getText("Complete"),icon: "sap-icon://status-completed",type:"Accept",
                            press: function () {
                                var created_date = getIndonesianTime();
                                var oDialog1 = new sap.m.Dialog({
                                    title: oBundle.getText("Complete_Workorder"),
                                    state: sap.ui.core.ValueState.Success,
                                    content: [new sap.m.Label({ text: oBundle.getText("Sure_you_want_to_Complete_Workorder") + "?"})],
                                    buttons: [
                                                new sap.m.Button({text: oBundle.getText("Complete"),icon: "sap-icon://status-completed",
                                                    press: function () {
                                                        busyDialog.open();
                                                        Car_Workorder.update({ id: obj['id'],wo_status:"Completed",completion_date:created_date }).done(function () {
                                                            Car_Workorder_Status.insert({ master_email:emailUser, wo_number:obj['wo_number'], wo_id: obj['id'], wo_status: "Completed", 
                                                                 changed_date: created_date, changed_by: operatedID
                                                            }).done(function () {

                                                            });
                                                            getOpenWorkorder();
                                                            getCompletedWorkorder();
                                                            // getAllWorkorderDetails()
                                                            oDialog.close();
                                                            oDialog1.close();
                                                            busyDialog.close();
                                                        });
                                                    }
                                                }),
                                                new sap.m.Button({text: oBundle.getText("Cancel"),icon: "sap-icon://decline",
                                                    press: function () {
                                                        oDialog1.close();
                                                    }
                                                })
                                            ]
                                }).open();
                            }
                        });
                        
    var downloadBtn = new sap.m.Button({ text: oBundle.getText("Download"), 
        visible:false,
        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"); 
            }
        }
    });


    let emailTeamDB = new sap.m.MultiInput({
        showValueHelp: true, showSuggestion: true, valueHelpOnly: true,
        fieldWidth: "100%",
        valueHelpRequest: function () {
          getMailNextApproverDialog(1,emailTeamDB,'Approval0');
        },
        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 verifyBtn = new sap.m.Button({ text: oBundle.getText("Verify"), 
        visible:false,
        type: sap.m.ButtonType.Emphasized,
        icon: "sap-icon://approvals",
        press: function (e) {
            var created_date = getIndonesianTime();
            var oDialog1 = 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 verify this workorder?") }),oFormSendEmail4w],
                buttons: [
                            new sap.m.Button({text: oBundle.getText("Verify"),
                                type: sap.m.ButtonType.Emphasized,
                                press: function () {
                                    let email = "";
                                    let emailApprovalWoTokenList = emailTeamDB.getTokens();
                    
                                    for (var j = 0; j < emailApprovalWoTokenList.length; j++) {
                                    if (email === "") {
                                        email = emailApprovalWoTokenList[j].getKey();
                                    }
                                    }
                                   

                                    busyDialog.open();
                                    Car_Workorder.update({ id: obj['id'],wo_status:"Pending Approval",verified_by:operatedBy,verified_date:created_date }).done(function () {
                                        Car_Workorder_Status.insert({ master_email:emailUser, wo_number:obj['wo_number'], wo_id: obj['id'], wo_status: "Pending Approval", 
                                            changed_date: created_date, changed_by: operatedID
                                        }).done(function () { });

                                        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
                                        }];
                                    
                                        if(nullCheckAll(email)){
                                            sendEmailToNextApprover(email,selectedWorkordersEmail);
                                        }
                                        getVerificationWorkorder();
                                        getPendingWorkorder();
                                        oDialog.close();
                                        oDialog1.close();
                                        busyDialog.close();
                                    });
                                }
                            }),
                            new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",
                                press: function () {
                                    oDialog1.close();
                                }
                            })
                        ]
            }).open();
        }
    });

    var rejectVerifyBtn = new sap.m.Button({ text: oBundle.getText("Reject"),icon: "sap-icon://cancel",type:"Reject",
        visible:false,
        press: function (e) {
            var comment = new sap.m.TextArea({width:"100%",value:"",height:"70px",rows : 2, 
                wrapping : sap.ui.core.Wrapping.on,
                placeholder:"Enter Comment(mandatory)",
                liveChange: function (oEvent) {
                    var sText = oEvent.getParameter('value');
                    //var parent = oEvent.getSource().getParent();
                    verifyRejectBtn.setEnabled(sText.length > 0);
            }});
            var verifyRejectBtn = new sap.m.Button({text: oBundle.getText("Reject"),enabled:false,
                icon: "sap-icon://cancel",type:"Reject",
                press: function () {
                    commentData = comment.getValue();
                   
                    busyDialog.open();

                    Car_Workorder.update({ id: obj['id'],wo_status:"Reject" }).done(function () {
                        Car_Workorder_Status.insert({ master_email:emailUser, wo_number:obj['wo_number'], wo_id: obj['id'], wo_status: "Reject", 
                            changed_date: created_date, changed_by: operatedID, note:commentData
                        }).done(function () { });

                        getVerificationWorkorder();
                        getRejectWorkorder();
                        oDialog.close();
                        oDialog1.close();
                        busyDialog.close();
                    });
                }
            });
            var created_date = getIndonesianTime();
            var oDialog1 = 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 Reject this workorder?") }),comment],
                buttons: [
                            verifyRejectBtn,
                            new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",
                                press: function () {
                                    oDialog1.close();
                                }
                            })
                        ]
            }).open();
        }
    });

    if(src=="2"){
        // console.log(obj['wo_status'])
        if(obj['wo_status'] == "Need Verification"){
            // console.log("IN")
            verifyBtn.setVisible(true);
            rejectVerifyBtn.setVisible(true);
            approvedButton.setVisible(false);
            declinedButton.setVisible(false);
            downloadBtn.setVisible(false);
        }else{
            approvedButton.setVisible(true);
            declinedButton.setVisible(true);
            downloadBtn.setVisible(false);
            verifyBtn.setVisible(false);
        }
    }else if(src == '3'){
        downloadBtn.setVisible(false);
        completeButton.setVisible(true);
    }


    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,completeButton,downloadBtn,editBtn,verifyBtn,rejectVerifyBtn,
				new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",
				press: function () {oDialog.close();}
				})
			]
    }).open();
};


// var openWOField3; 
// //Filter Global Variables
// var filterWoLicenseNumber = "";
// var filterWoCity = "";
// var filterWoWorkshop = "";
// var filterWoWorkshopGroup = "";
// var filterWoStatus = "";
// var filterWoRCN = "";
// var filterWoLCN = "";
// var filterWoStartDate = "";
// var filterWoEndDate = "";
// var filterWoInvoice = "";
// var filterWoReceiptNumber = "";
// var filterWoApprover = "";
// function funMultiFilterOpenWO(src,json,table,bindTemplate){
   

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

//     var openWOField2 = new sap.m.MultiInput({ showSuggestion: true, fieldWidth: "100%",autocomplete:true,
//         showValueHelp: true,valueHelpOnly: true,
//         valueHelpRequest: function () { selectTeamWorkshop(2,openWOField2); }
//     });

//     openWOField3 = new sap.m.Input({
//         showValueHelp: true,
//         valueHelpOnly: true,
//         placeholder:oBundle.getText("Select_vehicle_from_inventry_list"),
//         valueHelpRequest: function () {
//             if(!vehicleTemp){
//                 selectVehiclArea = "multiFilter_wo";
//                 pickVehicle();
//             }else{
//                 sap.m.MessageBox.error(oBundle.getText("Please Wait while vehicles get loaded."));
//                 get4WVehicle();
//                 vehicleTemp = false;
//                 return;
//             }
//         }
//     });

//     var openWOField4 = new sap.m.ComboBox({width:"100%",
//         items:[ 
//                 new sap.ui.core.ListItem({key:"Pending Approval",text:oBundle.getText("Pending Approval")}),
//                 new sap.ui.core.ListItem({key:"Open",text:oBundle.getText("Open")}),
//                 new sap.ui.core.ListItem({key:"Complete",text:oBundle.getText("Complete")}),
//                 new sap.ui.core.ListItem({key:"Closed",text:oBundle.getText("Closed")}),
//                 new sap.ui.core.ListItem({key:"GRN",text:oBundle.getText("GRN")}),
//                 new sap.ui.core.ListItem({key:"Reject",text:oBundle.getText("Reject")}),
//                 new sap.ui.core.ListItem({key:"Cancelled",text:oBundle.getText("Cancelled")}),
//                 new sap.ui.core.ListItem({key:"Archived",text:oBundle.getText("Archived")}),
//          ]
//      }).addEventDelegate({onAfterRendering: function(e) { openWOField4.$().find("input").attr("readonly", true);}});


//     let openWOField5 = new sap.m.Input({});
//     let openWOField6 = cityCB.clone();
//     // new sap.m.ComboBox({width:"100%",
//     //     value:"",
//     //     items:[
//     //         new sap.ui.core.ListItem({text: ""}),
//     //         new sap.ui.core.ListItem({text: oBundle.getText("BANDUNG")}),
//     //         new sap.ui.core.ListItem({text: oBundle.getText("BALI")}),
//     //         new sap.ui.core.ListItem({text: oBundle.getText("JAKARTA")}),
//     //         new sap.ui.core.ListItem({text: oBundle.getText("MAKASSAR")}),
//     //         new sap.ui.core.ListItem({text: oBundle.getText("MALANG")}),
//     //         new sap.ui.core.ListItem({text: oBundle.getText("MEDAN")}),
//     //         new sap.ui.core.ListItem({text: oBundle.getText("PALEMBANG")}),
//     //         new sap.ui.core.ListItem({text: oBundle.getText("SEMARANG")}),
//     //         new sap.ui.core.ListItem({text: oBundle.getText("SOLO")}),
//     //         new sap.ui.core.ListItem({text: oBundle.getText("SURABAYA")}),
//     //         new sap.ui.core.ListItem({text: oBundle.getText("YOGYAKARTA")}),
//     //         // // new sap.ui.core.ListItem({text: oBundle.getText("HEAD OFFICE AND ACCOUNTING OFFICE")}),
//     //         // new sap.ui.core.ListItem({text: oBundle.getText("STI jakarta")}),
//     // ]}).addEventDelegate({onAfterRendering: function(e) {openWOField6.$().find("input").attr("readonly", true);}});

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

//         if (!isValid) {
//             sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list_for_City"));
//             openWOField6.setValue(oBundle.getText("BALI"));
//         }
//     });

//     let openWOField7 = new sap.m.Input({});
//     let openWOField8 = new sap.m.Input({});
//     let openWOField11 = new sap.m.Input({});
//     let openWOField12 = new sap.m.Input({});
//     let openWOField9 = new sap.m.DatePicker({
//         width: "100%",
//         // minDate: new Date(),
//         displayFormat: "dd-MMM-yyyy",
//         valueFormat: "dd-MMM-yyyy",
//         change: function (oEvent) {
//             // Validate if the date is valid; otherwise, clear it
//             if (!oEvent.getParameter("valid")) {
//                 oIFInvoice4.setValue(""); // Clear invalid input
//                 sap.m.MessageToast.show("Please select a valid date from the calendar.");
//             }
//         }
//     }).attachBrowserEvent("keydown", function (oEvent) {
//         oEvent.preventDefault(); // Prevent manual typing
//     });  //Start Date
//     let openWOField10 =new sap.m.DatePicker({
//         width: "100%",
//         // minDate: new Date(),
//         displayFormat: "dd-MMM-yyyy",
//         valueFormat: "dd-MMM-yyyy",
//         change: function (oEvent) {
//             // Validate if the date is valid; otherwise, clear it
//             if (!oEvent.getParameter("valid")) {
//                 oIFInvoice4.setValue(""); // Clear invalid input
//                 sap.m.MessageToast.show("Please select a valid date from the calendar.");
//             }
//         }
//     }).attachBrowserEvent("keydown", function (oEvent) {
//         oEvent.preventDefault(); // Prevent manual typing
//     });  //End Date

//     var openWOField13 = new sap.m.ComboBox({width:"100%",
//         items:[ 
//                 new sap.ui.core.ListItem({key:oBundle.getText("Select_Approver"),text:oBundle.getText("Select_Approver")}),
//                 new sap.ui.core.ListItem({key:oBundle.getText("G3"),text:oBundle.getText("G3")}),
//                 new sap.ui.core.ListItem({key:oBundle.getText("G4"),text:oBundle.getText("G4")}),
//                 new sap.ui.core.ListItem({key:oBundle.getText("G5"),text:oBundle.getText("G5")}),
//                 new sap.ui.core.ListItem({key:oBundle.getText("G6"),text:oBundle.getText("G6")}),
//                 new sap.ui.core.ListItem({key:oBundle.getText("G7"),text:oBundle.getText("G7")})
//          ]
//      }).addEventDelegate({onAfterRendering: function(e) { openWOField13.$().find("input").attr("readonly", true);}});



//     var Form1 = 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: new sap.m.Label({required: false, text: oBundle.getText("License_Number")}),
//                         fields: [openWOField3]
//                     }),
//                     // new sap.ui.layout.form.FormElement({
//                     //     label: new sap.m.Label({required: false, text: oBundle.getText("Workorder Number")}),
//                     //     fields: [openWOField5]
//                     // }),
//                     new sap.ui.layout.form.FormElement({
//                         label: new sap.m.Label({required: false, text: oBundle.getText("City")}),
//                         fields: [openWOField6]
//                     }),
//                     new sap.ui.layout.form.FormElement({
//                         label: new sap.m.Label({required: false, text: oBundle.getText("Workshop_Group_Name")}),
//                         fields: [openWOField1]
//                     }),
//                     new sap.ui.layout.form.FormElement({
//                         label: new sap.m.Label({required: false, text: oBundle.getText("Workshop_Name")}),
//                         fields: [openWOField2]
//                     }),
//                     new sap.ui.layout.form.FormElement({
//                         label: new sap.m.Label({required: false, text: oBundle.getText("Status")}),
//                         fields: [openWOField4]
//                     }),
//                     new sap.ui.layout.form.FormElement({
//                         label: new sap.m.Label({required: false, text: oBundle.getText("Rental_Company_Name")}),
//                         fields: [openWOField7]
//                     }),
//                     new sap.ui.layout.form.FormElement({
//                         label: new sap.m.Label({required: false, text: oBundle.getText("Leasing_Company_Name")}),
//                         fields: [openWOField8]
//                     }),
//                     new sap.ui.layout.form.FormElement({
//                         label: new sap.m.Label({required: false, text: oBundle.getText("Start_Date")}),
//                         fields: [openWOField9]
//                     }),
//                     new sap.ui.layout.form.FormElement({
//                         label: new sap.m.Label({required: false, text: oBundle.getText("End_Date")}),
//                         fields: [openWOField10]
//                     }),
//                     new sap.ui.layout.form.FormElement({
//                         label: new sap.m.Label({required: false, text: oBundle.getText("Workshop_Invoice")}),
//                         fields: [openWOField11]
//                     }),
//                     new sap.ui.layout.form.FormElement({
//                         label: new sap.m.Label({required: false, text: oBundle.getText("Receipt_Number")}),
//                         fields: [openWOField12]
//                     }),
//                     new sap.ui.layout.form.FormElement({
//                         label: new sap.m.Label({required: false, text: oBundle.getText("Approver")}),
//                         fields: [openWOField13]
//                     }),
//                 ]
//             }),
//         ]
//     });
    
//     var editBtn = new sap.m.Button({visible:true, icon: "sap-icon://edit", 
//         text: oBundle.getText("Apply_Filter"),
//         press: function (event) {
//             oTableWorkorder.setBusy(true);
//             busyDialog.open();
    
//             var filter1 = "";
//             let filter1TokenList = openWOField1.getTokens();
//             for (var j = 0; j < filter1TokenList.length; j++) {
//                 if (filter1 == "") {
//                     filter1 = filter1TokenList[j].getKey();
//                 }
//             };

//             let filter2 = "";
//             let filter2TokenList = openWOField2.getTokens();
//             for (var j = 0; j < filter2TokenList.length; j++) {
//                 if (filter2 == "") {
//                     filter2 = filter2TokenList[j].getKey();
//                 }
//             };

//             var filter3 = openWOField3.getValue(); // vehicle Number
//             var filter4 = openWOField4.getSelectedKey(); //Status
//             // console.log(filter4)
//             // var filter5 = openWOField5.getValue();  // Workorder number

//             let filter6 = openWOField6.getValue();  //city
//             let filter7 = openWOField7.getValue();  //Rental Company Name
//             let filter8 = openWOField8.getValue();  //Leasing Company Name
//             let filter9 = openWOField9.getValue()  ;  //Start Date
//             let filter10 = openWOField10.getValue()  ;  //End Date
//             let filter11 = openWOField11.getValue();  //Workshop Invocie
//             let filter12 = openWOField12.getValue();  //Receipt Number
//             let filter13 = openWOField13.getValue();  //Approver list

//             if(filter6 == oBundle.getText("Select_City")){
//                 filter6 = "";
//             }
//             if(filter13 == oBundle.getText("Select_Approver")){
//                 filter13 = "";
//             }
//             var filterData = json
           
//             if(nullCheckAll(filter1)){
//                 filterData = filterData.filter(function(obj,eve){ return obj.ws_group_number == filter1; });
//             };
            
//             if(nullCheckAll(filter2)){
//                 filterData = filterData.filter(function(obj,eve){ return obj.workshop_number == filter2; });
//             };
            
//             if(nullCheckAll(filter3)){
//                 filterData = filterData.filter(function(obj,eve){ return obj.license_number == filter3; });
//             };

//             if(nullCheckAll(filter4)){
//                 filterData = filterData.filter(function(obj,eve){ return obj.wo_status == filter4; });
//             };
//             if(nullCheckAll(filter6)){
//                 filterData = filterData.filter(function(obj,eve){ return obj.city == filter6; });
//             };
//             if(nullCheckAll(filter7)){
//                 filterData = filterData.filter(function(obj,eve){ return obj.rental_company_name == filter7; });
//             };
//             if(nullCheckAll(filter8)){
//                 filterData = filterData.filter(function(obj,eve){ return obj.leasing_company_name == filter8; });
//             };
//             if(nullCheckAll(filter9)){
//                 filterData = filterData.filter(function(obj,eve){ return new Date(obj.created_date) >= new Date(filter9 + " 12:00 AM"); });
//             };
//             if(nullCheckAll(filter10)){
//                 filterData = filterData.filter(function(obj,eve){ return new Date(obj.created_date) <= new Date(filter10 + " 11:59 PM"); });
//             };
//             if(nullCheckAll(filter11)){
//                 filterData = filterData.filter(function(obj,eve){ return obj.invoice_number == filter11; });
//             };
//             if(nullCheckAll(filter12)){
//                 filterData = filterData.filter(function(obj,eve){ return obj.grn_number == filter12; });
//             };
//             if(nullCheckAll(filter13)){
              
//                 if(filter13 == oBundle.getText('G3')){
//                     filterData = filterData.filter(function(obj,eve){ return !nullCheckAll(obj.approval1); });
//                 }else if(filter13 == oBundle.getText('G4')){
//                     filterData = filterData.filter(function(obj,eve){ return !nullCheckAll(obj.approval2) && nullCheckAll(obj.approval1); });
//                 }else if(filter13 == oBundle.getText('G5')){
//                     filterData = filterData.filter(function(obj,eve){ return !nullCheckAll(obj.approval3) && nullCheckAll(obj.approval2); });
//                 }else if(filter13 == oBundle.getText('G6')){
//                     filterData = filterData.filter(function(obj,eve){ return !nullCheckAll(obj.approval4) && nullCheckAll(obj.approval3); });
//                 }else if(filter13 == oBundle.getText('G7')){
//                     filterData = filterData.filter(function(obj,eve){ return !nullCheckAll(obj.approval5) && nullCheckAll(obj.approval4); });
//                 }
//                 // filterData = filterData.filter(function(obj,eve){ return obj.grn_number == filter12; });
//             };
            
            
//             var oModel = new sap.ui.model.json.JSONModel();
//             oModel.setData({ modelData: filterData });
//             table.setModel(oModel);
//             if(src == 1){                 
//                 table.bindItems({ path: "/modelData", template: workorderTemplate });
//             }else{
//                 table.bindItems({ path: "/modelData", template: bindTemplate });
//             };

//             filterWoLicenseNumber = filter3;
//             filterWoCity = filter6;
//             filterWoWorkshop = filter2;
//             filterWoWorkshopGroup = filter1;
//             filterWoStatus = filter4;
//             filterWoRCN = filter7;
//             filterWoLCN = filter8;
//             filterWoStartDate = filter9;
//             filterWoEndDate = filter10;
//             filterWoInvoice = filter11;
//             filterWoReceiptNumber = filter12;
//             filterWoApprover = filter13;

//             console.log("Filter Variables:", {
//                 filterWoLicenseNumber,
//                 filterWoCity,
//                 filterWoWorkshop,
//                 filterWoWorkshopGroup,
//                 filterWoStatus,
//                 filterWoRCN,
//                 filterWoLCN,
//                 filterWoStartDate,
//                 filterWoEndDate,
//                 filterWoInvoice,
//                 filterWoReceiptNumber,
//                 filterWoApprover
//             });
            
//             table.setBusy(false);
//             oDialog.close();
//             busyDialog.close();
//         }
//     });

//     var clearFilterBtn = new sap.m.Button({visible:true, icon: "sap-icon://edit", 
//         text: oBundle.getText("Clear_Filter"),
//         press: function (event) {
//             busyDialog.open();
//             var filterData = json;

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

//             if(json == grabClosedWOJSONArray){
//                 oSelectInvocieStatus.setSelectedKey('ALL');
//             }

//             filterWoLicenseNumber = "";
//             filterWoCity = "";
//             filterWoWorkshop = "";
//             filterWoWorkshopGroup = "";
//             filterWoStatus = "";
//             filterWoRCN = "";
//             filterWoLCN = "";
//             filterWoStartDate = "";
//             filterWoEndDate = "";
//             filterWoInvoice = "";
//             filterWoReceiptNumber = "";
//             filterWoApprover = "";

//             oDialog.close();
//             busyDialog.close();
//         }
//     })
//     var oDialog = new sap.m.Dialog({ contentWidth: "30%", contentHeight: "90%", draggable: true, 
//         resizable: true,
//         title: oBundle.getText("Multi_Filter_Workorder"),
//         content: [Form1],
//         buttons: [clearFilterBtn, editBtn,
//             new sap.m.Button({ text: oBundle.getText("Close"), icon: "sap-icon://decline",
//                 press: function () {
//                     oDialog.close();
//                 }
//             })
//         ]
//     }).open();


//     if(src == 2){
//         Form1.getFormContainers()[0].getFormElements()[4].setVisible(false);
//         Form1.getFormContainers()[0].getFormElements()[7].setVisible(false);
//         Form1.getFormContainers()[0].getFormElements()[8].setVisible(false);
//         Form1.getFormContainers()[0].getFormElements()[9].setVisible(false);
//         Form1.getFormContainers()[0].getFormElements()[10].setVisible(false);
//     }else{
//         Form1.getFormContainers()[0].getFormElements()[4].setVisible(true);
//         Form1.getFormContainers()[0].getFormElements()[7].setVisible(true);
//         Form1.getFormContainers()[0].getFormElements()[8].setVisible(true);
//         Form1.getFormContainers()[0].getFormElements()[9].setVisible(true);
//         Form1.getFormContainers()[0].getFormElements()[10].setVisible(true);

//     }

// };

// function refreshVerifyWorkOrders() {
//     // Load your new JSON data into model
//     var oModel = new sap.ui.model.json.JSONModel();
//     oModel.setData({ workorders: grabVerificationWOJSONArray });
//     oTable4WVerificationWO.setModel(oModel);

//     // Build filter array again
//     var aFilters = [];

//     if (nullCheckAll(filterWoLicenseNumber)) {
//         console.log(1)
//         aFilters.push(new sap.ui.model.Filter("license_number", sap.ui.model.FilterOperator.Contains, filterWoLicenseNumber));
//     }
//     if (nullCheckAll(filterWoCity)) {
//         console.log(2)
//         aFilters.push(new sap.ui.model.Filter("city", sap.ui.model.FilterOperator.Contains, filterWoCity));
//     }
//     if (nullCheckAll(filterWoWorkshop)) {
//         console.log(3)
//         aFilters.push(new sap.ui.model.Filter("workshop_number", sap.ui.model.FilterOperator.EQ, filterWoWorkshop));
//     }
//     if (nullCheckAll(filterWoWorkshopGroup)) {
//         console.log(4)
//         aFilters.push(new sap.ui.model.Filter("ws_group_number", sap.ui.model.FilterOperator.EQ, filterWoWorkshopGroup));
//     }
//     if (nullCheckAll(filterWoStatus)) {
//         console.log(5)
//         aFilters.push(new sap.ui.model.Filter("wo_status", sap.ui.model.FilterOperator.EQ, filterWoStatus));
//     }
//     if (nullCheckAll(filterWoRCN)) {
//         console.log(6)
//         aFilters.push(new sap.ui.model.Filter("rental_company_name", sap.ui.model.FilterOperator.Contains, filterWoRCN));
//     }
//     if (nullCheckAll(filterWoLCN)) {
//         console.log(7)
//         aFilters.push(new sap.ui.model.Filter("leasing_company_name", sap.ui.model.FilterOperator.Contains, filterWoLCN));
//     }

//     // Apply filters again
//     console.log(aFilters)
//     var oBinding = oTable4WVerificationWO.getBinding("items");
//     if (oBinding) {
//         oBinding.filter(aFilters);
//     }
// }


// Global filter variables
var openWOField3; 
var filterWoLicenseNumber = "";
var filterWoCity = "";
var filterWoWorkshop = "";
var filterWoWorkshopGroup = "";
var filterWoStatus = "";
var filterWoRCN = "";
var filterWoLCN = "";
var filterWoStartDate = "";
var filterWoEndDate = "";
var filterWoInvoice = "";
var filterWoReceiptNumber = "";
var filterWoApprover = "";

var aAllFilters = [];
var aNeedVerifyFilters = [];
var aPendingFilters = [];
var aOpenFilters = [];
var aCompletedFilters = [];
var aClosedFilters = [];
var aGRNFilters = [];
var aRejectFilters = [];
var aCancelledFilters = [];
var aArchiveFilters = [];

// Reapply saved filters on a table
function applySavedFilters(oTable) {
    console.log(oTable)
    var aFilters = [];

    if (filterWoWorkshopGroup) {
        aFilters.push(new sap.ui.model.Filter("ws_group_number", sap.ui.model.FilterOperator.EQ, filterWoWorkshopGroup));
    }
    if (filterWoWorkshop) {
        aFilters.push(new sap.ui.model.Filter("workshop_number", sap.ui.model.FilterOperator.EQ, filterWoWorkshop));
    }
    if (filterWoLicenseNumber) {
        aFilters.push(new sap.ui.model.Filter("license_number", sap.ui.model.FilterOperator.Contains, filterWoLicenseNumber));
    }
    if (filterWoStatus) {
        aFilters.push(new sap.ui.model.Filter("wo_status", sap.ui.model.FilterOperator.EQ, filterWoStatus));
    }
    if (filterWoCity && filterWoCity != 'Select City') {
        aFilters.push(new sap.ui.model.Filter("city", sap.ui.model.FilterOperator.EQ, filterWoCity));
    }
    if (filterWoRCN) {
        aFilters.push(new sap.ui.model.Filter("rental_company_name", sap.ui.model.FilterOperator.Contains, filterWoRCN));
    }
    if (filterWoLCN) {
        aFilters.push(new sap.ui.model.Filter("leasing_company_name", sap.ui.model.FilterOperator.Contains, filterWoLCN));
    }
    if (filterWoInvoice) {
        aFilters.push(new sap.ui.model.Filter("invoice_number", sap.ui.model.FilterOperator.Contains, filterWoInvoice));
    }
    if (filterWoReceiptNumber) {
        aFilters.push(new sap.ui.model.Filter("grn_number", sap.ui.model.FilterOperator.Contains, filterWoReceiptNumber));
    }

    // Start & End Date filter
    // if (filterWoStartDate) {
    //     aFilters.push(new sap.ui.model.Filter("created_date", sap.ui.model.FilterOperator.GE, new Date(filterWoStartDate)));
    // }
    // if (filterWoEndDate) {
    //     aFilters.push(new sap.ui.model.Filter("created_date", sap.ui.model.FilterOperator.LE, new Date(filterWoEndDate)));
    // }

    if (nullCheckAll(filterWoStartDate) || nullCheckAll(filterWoEndDate)) {
        let fromDate = nullCheckAll(filterWoStartDate) ? new Date(filterWoStartDate) : null;
        let toDate = nullCheckAll(filterWoEndDate) ? new Date(filterWoEndDate) : null;
    
        if (fromDate) fromDate.setHours(0, 0, 0, 0);
        if (toDate) toDate.setHours(23, 59, 59, 999);
    
        aFilters.push(new sap.ui.model.Filter({
            path: "created_date",
            test: function (value) {
                if (!value) return false;
        
                // Clean up any spaces
                value = value.trim();
        
                // Try to parse directly
                let objDate = new Date(value);
        
                if (isNaN(objDate)) return false; // Skip if invalid
        
                if (fromDate && toDate) {
                    return objDate >= fromDate && objDate <= toDate;
                } else if (fromDate) {
                    return objDate >= fromDate;
                } else if (toDate) {
                    return objDate <= toDate;
                }
                return true;
            }
        }));
    }
    
    


    // Approver filter
    if (filterWoApprover) {
        if (filterWoApprover === oBundle.getText("G3")) {
            aFilters.push(new sap.ui.model.Filter("approval1", sap.ui.model.FilterOperator.EQ, null));
        } else if (filterWoApprover === oBundle.getText("G4")) {
            aFilters.push(new sap.ui.model.Filter("approval2", sap.ui.model.FilterOperator.EQ, null));
        } else if (filterWoApprover === oBundle.getText("G5")) {
            aFilters.push(new sap.ui.model.Filter("approval3", sap.ui.model.FilterOperator.EQ, null));
        } else if (filterWoApprover === oBundle.getText("G6")) {
            aFilters.push(new sap.ui.model.Filter("approval4", sap.ui.model.FilterOperator.EQ, null));
        } else if (filterWoApprover === oBundle.getText("G7")) {
            aFilters.push(new sap.ui.model.Filter("approval5", sap.ui.model.FilterOperator.EQ, null));
        }
    }

    // Apply filters to binding
    var oBinding = oTable.getBinding("items");
    if (oBinding) {
        oBinding.filter(aFilters);
    }
    let currentSectionId = oAppWorkOrderPageLayout.getSelectedSection();
     
        if(currentSectionId=="GWO1"){  // Pending
            var oBinding = oTableWorkorder.getBinding("items");
            aPendingFilters = oBinding.aFilters;
        }else if(currentSectionId=="GWO2"){  //Open
            var oBinding = oTable4WOpenWO.getBinding("items");
            aOpenFilters = oBinding.aFilters;
        }else if(currentSectionId=="GWO3"){  //Completed
            var oBinding = oTable4WCompletedWO.getBinding("items");
            aCompletedFilters = oBinding.aFilters;
        }else if(currentSectionId=="GWO4"){  //Closed
            var oBinding = oTable4WClosedWO.getBinding("items");
            aClosedFilters = oBinding.aFilters;
        }else if(currentSectionId=="GWO5"){  //GRN
            var oBinding = oTable4WGrnWO.getBinding("items");
            aGRNFilters = oBinding.aFilters;
        }else if(currentSectionId=="GWO6"){  //Reject
            var oBinding = oTable4WRejectWO.getBinding("items");
            aRejectFilters = oBinding.aFilters;
        }else if(currentSectionId=="GWO7"){  //Cancelled
            var oBinding = oTable4WCancelledWO.getBinding("items");
            aCancelledFilters = oBinding.aFilters;
        }else if(currentSectionId=="GWO8"){  //Archive
            var oBinding = ArchiveWOTable.getBinding("items");
            aArchiveFilters = oBinding.aFilters;
        }else if(currentSectionId=="GWO9"){  //Open Invoice
            // var oBinding = oTable4WVerificationWO.getBinding("items");
            // aNeedVerifyFilters = oBinding.aFilters;
        }else if(currentSectionId=="GW10"){  //All Workorder
            var oBinding = oTable4WAllWO.getBinding("items");
            aAllFilters = oBinding.aFilters;
        }else if(currentSectionId == "GWO11"){ // Need Verification
            var oBinding = oTable4WVerificationWO.getBinding("items");
            aNeedVerifyFilters = oBinding.aFilters;
        };
}

// ============================
// Main function
// ============================
// function funMultiFilterOpenWO(src, json, table, bindTemplate) {
//     var openWOField1 = new sap.m.MultiInput({
//         showSuggestion: true, fieldWidth: "100%",
//         showValueHelp: true, valueHelpOnly: true,
//         valueHelpRequest: function () { selectTeamWSGroup(openWOField1); }
//     });

//     var openWOField2 = new sap.m.MultiInput({
//         showSuggestion: true, fieldWidth: "100%", autocomplete: true,
//         showValueHelp: true, valueHelpOnly: true,
//         valueHelpRequest: function () { selectTeamWorkshop(2, openWOField2); }
//     });

//     openWOField3 = new sap.m.Input({
//         showValueHelp: true, valueHelpOnly: true,
//         placeholder: oBundle.getText("Select_vehicle_from_inventry_list"),
//         valueHelpRequest: function () {
//             if (!vehicleTemp) {
//                 selectVehiclArea = "multiFilter_wo";
//                 pickVehicle();
//             } else {
//                 sap.m.MessageBox.error(oBundle.getText("Please Wait while vehicles get loaded."));
//                 get4WVehicle();
//                 vehicleTemp = false;
//                 return;
//             }
//         }
//     });

//     var openWOField4 = new sap.m.ComboBox({
//         width: "100%",
//         items: [
//             new sap.ui.core.ListItem({ key: "Pending Approval", text: oBundle.getText("Pending Approval") }),
//             new sap.ui.core.ListItem({ key: "Open", text: oBundle.getText("Open") }),
//             new sap.ui.core.ListItem({ key: "Complete", text: oBundle.getText("Complete") }),
//             new sap.ui.core.ListItem({ key: "Closed", text: oBundle.getText("Closed") }),
//             new sap.ui.core.ListItem({ key: "GRN", text: oBundle.getText("GRN") }),
//             new sap.ui.core.ListItem({ key: "Reject", text: oBundle.getText("Reject") }),
//             new sap.ui.core.ListItem({ key: "Cancelled", text: oBundle.getText("Cancelled") }),
//             new sap.ui.core.ListItem({ key: "Archived", text: oBundle.getText("Archived") })
//         ]
//     }).addEventDelegate({
//         onAfterRendering: function (e) {
//             openWOField4.$().find("input").attr("readonly", true);
//         }
//     });

//     let openWOField6 = cityCB.clone();
//     openWOField6.attachChange(function (oEvent) {
//         let enteredValue = oEvent.getParameter("value");
//         let isValid = openWOField6.getItems().some(item => item.getText() === enteredValue);
//         if (!isValid) {
//             sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list_for_City"));
//             openWOField6.setValue(oBundle.getText("BALI"));
//         }
//     });

//     let openWOField7 = new sap.m.Input({});
//     let openWOField8 = new sap.m.Input({});
//     let openWOField11 = new sap.m.Input({});
//     let openWOField12 = new sap.m.Input({});
//     let openWOField9 = new sap.m.DatePicker({
//         width: "100%", displayFormat: "dd-MMM-yyyy", valueFormat: "dd-MMM-yyyy",
//         change: function (oEvent) {
//             if (!oEvent.getParameter("valid")) {
//                 this.setValue(""); // fixed
//                 sap.m.MessageToast.show("Please select a valid date from the calendar.");
//             }
//         }
//     }).attachBrowserEvent("keydown", function (oEvent) { oEvent.preventDefault(); });

//     let openWOField10 = new sap.m.DatePicker({
//         width: "100%", displayFormat: "dd-MMM-yyyy", valueFormat: "dd-MMM-yyyy",
//         change: function (oEvent) {
//             if (!oEvent.getParameter("valid")) {
//                 this.setValue(""); // fixed
//                 sap.m.MessageToast.show("Please select a valid date from the calendar.");
//             }
//         }
//     }).attachBrowserEvent("keydown", function (oEvent) { oEvent.preventDefault(); });

//     var openWOField13 = new sap.m.ComboBox({
//         width: "100%",
//         items: [
//             new sap.ui.core.ListItem({ key: oBundle.getText("Select_Approver"), text: oBundle.getText("Select_Approver") }),
//             new sap.ui.core.ListItem({ key: oBundle.getText("G3"), text: oBundle.getText("G3") }),
//             new sap.ui.core.ListItem({ key: oBundle.getText("G4"), text: oBundle.getText("G4") }),
//             new sap.ui.core.ListItem({ key: oBundle.getText("G5"), text: oBundle.getText("G5") }),
//             new sap.ui.core.ListItem({ key: oBundle.getText("G6"), text: oBundle.getText("G6") }),
//             new sap.ui.core.ListItem({ key: oBundle.getText("G7"), text: oBundle.getText("G7") })
//         ]
//     }).addEventDelegate({
//         onAfterRendering: function (e) {
//             openWOField13.$().find("input").attr("readonly", true);
//         }
//     });

//     var Form1 = 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: new sap.m.Label({ text: oBundle.getText("License_Number") }), fields: [openWOField3] }),
//                 new sap.ui.layout.form.FormElement({ label: new sap.m.Label({ text: oBundle.getText("City") }), fields: [openWOField6] }),
//                 new sap.ui.layout.form.FormElement({ label: new sap.m.Label({ text: oBundle.getText("Workshop_Group_Name") }), fields: [openWOField1] }),
//                 new sap.ui.layout.form.FormElement({ label: new sap.m.Label({ text: oBundle.getText("Workshop_Name") }), fields: [openWOField2] }),
//                 new sap.ui.layout.form.FormElement({ label: new sap.m.Label({ text: oBundle.getText("Status") }), fields: [openWOField4] }),
//                 new sap.ui.layout.form.FormElement({ label: new sap.m.Label({ text: oBundle.getText("Rental_Company_Name") }), fields: [openWOField7] }),
//                 new sap.ui.layout.form.FormElement({ label: new sap.m.Label({ text: oBundle.getText("Leasing_Company_Name") }), fields: [openWOField8] }),
//                 new sap.ui.layout.form.FormElement({ label: new sap.m.Label({ text: oBundle.getText("Start_Date") }), fields: [openWOField9] }),
//                 new sap.ui.layout.form.FormElement({ label: new sap.m.Label({ text: oBundle.getText("End_Date") }), fields: [openWOField10] }),
//                 new sap.ui.layout.form.FormElement({ label: new sap.m.Label({ text: oBundle.getText("Workshop_Invoice") }), fields: [openWOField11] }),
//                 new sap.ui.layout.form.FormElement({ label: new sap.m.Label({ text: oBundle.getText("Receipt_Number") }), fields: [openWOField12] }),
//                 new sap.ui.layout.form.FormElement({ label: new sap.m.Label({ text: oBundle.getText("Approver") }), fields: [openWOField13] })
//             ]
//         })]
//     });

//     var applyBtn = new sap.m.Button({
//         icon: "sap-icon://filter",
//         text: oBundle.getText("Apply_Filter"),
//         press: function () {
//             // save values globally
//             filterWoWorkshopGroup = openWOField1.getTokens().length ? openWOField1.getTokens()[0].getKey() : "";
//             filterWoWorkshop = openWOField2.getTokens().length ? openWOField2.getTokens()[0].getKey() : "";
//             filterWoLicenseNumber = openWOField3.getValue();
//             filterWoStatus = openWOField4.getSelectedKey();
//             filterWoCity = openWOField6.getValue();
//             filterWoRCN = openWOField7.getValue();
//             filterWoLCN = openWOField8.getValue();
//             filterWoStartDate = openWOField9.getValue();
//             filterWoEndDate = openWOField10.getValue();
//             filterWoInvoice = openWOField11.getValue();
//             filterWoReceiptNumber = openWOField12.getValue();
//             filterWoApprover = openWOField13.getValue();

//             // apply filters
//             applySavedFilters(table);
//             oDialog.close();
//         }
//     });

//     var clearBtn = new sap.m.Button({
//         icon: "sap-icon://reset",
//         text: oBundle.getText("Clear_Filter"),
//         press: function () {
//             filterWoLicenseNumber = "";
//             filterWoCity = "";
//             filterWoWorkshop = "";
//             filterWoWorkshopGroup = "";
//             filterWoStatus = "";
//             filterWoRCN = "";
//             filterWoLCN = "";
//             filterWoStartDate = "";
//             filterWoEndDate = "";
//             filterWoInvoice = "";
//             filterWoReceiptNumber = "";
//             filterWoApprover = "";

//             applySavedFilters(table); // clears filters
//             oDialog.close();
//         }
//     });

//     var oDialog = new sap.m.Dialog({
//         contentWidth: "30%", contentHeight: "90%", draggable: true, resizable: true,
//         title: oBundle.getText("Multi_Filter_Workorder"),
//         content: [Form1],
//         buttons: [clearBtn, applyBtn,
//             new sap.m.Button({ text: oBundle.getText("Close"), icon: "sap-icon://decline", press: function () { oDialog.close(); } })
//         ]
//     }).open();
// }

function funMultiFilterOpenWO(src, json, table, bindTemplate) {

    // ─────────── FIELDS ───────────
    var openWOField1 = new sap.m.MultiInput({
        showSuggestion: true,
        width: "100%",
        showValueHelp: true,
        valueHelpOnly: true,
        valueHelpRequest: function () { selectTeamWSGroup(openWOField1); }
    });

    var openWOField2 = new sap.m.MultiInput({
        showSuggestion: true,
        width: "100%",
        autocomplete: true,
        showValueHelp: true,
        valueHelpOnly: true,
        valueHelpRequest: function () { selectTeamWorkshop(2, openWOField2); }
    });

    openWOField3 = new sap.m.Input({
        placeholder: oBundle.getText("Select_vehicle_from_inventry_list"),
        showValueHelp: true,
        valueHelpOnly: true,
        valueHelpRequest: function () {
            if (!vehicleTemp) {
                selectVehiclArea = "multiFilter_wo";
                pickVehicle();
            } else {
                sap.m.MessageBox.error(oBundle.getText("Please Wait while vehicles get loaded."));
                get4WVehicle();
                vehicleTemp = false;
                return;
            }
        }
    });

    var openWOField4 = new sap.m.ComboBox({
        width: "100%",
        placeholder: oBundle.getText("Select_Status"),
        items: [
            new sap.ui.core.ListItem({ key: "Pending Approval", text: oBundle.getText("Pending Approval") }),
            new sap.ui.core.ListItem({ key: "Open", text: oBundle.getText("Open") }),
            new sap.ui.core.ListItem({ key: "Complete", text: oBundle.getText("Complete") }),
            new sap.ui.core.ListItem({ key: "Closed", text: oBundle.getText("Closed") }),
            new sap.ui.core.ListItem({ key: "GRN", text: oBundle.getText("GRN") }),
            new sap.ui.core.ListItem({ key: "Reject", text: oBundle.getText("Reject") }),
            new sap.ui.core.ListItem({ key: "Cancelled", text: oBundle.getText("Cancelled") }),
            new sap.ui.core.ListItem({ key: "Archived", text: oBundle.getText("Archived") })
        ]
    }).addEventDelegate({
        onAfterRendering: function () {
            openWOField4.$().find("input").attr("readonly", true);
        }
    });

    let openWOField6 = cityCB.clone();
    openWOField6.attachChange(function (oEvent) {
        let enteredValue = oEvent.getParameter("value");
        let isValid = openWOField6.getItems().some(item => item.getText() === enteredValue);
        if (!isValid) {
            sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list_for_City"));
            openWOField6.setValue(oBundle.getText("BALI"));
        }
    });

    let openWOField7 = new sap.m.Input({ placeholder: oBundle.getText("Rental_Company_Name") });
    let openWOField8 = new sap.m.Input({ placeholder: oBundle.getText("Leasing_Company_Name") });
    let openWOField11 = new sap.m.Input({ placeholder: oBundle.getText("Workshop_Invoice") });
    let openWOField12 = new sap.m.Input({ placeholder: oBundle.getText("Receipt_Number") });

    let openWOField9 = new sap.m.DatePicker({
        width: "100%",
        displayFormat: "dd-MMM-yyyy",
        valueFormat: "dd-MMM-yyyy",
        placeholder: oBundle.getText("Start_Date"),
        change: function (oEvent) {
            if (!oEvent.getParameter("valid")) {
                this.setValue("");
                sap.m.MessageToast.show("Please select a valid date from the calendar.");
            }
        }
    }).attachBrowserEvent("keydown", function (oEvent) { oEvent.preventDefault(); });

    let openWOField10 = new sap.m.DatePicker({
        width: "100%",
        displayFormat: "dd-MMM-yyyy",
        valueFormat: "dd-MMM-yyyy",
        placeholder: oBundle.getText("End_Date"),
        change: function (oEvent) {
            if (!oEvent.getParameter("valid")) {
                this.setValue("");
                sap.m.MessageToast.show("Please select a valid date from the calendar.");
            }
        }
    }).attachBrowserEvent("keydown", function (oEvent) { oEvent.preventDefault(); });

    var openWOField13 = new sap.m.ComboBox({
        width: "100%",
        placeholder: oBundle.getText("Select_Approver"),
        items: [
            new sap.ui.core.ListItem({ key: "Select", text: oBundle.getText("Select_Approver") }),
            new sap.ui.core.ListItem({ key: "G3", text: oBundle.getText("G3") }),
            new sap.ui.core.ListItem({ key: "G4", text: oBundle.getText("G4") }),
            new sap.ui.core.ListItem({ key: "G5", text: oBundle.getText("G5") }),
            new sap.ui.core.ListItem({ key: "G6", text: oBundle.getText("G6") }),
            new sap.ui.core.ListItem({ key: "G7", text: oBundle.getText("G7") })
        ]
    }).addEventDelegate({
        onAfterRendering: function () {
            openWOField13.$().find("input").attr("readonly", true);
        }
    });


    // ─────────── FORM (Modernized) ───────────
    var Form1 = new sap.ui.layout.form.Form({
        editable: true,
        layout: new sap.ui.layout.form.ResponsiveGridLayout({
            columnsM: 2,
            columnsL: 2,
            columnsXL: 2,
            labelSpanM: 4,
            labelSpanL: 4,
            labelSpanXL: 3
        }),
        formContainers: [
            new sap.ui.layout.form.FormContainer({
                // title: new sap.ui.core.Title({ text: oBundle.getText("Workorder_Filters"), level: "H4" }),
                formElements: [
                    new sap.ui.layout.form.FormElement({ label: oBundle.getText("License_Number"), fields: [openWOField3] }),
                    new sap.ui.layout.form.FormElement({ label: oBundle.getText("City"), fields: [openWOField6] }),
                    new sap.ui.layout.form.FormElement({ label: oBundle.getText("Workshop_Group_Name"), fields: [openWOField1] }),
                    new sap.ui.layout.form.FormElement({ label: oBundle.getText("Workshop_Name"), fields: [openWOField2] }),
                    new sap.ui.layout.form.FormElement({ label: oBundle.getText("Status"), fields: [openWOField4] }),
                    new sap.ui.layout.form.FormElement({ label: oBundle.getText("Rental_Company_Name"), fields: [openWOField7] }),
                    new sap.ui.layout.form.FormElement({ label: oBundle.getText("Leasing_Company_Name"), fields: [openWOField8] }),
                    new sap.ui.layout.form.FormElement({ label: oBundle.getText("Start_Date"), fields: [openWOField9] }),
                    new sap.ui.layout.form.FormElement({ label: oBundle.getText("End_Date"), fields: [openWOField10] }),
                    new sap.ui.layout.form.FormElement({ label: oBundle.getText("Workshop_Invoice"), fields: [openWOField11] }),
                    new sap.ui.layout.form.FormElement({ label: oBundle.getText("Receipt_Number"), fields: [openWOField12] }),
                    new sap.ui.layout.form.FormElement({ label: oBundle.getText("Approver"), fields: [openWOField13] })
                ]
            })
        ]
    });


    // ─────────── BUTTONS ───────────
    var applyBtn = new sap.m.Button({
        type: "Emphasized",
        icon: "sap-icon://filter",
        text: oBundle.getText("Apply_Filter"),
        press: function () {
            filterWoWorkshopGroup = openWOField1.getTokens().length ? openWOField1.getTokens()[0].getKey() : "";
            filterWoWorkshop = openWOField2.getTokens().length ? openWOField2.getTokens()[0].getKey() : "";
            filterWoLicenseNumber = openWOField3.getValue();
            filterWoStatus = openWOField4.getSelectedKey();
            filterWoCity = openWOField6.getValue();
            filterWoRCN = openWOField7.getValue();
            filterWoLCN = openWOField8.getValue();
            filterWoStartDate = openWOField9.getValue();
            filterWoEndDate = openWOField10.getValue();
            filterWoInvoice = openWOField11.getValue();
            filterWoReceiptNumber = openWOField12.getValue();
            filterWoApprover = openWOField13.getValue();

            applySavedFilters(table);
            oDialog.close();
        }
    });

    var clearBtn = new sap.m.Button({
        type: "Reject",
        icon: "sap-icon://reset",
        text: oBundle.getText("Clear_Filter"),
        press: function () {
            filterWoLicenseNumber = "";
            filterWoCity = "";
            filterWoWorkshop = "";
            filterWoWorkshopGroup = "";
            filterWoStatus = "";
            filterWoRCN = "";
            filterWoLCN = "";
            filterWoStartDate = "";
            filterWoEndDate = "";
            filterWoInvoice = "";
            filterWoReceiptNumber = "";
            filterWoApprover = "";

            applySavedFilters(table);
            oDialog.close();
        }
    });

    // ─────────── DIALOG (Modernized) ───────────
    var oDialog = new sap.m.Dialog({
        contentWidth: "40%",
        contentHeight: "auto",
        draggable: true,
        resizable: true,
        title: oBundle.getText("Multi_Filter_Workorder"),
        icon: "sap-icon://filter",
        content: [Form1],
        buttons: [
            clearBtn,
            applyBtn,
            new sap.m.Button({
                text: oBundle.getText("Close"),
                icon: "sap-icon://decline",
                press: function () { oDialog.close(); }
            })
        ]
    }).addStyleClass("sapUiContentPadding sapUiResponsiveContentPadding").open();
}



//Need Verification WO Get Data
var grabVerificationWOJSONArray = [];
function getVerificationWorkorder(){
    oTable4WVerificationWO.setBusy(true);
    
    let oxmaint_role = sessionStorage.getItem('oxmaint_role');
    if(allowedRoles.includes(oxmaint_role) ){
        getWorkorderByStatus("Need Verification",grabVerificationWOJSONArray,oTable4WVerificationWO);
    }else if(oxmaint_role == 'Workshop Group Admin'){
        getWorkorderByStatusAndWorkshopGroup("Need Verification",grabVerificationWOJSONArray,oTable4WVerificationWO);
    }else{
        getWorkorderByStatusAndWorkshop("Need Verification",grabVerificationWOJSONArray,oTable4WVerificationWO);
    }
};

//Pending WO Get Data
var grabPendingWOJSONArray = [];
function getPendingWorkorder(){
    oTableWorkorder.setBusy(true);

    let oxmaint_role = sessionStorage.getItem('oxmaint_role');
    if(allowedRoles.includes(oxmaint_role) ){
        getWorkorderByStatus("Pending Approval",grabPendingWOJSONArray,oTableWorkorder);
    }else if(oxmaint_role == 'Workshop Group Admin'){
        getWorkorderByStatusAndWorkshopGroup("Pending Approval",grabPendingWOJSONArray,oTableWorkorder);
    }else{
        getWorkorderByStatusAndWorkshop("Pending Approval",grabPendingWOJSONArray,oTableWorkorder);
    }
};

//Reject WO Get Data
var grabRejectWOJSONArray = [];
function getRejectWorkorder(){
    oTable4WRejectWO.setBusy(true);

    let oxmaint_role = sessionStorage.getItem('oxmaint_role');
    if(allowedRoles.includes(oxmaint_role) ){
        getWorkorderByStatus("Reject",grabRejectWOJSONArray,oTable4WRejectWO);
    }else if(oxmaint_role == 'Workshop Group Admin'){
        getWorkorderByStatusAndWorkshopGroup("Reject",grabRejectWOJSONArray,oTable4WRejectWO);
    }else{
        getWorkorderByStatusAndWorkshop("Reject",grabRejectWOJSONArray,oTable4WRejectWO,oxmaint_workshop_number);
    }

};

//Open WO Get Data
var grabOpenWOJSONArray = [];
function getOpenWorkorder(){
    oTable4WOpenWO.setBusy(true);

    let oxmaint_role = sessionStorage.getItem('oxmaint_role');
    if(allowedRoles.includes(oxmaint_role) ){
        getWorkorderByStatus("Open",grabOpenWOJSONArray,oTable4WOpenWO);
    }else if(oxmaint_role == 'Workshop Group Admin'){
        getWorkorderByStatusAndWorkshopGroup("Open",grabOpenWOJSONArray,oTable4WOpenWO);
    }else{
        getWorkorderByStatusAndWorkshop("Open",grabOpenWOJSONArray,oTable4WOpenWO,oxmaint_workshop_number);
    }

};

//Completed WO Get Data
var grabCompletedWOJSONArray = [];
function getCompletedWorkorder(){
    oTable4WCompletedWO.setBusy(true);
    
    let oxmaint_role = sessionStorage.getItem('oxmaint_role');
    if(allowedRoles.includes(oxmaint_role) ){
        getWorkorderByStatus("Completed",grabCompletedWOJSONArray,oTable4WCompletedWO);
    }else if(oxmaint_role == 'Workshop Group Admin'){
        getWorkorderByStatusAndWorkshopGroup("Completed",grabCompletedWOJSONArray,oTable4WCompletedWO);
    }else{
        getWorkorderByStatusAndWorkshop("Completed",grabCompletedWOJSONArray,oTable4WCompletedWO,oxmaint_workshop_number);
    }

};

//Closed WO Get Data
var grabClosedWOJSONArray = [];
function getClosedWorkorder(){
    oTable4WClosedWO.setBusy(true);

    let oxmaint_role = sessionStorage.getItem('oxmaint_role');
    if(allowedRoles.includes(oxmaint_role) ){
        getWorkorderByStatus("Closed",grabClosedWOJSONArray,oTable4WClosedWO);
    }else if(oxmaint_role == 'Workshop Group Admin'){
        getWorkorderByStatusAndWorkshopGroup("Closed",grabClosedWOJSONArray,oTable4WClosedWO);
    }else{
        getWorkorderByStatusAndWorkshop("Closed",grabClosedWOJSONArray,oTable4WClosedWO,oxmaint_workshop_number);
    }

};

//GRN WO Get Data
var grabGrnWOJSONArray = [];
function getGrnWorkorder(){
    oTable4WGrnWO.setBusy(true);
    
    let oxmaint_role = sessionStorage.getItem('oxmaint_role');
    if(allowedRoles.includes(oxmaint_role) ){
        getWorkorderByStatus("GRN",grabGrnWOJSONArray,oTable4WGrnWO);
    }else if(oxmaint_role == 'Workshop Group Admin'){
        getWorkorderByStatusAndWorkshopGroup("GRN",grabGrnWOJSONArray,oTable4WGrnWO);
    }else{
        getWorkorderByStatusAndWorkshop("GRN",grabGrnWOJSONArray,oTable4WGrnWO,oxmaint_workshop_number);
    }

};

//Cancelled WO Get Data
var grabCancelledWOJSONArray = [];
function getCancelledWorkorder(){
    oTable4WCancelledWO.setBusy(true);

    
    let oxmaint_role = sessionStorage.getItem('oxmaint_role');
    if(allowedRoles.includes(oxmaint_role) ){
        getWorkorderByStatus("Cancelled",grabCancelledWOJSONArray,oTable4WCancelledWO);
    }else if(oxmaint_role == 'Workshop Group Admin'){
        getWorkorderByStatusAndWorkshopGroup("Cancelled",grabCancelledWOJSONArray,oTable4WCancelledWO);
    }else{
        getWorkorderByStatusAndWorkshop("Cancelled",grabCancelledWOJSONArray,oTable4WCancelledWO,oxmaint_workshop_number);
    }
};

//All WO Get Data
var grab4WAllWoJSONArray = [];
function getAllWorkorderDetails(){
    oTable4WAllWO.setBusy(true);
    
    let oxmaint_role = sessionStorage.getItem('oxmaint_role');
    if(allowedRoles.includes(oxmaint_role) ){
        getWorkorderAllStatus();
    }else if(oxmaint_role == 'Workshop Group Admin'){
        getWorkorderAllStatusAndWorkshopGroup();
    }else{
        getWorkorderAllStatusAndWorkshop();
    }


};


