

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

var oDateVehicleOverView1 = new sap.m.DatePicker({width: "100%",displayFormat: "dd-MMM-yyyy",valueFormat: "dd-MMM-yyyy"});
var oDateVehicleOverView2 = new sap.m.DatePicker({width: "100%",displayFormat: "dd-MMM-yyyy",valueFormat: "dd-MMM-yyyy"});

var vehicleOverViewBlockLayout =  new sap.ui.layout.BlockLayout({
    background: sap.ui.layout.BlockBackgroundType.Dashboard,
	content: [
        new sap.ui.layout.BlockLayoutRow({
            content: [
                new sap.ui.layout.BlockLayoutCell({
                    titleAlignment:"Center",
                    title: oBundle.getText("Vehicle_Overview"),
                    content: [
                        
                        new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                            items: [ new sap.m.Label({required: true, width:"100%",text: oBundle.getText("Select_Vehicle")}),
                                    new sap.m.Label({width:"20px",text: ""}),oSearchVehicleOverView]}),
                        new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                            items: [ new sap.m.Label({required: true, width:"100%",text: oBundle.getText("Start_Date")}),
                                    new sap.m.Label({width:"20px",text: ""}),oDateVehicleOverView1]}),
                        new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                            items: [new sap.m.Label({required: true, text: oBundle.getText("End_Date")}),
                                    new sap.m.Label({width:"20px",text: ""}),oDateVehicleOverView2,]}),
                        new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                            items: [
                                new sap.m.Button({width:"100px",text:oBundle.getText("View"),icon: "sap-icon://show",
                                    press: function () {

                                        var vehicle_number = oSearchVehicleOverView.getValue();
                                                                              
                                        if (validation(vehicle_number, oBundle.getText("Vehicle_Number"))) { return; }

                                        if (!oDateVehicleOverView1.isValidValue() || !oDateVehicleOverView2.isValidValue()) {
                                            sap.m.MessageBox.error(oBundle.getText("Select_Valid_Start_and_End_Date"));
                                            return;
                                        }

                                        var getVehicle = vehicleJSONArray.filter(function(obj, index){
                                            return (obj.vehicle_serial === vehicle_number);
                                        });

                                        var startDate = oDateVehicleOverView1.getValue();
                                        var endDate = oDateVehicleOverView2.getValue()+" "+"11:59 PM";

                                        vehicleOverviewDialog(getVehicle[0],startDate,endDate);
                                    }
                                })
                        ]})
                        ]
                })]
        })
		
	]
}).addStyleClass('homeLayout');


var vehicleViewMaintenanceCost = new sap.m.Label({width:"100%",textAlign:"Center",text: "0",design: sap.m.LabelDesign.Bold}).addStyleClass('bigBoldText');
var vehicleViewMaintenancePartCost = new sap.m.Label({width:"100%",textAlign:"Center",text: "0",design: sap.m.LabelDesign.Bold}).addStyleClass('bigBoldText');
var vehicleViewMaintenanceLaborCost = new sap.m.Label({width:"100%",textAlign:"Center",text: "0",design: sap.m.LabelDesign.Bold}).addStyleClass('bigBoldText');
// var vehicleViewTotalRun = new sap.m.Label({width:"100%",textAlign:"Center",text: "0",design: sap.m.LabelDesign.Bold}).addStyleClass('bigBoldText');


        var vehicleViewIssueList = new sap.m.List({ showUnread: true, backgroundDesign: sap.m.BackgroundDesign.Solid });

            var vehicleViewIssueListItem1 = new sap.m.StandardListItem({
			    title: oBundle.getText("Total_Issue_Reported"),
			    icon: sap.ui.core.IconPool.getIconURI("inspect-down"),
			    iconInset: true,unread: false, info: "0",
			    infoState: "Error"
			});
             var vehicleViewIssueListItem2 = new sap.m.StandardListItem({
			    title: oBundle.getText("Open_Issue"),
			    icon: sap.ui.core.IconPool.getIconURI("cancel"),
			    iconInset: true, unread: false, info: "0",
			    infoState: "Error"
			});
              
            var vehicleViewIssueListItem3 = new sap.m.StandardListItem({
			    title: oBundle.getText("Resolved"),
			    icon: sap.ui.core.IconPool.getIconURI("complete"),
			    iconInset: true,
			    unread: false,
			    counter: 0,
			    selected: true,
			    info: "0",
			    infoState: "Success"
			});

          
            vehicleViewIssueList.addItem(vehicleViewIssueListItem1);
            vehicleViewIssueList.addItem(vehicleViewIssueListItem2);
            vehicleViewIssueList.addItem(vehicleViewIssueListItem3);


      var vehicleViewWorkorderList = new sap.m.List({ showUnread: true,
				backgroundDesign: sap.m.BackgroundDesign.Solid
			});

            var vehicleViewWOStatuslistItem1 = new sap.m.StandardListItem({
			    title: oBundle.getText("Total_Work_Order"),
			    icon: sap.ui.core.IconPool.getIconURI("wrench"),
			    iconInset: true,
			    unread: false,
			    info: "0",
			    infoState: "Error"
			});
            var vehicleViewWOStatuslistItem2 = new sap.m.StandardListItem({
			    title: oBundle.getText("Completed"),
			    icon: sap.ui.core.IconPool.getIconURI("complete"),
			    iconInset: true,
			    unread: false,
			    counter: 0,
			    selected: true,
			    info: "0",
			    infoState: "Error"
			    //press: tab2
			});
            var vehicleViewWOStatuslistItem3 = new sap.m.StandardListItem({
			    title: oBundle.getText("Open"),
			    icon: sap.ui.core.IconPool.getIconURI("create"),
			    iconInset: true,
			    unread: false,
			    counter: 0,
			    selected: true,
			    info: "0",
			    infoState: "Error"
			});
             var vehicleViewWOStatuslistItem4 = new sap.m.StandardListItem({
			    title: oBundle.getText("Reject"),
			    // icon: sap.ui.core.IconPool.getIconURI("line-chart-time-axis"),
			    icon: "sap-icon://reset",
			    iconInset: true,
			    unread: false,
			    counter: 0,
			    selected: true,
			    info: "0",
			    infoState: "Error"
			});
             var vehicleViewWOStatuslistItem5 = new sap.m.StandardListItem({
			    title: oBundle.getText("Pending_Approval"),
			    icon: sap.ui.core.IconPool.getIconURI("pending"),
			    iconInset: true,
			    unread: false,
			    counter: 0,
			    selected: true,
			    info: "0",
			    infoState: "Error"
			});
             var vehicleViewWOStatuslistItem6 = new sap.m.StandardListItem({
			    title: oBundle.getText("Closed"),
			    icon: "sap-icon://decline",
			    iconInset: true,
			    unread: false,
			    counter: 0,
			    selected: true,
			    info: "0",
			    infoState: "Error"
			});

            var vehicleViewWOStatuslistItem7 = new sap.m.StandardListItem({
			    title: oBundle.getText("GRN"),
			    // icon: sap.ui.core.IconPool.getIconURI("future"),
			    icon: "sap-icon://my-sales-order",
			    iconInset: true,
			    unread: false,
			    counter: 0,
			    selected: true,
			    info: "0",
			    infoState: "Error"
			});
            var vehicleViewWOStatuslistItem8 = new sap.m.StandardListItem({
			    title: oBundle.getText("Cancelled"),
			    icon: "sap-icon://cancel",
			    iconInset: true,
			    unread: false,
			    counter: 0,
			    selected: true,
			    info: "0",
			    infoState: "Error"
			});
            vehicleViewWorkorderList.addItem(vehicleViewWOStatuslistItem1);
            vehicleViewWorkorderList.addItem(vehicleViewWOStatuslistItem2);//Completed
            vehicleViewWorkorderList.addItem(vehicleViewWOStatuslistItem3); //Open
            vehicleViewWorkorderList.addItem(vehicleViewWOStatuslistItem4); //Reject
            vehicleViewWorkorderList.addItem(vehicleViewWOStatuslistItem5); //Pending Approval
            vehicleViewWorkorderList.addItem(vehicleViewWOStatuslistItem6); //Closed
            vehicleViewWorkorderList.addItem(vehicleViewWOStatuslistItem7); //GRN
            vehicleViewWorkorderList.addItem(vehicleViewWOStatuslistItem8); // Cancelled


var vehicleViewListTopDefective = new sap.m.List({inset : false});

 
var vehicleViewOverView =  new sap.ui.layout.BlockLayout({
        background: sap.ui.layout.BlockBackgroundType.Dashboard,
        content: [
            new sap.ui.layout.BlockLayoutRow({
                content: [
                    new sap.ui.layout.BlockLayoutCell({
                        content: [vehicleViewMaintenanceCost],
                        width: 1,
                        titleAlignment:"Center",
                        title: oBundle.getText("Total_Workorder_Cost")
                    }),
                    new sap.ui.layout.BlockLayoutCell({
                        content: [vehicleViewMaintenancePartCost],
                        width: 1,
                        titleAlignment:"Center",
                        title: oBundle.getText("Total_Parts_Cost")
                    }),
                    new sap.ui.layout.BlockLayoutCell({
                        content: [vehicleViewMaintenanceLaborCost],
                        width: 1,
                        titleAlignment:"Center",
                        title: oBundle.getText("Total_Labor_Cost")
                    }),

                    // new sap.ui.layout.BlockLayoutCell({
                    //     content: [vehicleViewTotalRun],
                    //     width: 1,
                    //     titleAlignment:"Center",
                    //     title: oBundle.getText("Total_Running")
                    // })
            ]}),
            new sap.ui.layout.BlockLayoutRow({
                content: [
                new sap.ui.layout.BlockLayoutCell({
                    content: [vehicleViewIssueList],
                    width: 1,
                    titleAlignment:"Center",
                    title: oBundle.getText("Issue_Report")
                }),
                    new sap.ui.layout.BlockLayoutCell({
                    content: [vehicleViewWorkorderList],
                    width: 1,
                    titleAlignment:"Center",
                    title: oBundle.getText("Work_order_Summary")
                }),
                    new sap.ui.layout.BlockLayoutCell({
                    content: [vehicleViewListTopDefective],
                    width: 1,
                    titleAlignment:"Center",
                    title: oBundle.getText("Top_Deffective_Items")
                })]
        })]
    }).addStyleClass('homeLayout');                         


var vehicleViewInspectionTable = oTableInspection.clone();
vehicleViewInspectionTable.destroyHeaderToolbar();
vehicleViewInspectionTable.setHeaderToolbar(new sap.m.Toolbar({
    content: [
        new sap.m.Label({text: oBundle.getText("INSPECTION_HISTORY")}),
        new sap.m.ToolbarSpacer(),
        new sap.m.SearchField({
            placeholder: oBundle.getText("Search"),
            width: "300px",
            liveChange: function (event) {
                var oBinding = vehicleViewInspectionTable.getBinding("items");
                var searchStr = this.getValue();
                if (oBinding) {
                    var oFilters = [
                        new sap.ui.model.Filter("report_number", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("inspection_date", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("license_number", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("vehicle_model", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("location", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("inspector_name", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("vehicle_status", sap.ui.model.FilterOperator.Contains, searchStr),
                    ];
                    var filterObj = new sap.ui.model.Filter(oFilters, false);
                    oBinding.filter(filterObj);
                } else {
                    oBinding.filter([]);
                }
            }
        }),
    ]
}));


var vehicleViewWOTable = oTableWorkorder.clone();
vehicleViewWOTable.destroyHeaderToolbar(); 
vehicleViewWOTable.setHeaderToolbar(new sap.m.Toolbar({
    content: [
        new sap.m.Label({text: oBundle.getText("WORKORDER_HISTORY")}),
        new sap.m.ToolbarSpacer(),
        new sap.m.SearchField({
            placeholder: oBundle.getText("Search"),
            width: "300px",
            liveChange: function (event) {
                var oBinding = vehicleViewWOTable.getBinding("items");
                var searchStr = this.getValue();
                if (oBinding) {
                    var oFilters = [
                        new sap.ui.model.Filter("wo_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("wo_title", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("wo_memo", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("city", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("license_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("vehicle_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("chassis_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("engine_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("assigned_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("model", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("make", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("vehicle_color", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("rental_company_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("leasing_company_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("assigned_id", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("assigned_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("ws_group_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("ws_group_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("workshop_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("workshop_number", sap.ui.model.FilterOperator.Contains, searchStr),
                    ];
                    var filterObj = new sap.ui.model.Filter(oFilters, false);
                    oBinding.filter(filterObj);
                } else {
                    oBinding.filter([]);
                }
            }
        }),
    ]
}));
var vehicleViewScheduleTable = oTableSchedule.clone();
// var vehicleViewIncidentTable = oTableIncident.clone();


vehicleViewWOTable.setHeaderToolbar(new sap.m.Toolbar({
          content: [new sap.m.Label({text: oBundle.getText("MAINTENANCE_WORKORDER_HISTORY")})]
      }));
// vehicleViewScheduleTable.setHeaderToolbar(new sap.m.Toolbar({
//           content: [new sap.m.Label({text: oBundle.getText("SCHEDULES")})]
//       }));
// vehicleViewIncidentTable.setHeaderToolbar(new sap.m.Toolbar({
//           content: [new sap.m.Label({text: oBundle.getText("Incident_Report_cap")})]
//       }));

/*
var oTableVehicleAttachment = new sap.m.Table({
            noDataText:oBundle.getText("No_Data"),
            mode: "Delete",
            "delete" : function(oEvent) { 
			       var oContext = oEvent.getParameter("listItem").getBindingContext();
                    var mid = oContext.getObject().id;
                    var vehicle_id = oContext.getObject().vehicle_id;
                    attachmentRemove(mid,vehicle_id);
		        },
          columns: [
                new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Document_Type"),design: sap.m.LabelDesign.Bold})}),
                new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Description"),design: sap.m.LabelDesign.Bold})}),
                new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Download"), design: sap.m.LabelDesign.Bold}),
                minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true})
          ]
      }).addStyleClass('withGrid');

 var oTableVehicleAttachmentTemplate = new sap.m.ColumnListItem({
        cells: [
            new sap.m.Label({ wrapping: true, text: "{attachment_type}" }),
            new sap.m.Label({ wrapping: true, text: "{attachment_name}" }),
            new sap.m.Button({
                text: oBundle.getText("Download"),
                icon: "sap-icon://download",
                type: sap.m.ButtonType.Emphasized,
                press: function (e) {
                    var model = this.getModel();
                    var path = e.getSource().getBindingContext().getPath();
                    var obj = model.getProperty(path);
                    var blob_path = obj['attachment_url'];

                    window.open(blob_path, "_blank");
                }
        })]
    });
*/

/*
var vehicle_view_assign_btn =  new sap.m.Button({ text: oBundle.getText("Forms"), 
        type: sap.m.ButtonType.Accept,icon: "sap-icon://survey"});

var formAssignList = new sap.m.List({mode: "Delete",
    "delete": function (oEvent) {
        var olist = oEvent.getParameter("listItem");
        var oContext = oEvent.getParameter("listItem").getBindingContext();
        var mid = oContext.getObject().id;
        sap.m.MessageBox.show(oBundle.getText("Do_you_want_to_remove_item"),
        sap.m.MessageBox.Icon.ERROR,
        oBundle.getText("Alert"),
        [sap.m.MessageBox.Action.YES, sap.m.MessageBox.Action.NO],
        function (bConfirmed) {
            if (bConfirmed == "YES") {
                formAssignList.removeItem(olist);
                HVI_Assign_Form.del({ id: mid}).done(function () { });
            }
        });
    },
    headerToolbar: new sap.m.Toolbar({
        content: [new sap.m.Label({ text: oBundle.getText("Assign_Inspection_Form"),design: sap.m.LabelDesign.Bold }), 
        new sap.m.ToolbarSpacer(),vehicle_view_assign_btn]
    })
});
*/


var oChartVehicleMeterHistory = new sap.viz.ui5.controls.VizFrame({width: "100%", height: "250px",
    legendVisible:false,uiConfig:{ applicationSet:"fiori"},vizType:"column",
    vizProperties:{
        title:{visible: false},
        valueAxis: {title: {visible: true}},
        categoryAxis: {title: {visible: true}},
            plotArea: {
                dataLabel: {visible: true},
                isRoundCorner: true,
                animation:{dataLoading:true},
                drawingEffect: sap.viz.ui5.types.VerticalBar_drawingEffect.glossy,
            }
    },
    dataset: new sap.viz.ui5.data.FlattenedDataset({
        dimensions: [{name:  oBundle.getText('Date'),value: "{created_date}"}],
        measures: [{ name:  oBundle.getText('Odometer'),value: '{odometer}'}],
        data: {path: "/modelData"}
    }),
    feeds:[new sap.viz.ui5.controls.common.feeds.FeedItem({
            uid : "primaryValues",type: "Measure",
            values: [ oBundle.getText("Odometer")]
        }),
        new sap.viz.ui5.controls.common.feeds.FeedItem({
            uid: "axisLabels",type: "Dimension",
            values: [ oBundle.getText("Date")]
        })
    ]
});


var oTableVehicleMeterHistory = new sap.m.Table({
        growing: true, noDataText:oBundle.getText("No_Data"),
        growingTriggerText:oBundle.getText("More"),
        sticky:[sap.m.Sticky.ColumnHeaders,sap.m.Sticky.HeaderToolbar,sap.m.Sticky.InfoToolbar],
        growingThreshold: 25,growingScrollToLoad : false,
        columns: [
            new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Vehicle"),design: sap.m.LabelDesign.Bold})}),
            new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Odometer"),design: sap.m.LabelDesign.Bold})}),
            new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Status"),design: sap.m.LabelDesign.Bold})}),
            new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Type"),design: sap.m.LabelDesign.Bold})}),
            new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Source"),design: sap.m.LabelDesign.Bold})}),
            new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Date"),design: sap.m.LabelDesign.Bold})}),
        ]
    });

var oTemplateVehicleMeterHistory = new sap.m.ColumnListItem({
        cells: [
            new sap.m.VBox({
                items:[new sap.m.Label({wrapping:true, text: "{vehicle_number}" }),
                    new sap.m.Label({wrapping:true, text: "{vehicle_name}"}).addStyleClass("sapUiTinyMarginTop"),
                ]}),
            new sap.m.HBox({
                items:[new sap.m.Label({ wrapping: true, text: "{odometer}" }),
                        new sap.m.Label({ wrapping: true, text: "{odometer_unit}" }).addStyleClass("sapUiTinyMarginBeginEnd"),
                ]}),
            new sap.tnt.InfoLabel({
                text: { path: "status",
                    formatter: function (status) {
                        
                        if (status == "2" || status == "4") {
                            this.setColorScheme(3);
                        }else if (status == "3") {
                            this.setColorScheme(1);
                        }else if (status == "5") {
                            this.setColorScheme(9);
                        }else{
                            this.setColorScheme(8);
                        }
                        return getVehicleStatus(status);
                    }
                }
            }),
            
            new sap.m.Label({wrapping:true, text: { path: "type",
                formatter: function (type) { return getVehicleHistoryType(type);}
            }}),
            new sap.m.Label({wrapping:true, text: { path: "source",
                formatter: function (source) { return getVehicleHistorySource(source);}
            }}),
            new sap.m.Label({ wrapping: true, text: "{created_date}" })
    ]});


var vehicleViewTab;

function vehicleOverviewDialog(obj,startDate,endDate,src){

    var blockLayout =  new sap.ui.layout.BlockLayout({
        content: [
            new sap.ui.layout.BlockLayoutRow({
                content: [
                    new sap.ui.layout.BlockLayoutCell({ width: 4, 
                    content: [
                        new sap.ui.layout.VerticalLayout({ content: [
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Chassis_Number"), text: obj['chassis_number'] }),
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Engine_Number"), text: obj['engine_number']}),
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Color") , text: obj['vehicle_color']}),
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Vehicle_year"), text: obj['model_year'] }),
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Branch"), text: obj['branch'] }),
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Make") , text: obj['make']+ ` (${obj['make_id']})`}),
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Model") , text: obj['model'] + `(${obj['model_id']})`}),
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Transmission") , text: obj['transmission']}),
                        ]}),
                        
                    ]}),
                    new sap.ui.layout.BlockLayoutCell({ width: 4, content: [
                        new sap.ui.layout.VerticalLayout({ content: [
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Jaya_Vehicle_Location"), text: obj['vehicle_status'] }),
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Jaya_Driver_ID"), text: obj['jaya_driver_id'] }),
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Driver_Name"), text: obj['driver_name'] }),
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Driver_Type"), text: obj['driver_type'] }),
                            new sap.m.ObjectAttribute({ title: oBundle.getText("E-mail"), text: obj['driver_email'] }),
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Handover_Date"), text: obj['handover_date'] }),
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Rental_Company_Name") , text: obj['rental_company_name']}),
                            new sap.m.ObjectAttribute({ title: oBundle.getText("Leasing_Company_Name"), text: obj['leasing_company_name'] }),

                        ]}),
                    ]}),

                    new sap.ui.layout.BlockLayoutCell({ width: 2, content: [
                        new sap.f.Avatar({ width: "150px", displaySize: "Custom", customDisplaySize: "150px",displayShape: "Square", 
                            src: obj['imgurl']
                        }),
                    ]}),
                ]
            }),
            
        ]
    });


    vehicleViewTab = new sap.m.IconTabBar({upperCase: true,applyContentPadding: false,
        items: [
            new sap.m.IconTabFilter({key:"1",text: oBundle.getText("Overview"),content: [blockLayout,vehicleViewOverView]}),
            new sap.m.IconTabFilter({key:"3",text: oBundle.getText("Inspection"),count: "0",content: [vehicleViewInspectionTable]}),
            new sap.m.IconTabFilter({key:"4",text: oBundle.getText("Work_Order"),count: "0",content: [vehicleViewWOTable]}),
            new sap.m.IconTabFilter({key:"6",text: oBundle.getText("Schedule"),count: "0",content: [vehicleViewScheduleTable]}),
            // new sap.m.IconTabFilter({enabled:false,key:"2",text: oBundle.getText("Meter_History"),content: [oChartVehicleMeterHistory,oTableVehicleMeterHistory]}),
            // new sap.m.IconTabFilter({visible:false,key:"7",text: oBundle.getText("Incident"),count: "0",content: []}),
            // new sap.m.IconTabFilter({visible:false,key:"9",text: oBundle.getText("Documents"),count: "0",content: [oTableVehicleAttachment]}),
            // new sap.m.IconTabFilter({visible:false,key:"10",text: oBundle.getText("Forms"),count: "0",content: [formAssignList]}),
            
        ]
    });

    var tabItems =  vehicleViewTab.getItems();


    var oDialog = new sap.m.Dialog({contentWidth:"100%",contentHeight:"100%",draggable:true, resizable: true,
        title: oBundle.getText("Vehicle_Overview")+" - "+obj['license_number']+" - "+obj['id'],
        content: [vehicleViewTab],
        beginButton: new sap.m.Button({text: "Close",press: function(oEvent){oDialog.close();}})
    }).open();

    setVehicleOverviewData(obj,startDate,endDate);
   
   

    // if(hvi_user_access!=null && hvi_user_access!="undefined"){
    //     if(hvi_user_access.indexOf('1')==-1){           //inspection
    //          tabItems[2].setVisible(false);
    //     }
    //     if(hvi_user_access.indexOf('5')==-1){           //workorder
    //         tabItems[3].setVisible(false);
    //     }
        
    //     if(hvi_user_access.indexOf('6')==-1){           //schedule
    //         tabItems[4].setVisible(false);
    //     }
    //     // if(hvi_user_access.indexOf('7')==-1){           //incident
    //     //     tabItems[5].setVisible(false);
    //     // }
    // }

 }

function setVehicleOverviewData(obj,startDate,endDate){

    var tabItems =  vehicleViewTab.getItems();
    tabItems[1].setCount("0");
    tabItems[2].setCount("0");
    tabItems[3].setCount("0");
    // tabItems[5].setCount("0");
    // tabItems[7].setCount("0");

    var vehicleNumber = obj['license_number'];
    var vehicle_name = obj['vehicle_name'];

    // vehicle_view_assign_btn.attachPress(function () {
    //     assignFormDialog(formAssignList,2,vehicleNumber,vehicle_name);
    // });

    //  var attachmentVehicleBtn = new sap.m.Button({ text: oBundle.getText("Upload_Document"), 
    //         type: sap.m.ButtonType.Accept,
    //         icon: sap.ui.core.IconPool.getIconURI("upload"), press: function () {
    //             uploadVehicleAttachmentDialog(obj['id'],vehicleNumber);
    //         } 
    //     });
   
    // oTableVehicleAttachment.setInfoToolbar(new sap.m.Toolbar({
    //         content: [new sap.m.Label({text: oBundle.getText("Documents")}),
    //                   new sap.m.ToolbarSpacer(),attachmentVehicleBtn]
    //     }));

    // getAttachmentVehicle(obj['id']);
    // getAssignedForm(obj['vehicle_serial'],formAssignList);
   
   
    
    var oDataTopFaulty = [];
    var oDataFaulty = [];
    var totalIssueReported = 0;
    var totalResolved = 0;

    for (var i = 0; i < inspectionJSONArray.length; i++) {

        if(vehicleNumber == inspectionJSONArray[i]['license_number']){
               
            var repair = inspectionJSONArray[i]['repair'];
            var replace = inspectionJSONArray[i]['replace'];
                    
            if (repair == null) { repair = ""; }
            if (replace == null) { replace = ""; }

            var faultyItems = repair +repair;

            
            var faultyItemsAreay = faultyItems.split("^");
            if (faultyItemsAreay.length > 1){
                totalIssueReported = totalIssueReported + 1;
            }

            for (var j = 1; j < faultyItemsAreay.length; j++) {

                if (oDataFaulty.indexOf(faultyItemsAreay[j]) > -1) {
                    var objValue = oDataTopFaulty[oDataFaulty.indexOf(faultyItemsAreay[j])].count;
                    oDataTopFaulty[oDataFaulty.indexOf(faultyItemsAreay[j])].count = parseInt(objValue) + 1;
                } else {
                    oDataFaulty.push(faultyItemsAreay[j]);
                    oDataTopFaulty.push({ faulty_item: faultyItemsAreay[j], count: 1 });
                }
            }
        }          
    }

    // var taskItems = inspectionFaultJSONArray.filter(function (obj, index) {
    //     return (obj.vehicle_number === vehicleNumber && obj.task_status === "4");
    // });
    // totalResolved = taskItems.length;
    totalResolved = 0;

    vehicleViewIssueListItem1.setInfo(totalIssueReported);
    vehicleViewIssueListItem2.setInfo(totalIssueReported-totalResolved);
    vehicleViewIssueListItem3.setInfo(totalResolved);
    


    oDataTopFaulty.sort(function (a, b) {
        return b.count - a.count;
    });

    var oModelTopFaulty = new sap.ui.model.json.JSONModel();
    oModelTopFaulty.setData({ modelData: oDataTopFaulty.slice(0, 7) });
    vehicleViewListTopDefective.setModel(oModelTopFaulty);

    var oItemTopFaultyTemplate = new sap.m.StandardListItem({
        title: "{faulty_item}",
        info: "{count}",
        infoState: "Error"
    });
    vehicleViewListTopDefective.bindAggregation("items", "/modelData", oItemTopFaultyTemplate);

   

    


        //#####################  Meter History   #######   
        // oTableVehicleMeterHistory.setBusy(true);
        // HVI_VehiclesHistory.where(filterQueryVehicleViewMeterHistory,emailUser,vehicleNumber,startDate,endDate).orderByDescending("createdAt").read().done(function (results) {
            
        //     var oModel = new sap.ui.model.json.JSONModel();
        //     oModel.setData({ modelData: results });
        //     oTableVehicleMeterHistory.setModel(oModel);
            
        //     oTableVehicleMeterHistory.bindItems({
        //         path: "/modelData",
        //         template : oTemplateVehicleMeterHistory
        //     });     
                
        //     oChartVehicleMeterHistory.setModel(oModel);
        //     oTableVehicleMeterHistory.setBusy(false);  

        //     var resultsExt = results;

        //     resultsExt.sort(function (a, b) {
        //         return b.odometer - a.odometer;
        //     });

        //     var totalRunning = 0;

        //     if(resultsExt.length>1){
        //         var odometer1 = resultsExt[0]['odometer'];
        //         var odometer2 = resultsExt[resultsExt.length-1]['odometer'];
        //         totalRunning = parseFloat(odometer1) - parseFloat(odometer2);
        //     }

        //     vehicleViewTotalRun.setText(totalRunning);
    
        // });
        //#####################  Meter History   #######   


    //#####################  Inspection   #######
    vehicleViewInspectionTable.setBusy(true);
    Car_Inspection.where(filterQueryVehicleViewInspection,emailUser,vehicleNumber,startDate,endDate).take(2000).orderByDescending("createdAt").read().done(function (results) {
        // console.log(results)
        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        vehicleViewInspectionTable.setModel(oModel);
        vehicleViewInspectionTable.bindItems({
            path: "/modelData",
            template: inspectionTemplate
        });
        vehicleViewInspectionTable.setBusy(false);
        tabItems[1].setCount(results.length);
    });
  //#####################  Inspection   #######

    //#####################  Workorder   #######
    vehicleViewWOTable.setBusy(true);
    Car_Workorder.where(filterQueryVehicleViewWorkorder,emailUser,vehicleNumber,startDate,endDate).take(2000).orderByDescending("createdAt").read().done(function (results) {
        
        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        vehicleViewWOTable.setModel(oModel);
        vehicleViewWOTable.bindItems({
            path: "/modelData",
            template: workorderTemplate
        });
        vehicleViewWOTable.setBusy(false);
        tabItems[2].setCount(results.length);

        var totalMaintenanceCost = 0;
        var totalMaintenancePartCost = 0;
        var totalMaintenanceLaborCost = 0;
        var totalWoCount = 0;
        var pendingWOCount1 = 0;
        var openWOCount2 = 0;
        var completedWOCount3 = 0;
        var closedWOCount4 = 0;
        var grnWOCount5 = 0;
        var rejectWOCount6 = 0;
        var cancelledWOCount6 = 0;
    
        for (var i = 0; i < results.length; i++) {
    
            totalMaintenanceCost = totalMaintenanceCost + parseFloat(results[i]['total_wo_cost']);
            totalMaintenancePartCost = totalMaintenancePartCost + parseFloat(results[i]['total_parts_cost']);
            totalMaintenanceLaborCost = totalMaintenanceLaborCost + parseFloat(results[i]['total_labor_cost']);
            
            var order_status = results[i]['wo_status'];
        
            totalWoCount++;
    
            if (order_status == "Pending Approval") {
                pendingWOCount1++;
            } else if (order_status == "Open") {
                openWOCount2++;
            } else if (order_status == "Completed") {
                completedWOCount3++; 
            } else if (order_status == "Closed") {
                closedWOCount4++;   
            } else if (order_status == "GRN") {
                grnWOCount5++;
            } else if (order_status == "Reject") {
                rejectWOCount6++; 
            } else if (order_status == "Cancelled") {
                cancelledWOCount6++;
            } 
                
        }
        //WO Status
        vehicleViewWOStatuslistItem1.setInfo(totalWoCount);
        vehicleViewWOStatuslistItem2.setInfo(completedWOCount3);
        vehicleViewWOStatuslistItem3.setInfo(openWOCount2);
        vehicleViewWOStatuslistItem4.setInfo(rejectWOCount6);
        vehicleViewWOStatuslistItem5.setInfo(pendingWOCount1);
        vehicleViewWOStatuslistItem6.setInfo(closedWOCount4);
        vehicleViewWOStatuslistItem7.setInfo(grnWOCount5);
        vehicleViewWOStatuslistItem8.setInfo(cancelledWOCount6);

        var roundtotalMaintenanceCost = Math.round(totalMaintenanceCost * 100) / 100;
        var roundtotalMaintenancePartCost = Math.round(totalMaintenancePartCost * 100) / 100;
        var roundtotalMaintenanceLaborCost = Math.round(totalMaintenanceLaborCost * 100) / 100;
        vehicleViewMaintenanceCost.setText(formatToIDR(roundtotalMaintenanceCost));
        vehicleViewMaintenancePartCost.setText(formatToIDR(roundtotalMaintenancePartCost));
        vehicleViewMaintenanceLaborCost.setText(formatToIDR(roundtotalMaintenanceLaborCost));


    });
      //#####################  Workorder   #######     

  
        //#####################  Schedule   #######     
        var scheduleFilterArray = scheduleJSONArray.filter(function(val,ind){
            return val.license_number == vehicleNumber;
        })
        

         var oModelSchedule = new sap.ui.model.json.JSONModel();
         oModelSchedule.setData({ modelData: scheduleFilterArray });
         vehicleViewScheduleTable.setModel(oModelSchedule);
         oModelSchedule.setSizeLimit(scheduleFilterArray.length);

         vehicleViewScheduleTable.bindItems({
		    path: "/modelData",
		    template : scheduleTemplate
	    });
        // tabItems[3].setCount(scheduleFilterArray.length);
        //#####################  Schedule   #######     


        //#####################  Incident   #######
        // vehicleViewIncidentTable.setBusy(true);
        // HVI_Incident.where(filterQueryVehicleViewIncident,emailUser,vehicleNumber,startDate,endDate).take(1000).orderByDescending("createdAt").read().done(function (results) {
        
        //     var oModel = new sap.ui.model.json.JSONModel();
        //     oModel.setData({ modelData: results });
        //     vehicleViewIncidentTable.setModel(oModel);
        //     vehicleViewIncidentTable.bindItems({
        //         path: "/modelData",
        //         template: incidentTemplate
        //     });
        //     vehicleViewIncidentTable.setBusy(false);
        //     tabItems[5].setCount(results.length);
        // });
        //#####################  Incident   #######             

}

/*
function uploadVehicleAttachmentDialog(vehicle_id,vehicle_number){

        var oDialogVehicleAttachment =  new sap.m.BusyDialog({text: oBundle.getText('Document_Uploading')});
 
        var tsLong = new Date().getTime();
        var userFolder = emailUser.replace(/[@.]/g,"");
        var vehicle_number = vehicle_number.replace(/[^.,a-zA-Z0-9]/g,"");
        var	blob_name  = vehicle_number+"_"+tsLong+"";

        var oFileUploaderVehicleAttachment = new sap.ui.unified.FileUploader({
            name: "pdf",
            uploadUrl: "https://oxmaint.com/upload/vehicle_attachment.php",
            sendXHR: true,
            maximumFileSize: 5,
            fileType: ['jpeg', 'jpg', 'JPG', 'JPEG', "PNG", 'png','pdf', 'ppt', 'xls', 'xlsx', 'doc','jpeg', 'jpg', 'png'],
            width: "100%",
            placeholder: oBundle.getText("Choose_a_file_for_uploading"),
            parameters: [
					new sap.ui.unified.FileUploaderParameter({ name: "name", value: blob_name }),
                    new sap.ui.unified.FileUploaderParameter({ name: "email", value: userFolder })
				],
            uploadProgress: function (oEvent) {
                var nLoaded, nTotal;
                if (oEvent.getParameter("lengthComputable")) {
                    nLoaded = oEvent.getParameter("loaded");
                    nTotal = oEvent.getParameter("total");
                    oDialogVehicleAttachment.setText(Math.floor((nLoaded / nTotal) * 100) + "%");
                }
            },
            fileSizeExceed: function (oEvent) {
                oDialogVehicleAttachment.close();
                sap.m.MessageBox.error(oBundle.getText("file_size_warning"));
            },
            typeMissmatch: function (oEvent) {
                oDialogVehicleAttachment.close();
                sap.m.MessageBox.error(oBundle.getText("This_is_not_valid_file_type"));
            },
            uploadAborted: function (oEvent) {  standartBusyDialog.close();},
            uploadComplete: function (oEvent) {
                var ext = oEvent.getParameter("responseRaw").replace(/"/g, "");
                var attachName = attachmentName.getValue();
                var attachment_type = attachedTypeDB.getValue();

                var attachment_url = "https://oxmaint.com/upload/vehicle_attachment/"+userFolder+"/"+blob_name+"."+ext;

                var created_date = getIndonesianTime();
                 HVI_VehicleDoc.insert({master_email:emailUser, vehicle_id: vehicle_id, vehicle_number:vehicle_number,attachment_name: attachName, 
                        attached_by: operatedBy,attached_date:created_date, attachment_url: attachment_url,attachment_type:attachment_type
                }).done(function () {   
                    getAttachmentVehicle(vehicle_id);
                    oDialogVehicleAttachment.close();
                    oDialog.close();
                    
                });
            }
        });


    var attachmentName = new sap.m.Input({});

    var attachedTypeDB = new sap.m.ComboBox();
    attachedTypeDB.setWidth("100%");
    attachedTypeDB.addItem(new sap.ui.core.ListItem({key:"1",text:oBundle.getText("Select_Type")}));
    attachedTypeDB.addItem(new sap.ui.core.ListItem({key:"2",text:oBundle.getText("Invoice")}));
    attachedTypeDB.addItem(new sap.ui.core.ListItem({ key: "2", text: oBundle.getText("Insurance") }));
    attachedTypeDB.addItem(new sap.ui.core.ListItem({ key: "2", text: oBundle.getText("Registration") }));
    attachedTypeDB.addItem(new sap.ui.core.ListItem({ key: "2", text: oBundle.getText("Manual") }));
    attachedTypeDB.addItem(new sap.ui.core.ListItem({ key: "2", text: oBundle.getText("Warranty") }));
    attachedTypeDB.addItem(new sap.ui.core.ListItem({key:"3",text:oBundle.getText("Purchase_Order")}));
    attachedTypeDB.addItem(new sap.ui.core.ListItem({key:"4",text:oBundle.getText("Quotation")}));
    attachedTypeDB.addItem(new sap.ui.core.ListItem({key:"5",text:oBundle.getText("Miscellaneous")}));
    attachedTypeDB.setSelectedKey("1");
    attachedTypeDB.addEventDelegate({
         onAfterRendering: function(e) {
              attachedTypeDB.$().find("input").attr("readonly", true);
         }
        });

    var oLayoutForm = 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: true, text: oBundle.getText("Document_Type") }),
                        fields: [attachedTypeDB]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ text: oBundle.getText("Document_Description") }),
                        fields: [attachmentName]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ required: true, text: oBundle.getText("Select_File") }),
                        fields: [oFileUploaderVehicleAttachment]
                    }),
                ]
            })
            ]
        });

    var oDialog = new sap.m.Dialog({
        title: oBundle.getText("Upload_Vehicle_Document"),
        state: sap.ui.core.ValueState.Success,
        content: [oLayoutForm],
        buttons: [new sap.m.Button({
                      text: oBundle.getText("Upload"),
                      icon: "sap-icon://upload",
                      press: function () {

                            var attachName = attachmentName.getValue();
	                        var attachment_type = attachedTypeDB.getValue();
	                        var attachment_typeKey = attachedTypeDB.getSelectedKey();
	                        if (attachment_typeKey == "1") {
                                sap.m.MessageBox.error(oBundle.getText("Select_document_type"));
	                            return;
	                        }
                          if(oFileUploaderVehicleAttachment.getValue()!=""){
                              oDialogVehicleAttachment.open();
                              oFileUploaderVehicleAttachment.upload();
                          }else{
                              sap.m.MessageBox.error(oBundle.getText("Select_file_for_upload"));
                          }
                      }
                  }),
					new sap.m.Button({
					    text: oBundle.getText("Cancel"),
					    icon: "sap-icon://decline",
					    press: function () {
					        oDialog.close();
					    }
					})
				]
    }).open();
}
function attachmentRemove(mid,vehicle_id){

     sap.m.MessageBox.show(oBundle.getText("Do_you_want_to_delete"),
            sap.m.MessageBox.Icon.ERROR,
            oBundle.getText("Alert"),
            [sap.m.MessageBox.Action.YES, sap.m.MessageBox.Action.NO],
            function (bConfirmed) {
                if (bConfirmed == "YES") {
                    busyDialog.open();
                    HVI_VehicleDoc.del({ id: mid }).done(function () {
                        busyDialog.close();
                        getAttachmentVehicle(vehicle_id);
                    }, failure);
                }
            });
}
function getAttachmentVehicle(vehicle_id){

     oTableVehicleAttachment.setBusy(true);
     HVI_VehicleDoc.where({ master_email: emailUser,vehicle_id:vehicle_id }).includeTotalCount().take(1000).orderByDescending("__createdAt").read().done(function (results) {
         //alert( JSON.stringify(results));

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

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

        if(vehicleViewTab!=null && vehicleViewTab != "undefined"){
            var tabItems = vehicleViewTab.getItems();
            tabItems[6].setCount(results.length);
        }

     });
}*/

// function getAssignedForm(vehicle_number,assignList){

//     assignList.setBusy(true);
//     HVI_Assign_Form.where({ master_email: emailUser,vehicle_number : vehicle_number}).take(100).orderByDescending("createdAt").read().done(function (results) {

//        /* for (var i = 0; i < results.length; i++) {
//             var form_id = results[i]['form_id'];
//             assignFormArray.push(form_id);
//         }*/

//         var oModel = new sap.ui.model.json.JSONModel();
//         oModel.setData({ modelData: results });
//         assignList.setModel(oModel);

//         var oItemItem = new sap.m.StandardListItem({
//             title: "{form_name}",
//             customData: new sap.ui.core.CustomData({key:"{form_id}"})
//         });
//         assignList.bindAggregation("items", "/modelData", oItemItem);
//         assignList.setBusy(false);

//         var tabItems = vehicleViewTab.getItems();
//         tabItems[7].setCount(results.length);
//     });

// }