// var Car_Schedule = client.getTable("Car_Schedule");


var oTableSchedule = new sap.m.Table({
        growing: true,
        noDataText:oBundle.getText("No_Data"),
        growingTriggerText:oBundle.getText("More"),
        sticky:[sap.m.Sticky.ColumnHeaders,sap.m.Sticky.HeaderToolbar,sap.m.Sticky.InfoToolbar],
        growingThreshold: 25,
        growingScrollToLoad : false,
        columns: [
            new sap.m.Column({width:"100px",header: new sap.m.Label({text: oBundle.getText("Action"),design: sap.m.LabelDesign.Bold})}),
            new sap.m.Column({width:"25%",header: new sap.m.Label({wrapping:true,text: oBundle.getText("Schedule"),design: sap.m.LabelDesign.Bold})}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("License_Number"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
            
            new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Due"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),

            // new sap.m.Column({width:"20%",header: new sap.m.Label({text: oBundle.getText("Workorder"),design: sap.m.LabelDesign.Bold}),
            // minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
            
        ],
        headerToolbar:new sap.m.OverflowToolbar({
            content: [   
                    new sap.m.Button({
                        id:"createScheduleID",
                        text:oBundle.getText("Create_Schedule"),
                        type:sap.m.ButtonType.Emphasized,
                        icon: "sap-icon://create-entry-time",
                        press: function (e) {
                            if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('create_schedule') != -1)){
                                addUpdateSchedule(1);//Create
                            }else{
                                sap.m.MessageToast.show("Create Access not provided.");
                            }
                               
                        }
                    }),
                    new sap.m.ToolbarSpacer(),
                    new sap.m.SearchField({
                        placeholder: oBundle.getText("Search"),
                        width: "300px",
                        liveChange: function (event) {

                            var oBinding = oTableSchedule.getBinding("items");
                            var searchStr = this.getValue();
                            if (oBinding) {
                                var oFilters = [new sap.ui.model.Filter("schedule_id", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("schedule_title", 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("task_list", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("workorder_number", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("location_id", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("location_name", sap.ui.model.FilterOperator.Contains, searchStr),
                                ];
                                var filterObj = new sap.ui.model.Filter(oFilters, false);
                                oBinding.filter(filterObj);
                            } else {
                                oBinding.filter([]);
                            }
                        }
                    }),
                    new sap.m.Button({icon: "sap-icon://sort",press: function () {
                            VSDSchedule.open();
                    }})
            ]})
    });

function milesFormatter(repeat_type,vehicle_number,last_reading,interval_reading,interval_type,vMeterUnit){
    
     if (interval_type == "1" || interval_type == "3") {
            var current_reading = 0;
            var getVehicle = vehicle4WJSONData.filter(function(obj, index){
                    return (obj.license_number === vehicle_number);
                });
                if(getVehicle.length>0){
                    current_reading = parseFloat(getVehicle[0]['odometer']);
                }
                                            
            
            var intervalReading = parseFloat(interval_reading);

            //var dueAt = lastReading + intervalReading;

            var dueAt = 0;
            if (repeat_type=="1") {
                var lastReading = parseFloat(last_reading);
                dueAt = lastReading + intervalReading;
            }else{
                dueAt =  intervalReading;
            }

            var dueAgo = dueAt - current_reading;

            return oBundle.getText("at") + " " +Math.round(dueAt)+" "+vMeterUnit;
        }else{
            return "";
        }
}

function milesAgoFormatter(repeat_type,vehicle_number,last_reading,interval_reading,interval_type,vMeterUnit,notify_reading){
    
     if (interval_type == "1" || interval_type == "3") {
            var current_reading = 0;
            var getVehicle = vehicle4WJSONData.filter(function(obj, index){
                    return (obj.license_number === vehicle_number);
                });
            if(getVehicle.length>0){
                current_reading = parseFloat(getVehicle[0]['odometer']);
            }
                                            
            var intervalReading = parseFloat(interval_reading);

           // var dueAt = lastReading + intervalReading;
            
            var dueAt = 0;
            if (repeat_type=="1") {
                var lastReading = parseFloat(last_reading);
                dueAt = lastReading + intervalReading;
            }else{
                dueAt =  intervalReading;
            }
            var dueAgo = dueAt - current_reading;
            //return "at" +" "+Math.round(dueAt)+" "+vMeterUnit;
           
            var notifyReading = parseInt(notify_reading);

            if (dueAt <= current_reading) {
                dueAgo = dueAgo * -1;
                this.setState("Error");
                return Math.round(dueAgo) +" "+vMeterUnit+" "+ oBundle.getText("ago");
                // overdueFlag = overdueFlag + 1;
            } else if ((dueAt-notifyReading) <= current_reading) {
                this.setState("Warning");
                return Math.round(dueAgo) +" "+vMeterUnit+" "+ oBundle.getText("to_go");
                //overdueSoonFlag = overdueSoonFlag + 1;
            } else {
                this.setState("None");
                return Math.round(dueAgo) +" "+vMeterUnit+" "+ oBundle.getText("to_go");
            }
            
        }else{
            return "";
        }
}

function durationFormatter(repeat_type,interval_type,last_date,interval_duration,duration_unit,on_date){
    
     if (interval_type == "2" || interval_type == "3") {
         var nextDate;
         if (repeat_type=="1") {
            var intervalDuration = parseInt(interval_duration);
           
            if (duration_unit == "1") {
                nextDate = nextDateValue(last_date,intervalDuration*1);
            } else if (duration_unit == "2") {
                nextDate = nextDateValue(last_date,intervalDuration*7);
            } else if (duration_unit == "3") {
                nextDate = nextDateValue(last_date,intervalDuration*30);
            } else if (duration_unit == "4") {
                nextDate = nextDateValue(last_date,intervalDuration*365);
            } 
         } else {
               nextDate = on_date;  
         }
          return oBundle.getText("on") + " " + nextDate;
        }else{
            return "";
        }
}
 
function durationAgoFormatter(repeat_type,interval_type,last_date,interval_duration,duration_unit,on_date,notify_duration,notify_unit){
    
     if (interval_type == "2" || interval_type == "3") {

         var currentDate = Date.parse(getCurrentDate());
         var nextDate;
         if (repeat_type=="1") {
             
            var lastServiceDate = new Date(last_date);
            var intervalDuration = parseInt(interval_duration);
           
            if (duration_unit == "1") {
                nextDate = new Date(nextDateValue(last_date,intervalDuration*1));
            } else if (duration_unit == "2") {
                nextDate = new Date(nextDateValue(last_date,intervalDuration*7));
            } else if (duration_unit == "3") {
                nextDate = new Date(nextDateValue(last_date,intervalDuration*30));
            } else if (duration_unit == "4") {
                nextDate = new Date(nextDateValue(last_date,intervalDuration*365));
            } 

         } else {
               nextDate = new Date(on_date);
         }
         
            var notifyDuration = parseInt(notify_duration);
            if (notify_unit=="2") {
                notifyDuration = notifyDuration * 7;
            } else if (notify_unit=="3") {
                notifyDuration = notifyDuration * 30;
            }

            var msDiff = nextDate.getTime() - new Date().getTime(); 
            var daysDiff = msDiff / (1000 * 3600 * 24)+1; 

            //console.log("avd2"+daysDiff);

            daysDiff = Math.round(daysDiff);

            //console.log(""+daysDiff);

            if (daysDiff <= 0) {
                daysDiff = daysDiff * -1;
                this.setState("Error");
                return (daysDiff) +" "+ oBundle.getText("days_ago");
                //overdueFlag = overdueFlag + 1;
            }else if (daysDiff - notifyDuration <= 0) {
                this.setState("Warning");
                return (daysDiff) +" "+ oBundle.getText("days_to_go");
                //overdueSoonFlag = overdueSoonFlag + 1;
            } else {
                this.setState("None");
                return (daysDiff) +" "+ oBundle.getText("days_to_go");
            }

        }else{
            return "";
        }
}
 
function scheduleStatusFormatter(interval_type,repeat_type,vehicle_number,last_reading,last_date,
            interval_reading,interval_duration,duration_unit,on_date,notify_reading,notify_duration,notify_unit,status){
    
    var overdueFlag = 0;
    var overdueSoonFlag = 0;

    if (interval_type == "1" || interval_type == "3") {
            var current_reading = 0;
            var getVehicle = vehicle4WJSONData.filter(function(obj, index){
                    return (obj.license_number === vehicle_number);
                });
            if(getVehicle.length>0){
                current_reading = parseFloat(getVehicle[0]['odometer']);
            }
                                            
            var lastReading = parseFloat(last_reading);
            var intervalReading = parseFloat(interval_reading);

            var dueAt = 0;
            if (repeat_type=="1") {
                var lastReading = parseFloat(last_reading);
                dueAt = lastReading + intervalReading;
            }else{
                dueAt =  intervalReading;
            }
            var dueAgo = dueAt - current_reading;
           
            var notifyReading = parseInt(notify_reading);

            if (dueAt <= current_reading) {
                 overdueFlag = overdueFlag + 1;
            } else if ((dueAt-notifyReading) <= current_reading) {
                overdueSoonFlag = overdueSoonFlag + 1;
            } 
        }

    if (interval_type == "2" || interval_type == "3") {

             var currentDate = Date.parse(getCurrentDate());
             var nextDate;
             if (repeat_type=="1") {
             
                var lastServiceDate = new Date(last_date);
                var intervalDuration = parseInt(interval_duration);

                if (duration_unit == "1") {
                    nextDate = new Date(nextDateValue(last_date,intervalDuration*1));
                } else if (duration_unit == "2") {
                    nextDate = new Date(nextDateValue(last_date,intervalDuration*7));
                } else if (duration_unit == "3") {
                    nextDate = new Date(nextDateValue(last_date,intervalDuration*30));
                } else if (duration_unit == "4") {
                    nextDate = new Date(nextDateValue(last_date,intervalDuration*365));
                } 
             } else {
                   nextDate = new Date(on_date);
             }
         
            var notifyDuration = parseInt(notify_duration);
            if (notify_unit=="2") {
                notifyDuration = notifyDuration * 7;
            } else if (notify_unit=="3") {
                notifyDuration = notifyDuration * 30;
            }

            var msDiff = nextDate.getTime() - new Date().getTime(); 
            var daysDiff = msDiff / (1000 * 3600 * 24)+1; 
            daysDiff = Math.round(daysDiff);

            if (daysDiff <= 0) {
                overdueFlag = overdueFlag + 1;
            } else if (daysDiff - notifyDuration <= 0) {
                overdueSoonFlag = overdueSoonFlag + 1;
            } 
        }
        if (status == "1") {
            if (overdueFlag > 0) {
                this.setColorScheme(3);
                return oBundle.getText("Overdue");
            } else if (overdueSoonFlag > 0) {
                this.setColorScheme(1);
                return oBundle.getText("Duesoon");
            } else {
                this.setVisible(false);
            }
        }else{
            this.setColorScheme(5);
            return oBundle.getText("Inactive");
        }
}
 
 var scheduleTemplate = new sap.m.ColumnListItem({
          cells: [
                new sap.m.Button({
                    type: "Emphasized",
                    icon: "sap-icon://action",
                    text: oBundle.getText("Action"),
                    press: function (event) {
                        var model = this.getModel();
                        var path = event.getSource().getBindingContext().getPath();
                        var obj = model.getProperty(path);
                        scheduleID = obj['id'];
                     
                        displayMenuSchedule(event,obj);
                    }
                }),
                new sap.m.VBox({
                    items:[
                    new sap.m.HBox({
                            items:[new sap.m.Label({ text: "{schedule_id}"}),new sap.m.Label({ text: "-"}),
                            new sap.m.Label({ text: "{cycle_count}"}), 
                            new sap.tnt.InfoLabel({
                                text: { parts: [{ path: "interval_type", type: new sap.ui.model.type.String()},
                                                { path: "repeat_type", type: new sap.ui.model.type.String()},
                                                { path: "license_number", type: new sap.ui.model.type.String()},
                                                { path: "last_service_reading", type: new sap.ui.model.type.String()},
                                                { path: "last_service_date", type: new sap.ui.model.type.String()},

                                                { path: "interval_reading", type: new sap.ui.model.type.String()},
                                                { path: "interval_duration", type: new sap.ui.model.type.String()},
                                                { path: "duration_unit", type: new sap.ui.model.type.String()},
                                                { path: "on_date", type: new sap.ui.model.type.String()},

                                                { path: "notify_reading", type: new sap.ui.model.type.String()},
                                                { path: "notify_duration", type: new sap.ui.model.type.String()},
                                                { path: "notify_duration_unit", type: new sap.ui.model.type.String()},
                                                { path: "status", type: new sap.ui.model.type.String()}],
                                        formatter: scheduleStatusFormatter
                                    }
                            }).addStyleClass("sapUiTinyMarginBegin")
				        ]}),
                    // new sap.m.Label({text: "{schedule_title}"}).addStyleClass("sapUiTinyMarginTop"),
				]}).addStyleClass("sapUiTinyMargin"),
                 new sap.m.VBox({
                    items:[new sap.m.Label({ wrapping: true, text: "{license_number}" }),
                        //    new sap.m.Label({ wrapping: true, text: "{vehicle_model}" }).addStyleClass("sapUiTinyMarginTop"),
                    ]}).addStyleClass("sapUiTinyMargin"),
                new sap.m.VBox({
                    items:[
                     new sap.m.HBox({
                        items:[
                        new sap.ui.core.Icon({
                             src: { path: "interval_type",
                                    formatter: function (interval_type) {
                                        if (interval_type == "1" || interval_type == "3") {
                                                return "sap-icon://performance";
                                        }else{
                                            this.setVisible(false);
                                        }
                         }}}),
                        new sap.m.Label({ 
                            text: { parts: [{ path: "repeat_type", type: new sap.ui.model.type.String()},
                                            { path: "license_number", type: new sap.ui.model.type.String()},
                                            { path: "last_service_reading", type: new sap.ui.model.type.String()},
                                            { path: "interval_reading", type: new sap.ui.model.type.String()},
                                            { path: "interval_type", type: new sap.ui.model.type.String()},
                                            { path: "vehicle_meter_unit", type: new sap.ui.model.type.String()}],
                                    formatter: milesFormatter
                                }
                        }).addStyleClass("sapUiTinyMarginBeginEnd"),

                        new sap.m.ObjectStatus({
                            text: { parts: [{ path: "repeat_type", type: new sap.ui.model.type.String()},
                                            { path: "license_number", type: new sap.ui.model.type.String()},
                                            { path: "last_service_reading", type: new sap.ui.model.type.String()},
                                            { path: "interval_reading", type: new sap.ui.model.type.String()},
                                            { path: "interval_type", type: new sap.ui.model.type.String()},
                                            { path: "vehicle_meter_unit", type: new sap.ui.model.type.String()},
                                            { path: "notify_reading", type: new sap.ui.model.type.String()}],
                                    formatter: milesAgoFormatter
                                }
                        }).addStyleClass("sapUiMediumMarginBegin"),

				    ]}).addStyleClass("sapUiTinyMarginTop"),
                     new sap.m.HBox({
                        items:[
                        new sap.ui.core.Icon({
                             src: { path: "interval_type",
                                formatter: function (interval_type) {
                                     if (interval_type == "2" || interval_type == "3") {
                                            return "sap-icon://calendar";
                                    }else{
                                        this.setVisible(false);
                                    }
                         }}}),
                        new sap.m.Label({ 
                            text: { parts: [{ path: "repeat_type", type: new sap.ui.model.type.String()},
                                            { path: "interval_type", type: new sap.ui.model.type.String()},
                                            { path: "last_service_date", type: new sap.ui.model.type.String()},
                                            { path: "interval_duration", type: new sap.ui.model.type.String()},
                                            { path: "duration_unit", type: new sap.ui.model.type.String()},
                                            { path: "on_date", type: new sap.ui.model.type.String()}],
                                    formatter: durationFormatter
                                }
                        }).addStyleClass("sapUiTinyMarginBeginEnd"),

                        new sap.m.ObjectStatus({
                            text: { parts: [{ path: "repeat_type", type: new sap.ui.model.type.String()},
                                            { path: "interval_type", type: new sap.ui.model.type.String()},
                                            { path: "last_service_date", type: new sap.ui.model.type.String()},
                                            { path: "interval_duration", type: new sap.ui.model.type.String()},
                                            { path: "duration_unit", type: new sap.ui.model.type.String()},
                                            { path: "on_date", type: new sap.ui.model.type.String()},
                                            { path: "notify_duration", type: new sap.ui.model.type.String()},
                                            { path: "notify_duration_unit", type: new sap.ui.model.type.String()}],
                                    formatter: durationAgoFormatter
                                }
                        }).addStyleClass("sapUiMediumMarginBegin")
				    ]}).addStyleClass("sapUiTinyMarginTop")
				]}),
            //     new sap.m.HBox({
            //          items:[
            //              new sap.m.Link({emphasized: true,
            //              text: {path: "workorder_number",
            //                 formatter: function (wo_number) {
            //                      if (wo_number != null && wo_number != "") {
            //                        this.setVisible(true);
            //                        return wo_number;
            //                     } else {
            //                        this.setVisible(false);
            //                     }
            //             }},
            //             press: function (event) {
            //                 var wo_number = this.getText();
            //                 getAttachedWorkorder(wo_number);
            //                 // 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"));
            //                 // } 
            //             }
            //         }),
            //         new sap.m.Button({
            //                 icon: "sap-icon://wrench",
            //                 text: {
            //                     path: "workorder_number",
            //                     formatter: function (wo_number) {
                                   
            //                          if (wo_number == null || wo_number == "") {
            //                             if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('create_work_order') != -1)){
            //                                 this.setVisible(true);
            //                                 return oBundle.getText("Create_Workorder");
            //                             }else{
            //                                 this.setVisible(false);
            //                             }
            //                         } else {
            //                             this.setVisible(false);
            //                         }
            //                     }
            //                 },
            //                 press: function (event) {
            //                     var model = this.getModel();
            //                     var path = event.getSource().getBindingContext().getPath();
            //                     var obj = model.getProperty(path);
                               
            //                     sideNavigation.setSelectedKey("grab_workorder");
            //                     navContainer.to("grab_workorder");
            //                     // oLayoutVehicle.to("vehicle_page");

            //                     addPageSrc = "1";
            //                     oAppWorkOrder.addPage(addWOPage);
            //                     oAppWorkOrder.to("add_wo_page");
            //                     addWOPage.setTitle(oBundle.getText("Maintenance_Workorder"));
            //                     iniWorkOrder("Schedule", obj);
            //                     btnWO1.setText(oBundle.getText("Create_WorkOrder"));

            //                 }
            //         }),
                    
			// ]}).addStyleClass("sapUiTinyMargin")
                
      ]});

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

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

                  oTableSchedule.getColumns()[1].setSortIndicator(sap.ui.core.SortOrder.None);
                  oTableSchedule.getColumns()[2].setSortIndicator(sap.ui.core.SortOrder.None);

                  if (key == "1") {
                      oTableSchedule.getColumns()[1].setSortIndicator(sortType);
                  } else if (key == "2") {
                      oTableSchedule.getColumns()[2].setSortIndicator(sortType);
                  }
                  if (oSorter) {
                      oSorter.bDescending = p.sortDescending;
                      oTableSchedule.getBinding("items").sort(oSorter);
                  }
              }
          },
          sortItems:[
              new sap.m.ViewSettingsItem({
                  text: oBundle.getText("Created_Date" ),
                  selected: true,
                  customData: new sap.ui.core.CustomData({
                      key:"1",
                      value: new sap.ui.model.Sorter("created_date", false)
                  })
              }),
              new sap.m.ViewSettingsItem({
                  text: oBundle.getText("Schedule_ID" ),
                  customData: new sap.ui.core.CustomData({
                      key:"2",
                      value: new sap.ui.model.Sorter("schedule_id", false)
                  })
              }),
              new sap.m.ViewSettingsItem({
                  text: oBundle.getText("License_Number"),
                  customData: new sap.ui.core.CustomData({
                      key:"3",
                      value: new sap.ui.model.Sorter("vehicle_number", false)
                  })
              }),
          ]
      });
     
       
function displayMenuSchedule(event,obj){

    var oMenu = new sap.m.Menu({
        items: [
            // new sap.m.MenuItem({icon: "sap-icon://edit",text:oBundle.getText("Update"),key: "1"}),
            // new sap.m.MenuItem({icon: "sap-icon://complete",text:oBundle.getText("Mark_as_completed"),key: "2"}),
           // new sap.m.MenuItem({icon: "sap-icon://edit",text:oBundle.getText("Schedule_Overview"),key: "6"}),
           // new sap.m.MenuItem({icon: "sap-icon://duplicate",text:oBundle.getText("Duplicate_Schedule"),key: "7"}),
         ],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
             var mid = obj['id'];
            if (oItem == "1") {
                addUpdateSchedule(2,obj);
            } else if (oItem == "2") {

                var wo_number = obj['workorder_number'];
                if (wo_number != null && wo_number != "") {
                    
                    var result = workorderJSONArray.filter(function (obj, index) {
                        return (obj.wo_number == wo_number);
                    });
                    if(result.length>0){
                        sap.m.MessageBox.error(oBundle.getText("A_workorder_is_link_with_this_schedule_so_complete_workorder"));
                    }else{
                        markCompletedSchedule(obj);
                    } 
                }else{
                    markCompletedSchedule(obj);
                }

            } else if (oItem == "3") {
                deleteSchedule(mid);
            } else if (oItem == "4") {
                activeInactiveStatus(mid,1)
            } else if (oItem == "5") {
                activeInactiveStatus(mid,2)
            } else if (oItem == "6") {
                getScheduleHistory(obj)
            } 
            else if (oItem == "7") {
                sap.m.MessageBox.show(oBundle.getText("Do_you_want_to_Duplicate_Schedule"),
                sap.m.MessageBox.Icon.INFORMATION,
                oBundle.getText("Alert"),
                [sap.m.MessageBox.Action.YES, sap.m.MessageBox.Action.NO],
                function (bConfirmed) {
                    if (bConfirmed == "YES") {
                        // busyDialog.open();
                        // duplicateSchedule(obj);
                        addUpdateSchedule(3,obj);
                    }
                });
            }
        }
    });

    
  


    //Modify
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('modify_schedule') != -1)){
        oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://edit",text: oBundle.getText("Update"),key: "1"}));
        // oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://complete",text: oBundle.getText("Mark_as_completed"),key: "2"}));
    };

      
    // if(obj['status'] == "1"){
    //     oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://sap-box",text: oBundle.getText("Inactive"),key: "4"}));
    // }else if(obj['status'] == "0"){
    //         oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://sap-box",text: oBundle.getText("Active"),key: "5"}));
    // };

    //Delete
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('delete_schedule') != -1)){
        getDeleteMenu(oMenu,"3");
    };

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

function activeInactiveStatus(mid,type){
    
    var status;
    if(type==1){
        status = "0";
    }else{
        status = "1";
    }
    busyDialog.open();
    Car_Schedule.update({id:mid, status: status
	        }).done(function () {
	            busyDialog.close();
	            getScheduleDetails();
	   }, failure); 

}

function markCompletedSchedule(obj){
    
    var vehicle_number = obj['license_number'];
    var repeat_type = obj['repeat_type'];

    var getVehicle = vehicle4WJSONData.filter(function(obj, index){
        return (obj.license_number === vehicle_number);
    });
    
    var meterReading = getVehicle[0]['last_service_odometer'];
    var schedule_id = obj['schedule_id']+"-"+obj['cycle_count'];

    var comInput1 = new sap.m.Input({ type:"Number",value: "", width: "100%", description:"KM"});
    var comInput2 = new sap.m.DateTimePicker({width: "100%",
        displayFormat: "dd-MMM-yyyy hh:mm a",
        valueFormat: "dd-MMM-yyyy hh:mm a"
    });


    var oCheckBoxMeter = new sap.m.CheckBox({selected: true,
        text:oBundle.getText("Update_vehicle_meter_reading"),
    });

    var oForm1 = 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("Schedule#")}),
                        fields: [new sap.m.Label({text: schedule_id})]
                    }),
                   /* new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ text: oBundle.getText("")}),
                        fields: [oCheckBoxMeter]
                    }),*/
				    new sap.ui.layout.form.FormElement({
					    label: new sap.m.Label({ required: true, text: oBundle.getText("Vehicle_meter_reading")}),
					    fields: [comInput1]
                    }),
                   /* new sap.ui.layout.form.FormElement({
					    //label: new sap.m.Label({ text: oBundle.getText("Current_meter_reading")}),
					    fields: [new sap.m.Label({text: oBundle.getText("Current_meter_reading") +" : "+meterReading})]
				    }),*/
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({required: true, text: oBundle.getText("Completed_Date")}),
                        fields: [comInput2]
                    })
			    ]
			})
		]
    });

    var oButton = new sap.m.Button({
        text: oBundle.getText("Complete"),
        icon: "sap-icon://complete",
        press: function () {

            var value1 = comInput1.getValue();
            var value2 = comInput2.getValue();

            if (textFieldValidation(comInput1, value1)) { return; }
            if (textFieldValidation(comInput2, value2)) { return; }

          /*  if (oCheckBoxMeter.getSelected()) {
                if (parseFloat(value1) < parseFloat(meterReading)) {
                    sap.m.MessageBox.error(oBundle.getText("Meter_Reading_can_not_be_less_than_current_reading"));
                    return;
                }
            }*/

            if (!comInput2.isValidValue()) {
                sap.m.MessageBox.error(oBundle.getText("Invalid") + " " + oBundle.getText("Completed_Date"));
                return;
            }
            
            oButton.setEnabled(false);

          //  if (oCheckBoxMeter.getSelected()) {
               // updateCompletedVehicleReading(getVehicle, value1, value2, "5");
           // }
           // updateVehicleStatus(getVehicle,"5");

            Car_Schedule.update({ id: obj['id'], status: "2", completion_mile: value1, 
                completion_date: value2, completion_by: operatedID
            }).done(function () { });

            var newCycle = parseInt(obj['cycle_count']) + 1;
            var newScheduleID = new Date().getTime() + "";
            var splited = value2.split(" ");

            if (repeat_type == "1") {
                Car_Schedule.insert({ id: newScheduleID, master_email: emailUser, cycle_count: newCycle,
                    last_service_reading: value1, last_service_date: splited[0],
                    status: "1", due_soon_flag: "0", due_flag: "0", workorder_id: "", workorder_number: "",
                    schedule_id: obj['schedule_id'],
                    schedule_title: obj['schedule_title'],

                    created_date: obj['created_date'],
                    created_by: obj['created_by'],
                    vehicle_number: obj['license_number'],
                    vehicle_name: getVehicle[0]['vehicle_name'],
                    vehicle_meter_unit: obj['vehicle_meter_unit'],

                    task_list: obj['task_list'],
                    repeat_type: obj['repeat_type'],
                    interval_type: obj['interval_type'],

                    interval_reading: obj['interval_reading'],
                    interval_duration: obj['interval_duration'],
                    duration_unit: obj['duration_unit'],
                    on_date: obj['on_date'],
                    notify_reading: obj['notify_reading'],
                    notify_duration: obj['notify_duration'],
                    notify_duration_unit: obj['notify_duration_unit'],
                    location_id:hvi_location_id,
                    team_id: obj['team_id'],
                    team_name:obj['team_name'],
                    wo_flag:obj['wo_flag']
                }).done(function () { 

                    getScheduleDetails();

                });
            }

            oDialog.close();

        }
    });

      var oDialog = new sap.m.Dialog({draggable:true, resizable: true,contentWidth: "40%",
        title: oBundle.getText("Completion_Details"),
        content: [oForm1],
        buttons: [oButton,
				  new sap.m.Button({
					text: oBundle.getText("Cancel"),
					icon: "sap-icon://decline",
					press: function () {
					    oDialog.close();
					}
				})]
    }).open();

}

function deleteSchedule(mid) {

    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();
		        Car_Schedule.del({ id: mid }).done(function () {
		            sap.m.MessageBox.success(oBundle.getText("Record_Deleted"));
		            getScheduleDetails();
                    busyDialog.close();
		        }, failure);
		    }
		});

}

var scheduleArray;
var scheduleJSONArray = [];

function getScheduleDetails() {

    oTableSchedule.setBusy(true);

    Car_Schedule.where(filterQueryGrabSchedule).take(2000).orderByDescending("createdAt").read().done(function (result) {
        var results = filterGrabVehicle(result);
        setScheduleData(results);
    });

}


function setScheduleData(results){

    // getCompletedSchedule();

    scheduleArray = results;
    scheduleJSONArray = results;

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

    // list5.setInfo(results.length);
    oTableSchedule.setBusy(false);


    var upcomingArray = [];
    var upcomingOverArray = [];
    var upcomingSoonArray = [];

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

    var interval_type = results[i]['interval_type'];
    var repeat_type = results[i]['repeat_type'];
    var vehicle_number = results[i]['license_number'];
    var last_reading = results[i]['last_service_reading'];
    var last_date = results[i]['last_service_date'];

    var interval_reading = results[i]['interval_reading'];
    var interval_duration = results[i]['interval_duration'];
    var duration_unit = results[i]['duration_unit'];
    var on_date = results[i]['on_date'];
    var notify_reading = results[i]['notify_reading'];
    var notify_duration = results[i]['notify_duration'];
    var notify_unit = results[i]['notify_duration_unit'];
  
     var overdueFlag = 0;
     var overdueSoonFlag = 0;

     if (interval_type == "1" || interval_type == "3") {
            var current_reading = 0;
            var getVehicle = vehicle4WJSONData.filter(function(obj, index){
                    return (obj.license_number === vehicle_number);
                });
            if(getVehicle.length>0){
               current_reading = parseFloat(getVehicle[0]['odometer']);
            }
                                            
            var lastReading = parseFloat(last_reading);
            var intervalReading = parseFloat(interval_reading);

            var dueAt = lastReading + intervalReading;
            var dueAgo = dueAt - current_reading;
            var notifyReading = parseInt(notify_reading);

            if (dueAt <= current_reading) {
                 overdueFlag = overdueFlag + 1;
            } else if ((dueAt-notifyReading) <= current_reading) {
                overdueSoonFlag = overdueSoonFlag + 1;
            } 
        }


    if (interval_type == "2" || interval_type == "3") {

             var currentDate = Date.parse(getCurrentDate());
             var nextDate;
             if (repeat_type=="1") {
             
                var lastServiceDate = new Date(last_date);
                var intervalDuration = parseInt(interval_duration);

                if (duration_unit == "1") {
                    nextDate = new Date(nextDateValue(last_date,intervalDuration*1));
                } else if (duration_unit == "2") {
                    nextDate = new Date(nextDateValue(last_date,intervalDuration*7));
                } else if (duration_unit == "3") {
                    nextDate = new Date(nextDateValue(last_date,intervalDuration*30));
                } else if (duration_unit == "4") {
                    nextDate = new Date(nextDateValue(last_date,intervalDuration*365));
                } 

             } else {
                   nextDate = new Date(on_date);
             }
         
            var notifyDuration = parseInt(notify_duration);
            if (notify_unit=="2") {
                notifyDuration = notifyDuration * 7;
            } else if (notify_unit=="3") {
                notifyDuration = notifyDuration * 30;
            }

            var msDiff = nextDate.getTime() - new Date().getTime(); 
            var daysDiff = msDiff / (1000 * 3600 * 24); 
            daysDiff = Math.round(daysDiff);

            if (daysDiff <= 0) {
                overdueFlag = overdueFlag + 1;
            } else if (daysDiff - notifyDuration <= 0) {
                overdueSoonFlag = overdueSoonFlag + 1;
            } 
        }

    
        if (overdueFlag > 0) {
            results[i]["overDueSoonStatus"] = "Over Due";
            upcomingArray.push(results[i]);
            upcomingOverArray.push(results[i]);

        } else if (overdueSoonFlag > 0) {
            results[i]["overDueSoonStatus"] = "Due Soon";
            upcomingArray.push(results[i]);
            upcomingSoonArray.push(results[i]);
        }
}

    // contentWOtile36.setValue(upcomingSoonArray.length)
    // contentWOtile37.setValue(upcomingOverArray.length)
    // contentWOtile38.setValue(results.length)
    // duesoonChartArray = [{status:oBundle.getText('Overdue'),count:upcomingOverArray.length},{status:oBundle.getText('Duesoon'),count:upcomingSoonArray.length}]

    // var oModel5 = new sap.ui.model.json.JSONModel();
    // oModel5.setData({ modelData: duesoonChartArray });
    // oPieChartOverdueDueSoonWOD.setModel(oModel5);

    //Dashboard Upcomming
    upcomingArray.sort((a, b) =>
        a.overDueSoonStatus.localeCompare(b.overDueSoonStatus)
    );
    var oModelUpcoming = new sap.ui.model.json.JSONModel();
    oModelUpcoming.setData({ modelData: upcomingArray });
    oTableUpcommingDashSchedule.setModel(oModelUpcoming);
      
    oTableUpcommingDashSchedule.bindItems({
        path: "/modelData",
        template : upcommingScheduleDashTemplate
    });

    //OVER DUE
    var oModelUpcoming = new sap.ui.model.json.JSONModel();
    oModelUpcoming.setData({ modelData: upcomingOverArray });
    oTableUpcommingSchedule.setModel(oModelUpcoming);
      
    oTableUpcommingSchedule.bindItems({
        path: "/modelData",
        template : upcommingScheduleTemplate
    });

    //DUE SOON
    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ modelData: upcomingSoonArray });
    oTableDuesoonSchedule.setModel(oModel);
      
    oTableDuesoonSchedule.bindItems({
        path: "/modelData",
        template : oTableDuesoonScheduleTemplate
    });

}

//#####################################################Group Dialog Start#############################################################
var oDialogGroup;
function pickGroup(){

     oDialogGroup = new sap.m.Dialog({
        modal : true,
        title: oBundle.getText("Select_Inspection_Form"),
        state: sap.ui.core.ValueState.Success,
        content: [oTableScheduleGroup],
        buttons: [
					new sap.m.Button({
					    text: oBundle.getText("Cancel"),
					    icon: "sap-icon://decline",
					    press: function () {
					        oDialogGroup.close();
					    }
					})
				]
    }).open();

}

var oTableScheduleGroup = new sap.m.Table({
            growing: false,
            noDataText:oBundle.getText("No_Data"),
            growingTriggerText:oBundle.getText("More"),
            sticky:[sap.m.Sticky.ColumnHeaders,sap.m.Sticky.HeaderToolbar,sap.m.Sticky.InfoToolbar],
		    growingThreshold: 12,
		    growingScrollToLoad : false,
          columns: [
                new sap.m.Column({header: new sap.m.Label({text: oBundle.getText("Inspection_Form"),design: sap.m.LabelDesign.Bold})}),
                new sap.m.Column({ width: "100px", header: new sap.m.Label({ text: oBundle.getText("Action"), design: sap.m.LabelDesign.Bold})})
                
          ]
      }).addStyleClass('withGrid');

 var oTableScheduleGroupTemplate = new sap.m.ColumnListItem({
          cells: [
                new sap.m.Label({ wrapping: true, text: "{group_name}"}),
                new sap.m.Button({
                    type: "Emphasized",
                    icon: "sap-icon://complete",
                    text: oBundle.getText("Select"),
                    press: function (e) {
                        var model = this.getModel();
                        var path = e.getSource().getBindingContext().getPath();
                        var obj = model.getProperty(path);

                        var checklistName = obj['group_name'];
                        checklistID = obj['id'];

                        if(formSelectSource=="inspection"){
                            inspectionField4.setValue(checklistName);
                            funGetInspectionForm(obj['id']);
                        }else{
                            fieldSchedule6.setValue(checklistName);
                        }

                        oDialogGroup.close();
                    }
                }),
               ]

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

                  var sortType = sap.ui.core.SortOrder.Descending;
                  if (this.getSortDescending()) {
                      sortType = sap.ui.core.SortOrder.Descending;
                  } else {
                      sortType = sap.ui.core.SortOrder.Ascending;
                  }
                  oTableScheduleGroup.getColumns()[0].setSortIndicator(sap.ui.core.SortOrder.None);
                 
                  if (key == "1") {
                      oTableScheduleItem.getColumns()[0].setSortIndicator(sortType);
                  } 
                  if (oSorter) {
                      oSorter.bDescending = p.sortDescending;
                      oTableScheduleGroup.getBinding("items").sort(oSorter);
                  }
              }
          }
      });
      oTableScheduleGroup.getColumns()[0].setSortIndicator(sap.ui.core.SortOrder.Ascending);
      VSDoTableScheduleGroup.addSortItem(new sap.m.ViewSettingsItem({
          text: oBundle.getText("Inspection_Form" ),
          selected: true,
          customData: new sap.ui.core.CustomData({
               key:"1",
              value: new sap.ui.model.Sorter("group_name", false)
          })
      }));
    
 oTableScheduleGroup.setInfoToolbar(new sap.m.Toolbar({
          content: [
                new sap.m.ToolbarSpacer(),
                new sap.m.SearchField({
                    placeholder: oBundle.getText("Search"),
                    width: "300px",
                    liveChange: function (event) {

                        var oBinding = oTableScheduleGroup.getBinding("items");
                        var searchStr = this.getValue();
                        if (oBinding) {
                            var oFilters = [new sap.ui.model.Filter("group_name", sap.ui.model.FilterOperator.Contains, searchStr)
                            ];
                            var filterObj = new sap.ui.model.Filter(oFilters, false);
                            oBinding.filter(filterObj);
                        } else {
                            oBinding.filter([]);
                        }
                    }
                }),
                new sap.m.Button({
                    text:oBundle.getText("sorting"),
                    icon: "sap-icon://sort",
                    press: function () {
                        VSDoTableScheduleGroup.open();
                    }
                })
            ]
      }));
           
//#####################################################Group Dialog End#############################################################

 function nextDateValue(service_date,days) {

     var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    // var date1 = Date.parse(service_date);
     var newdate = new Date(service_date);
     newdate.setDate(newdate.getDate() + days);

     var d = newdate.getDate();
     var m = newdate.getMonth() + 1;
     var y = newdate.getFullYear();

     if (d < 10) {
         d = "0"+d;
     }

     return next_date_value = d + "-" + monthNames[newdate.getMonth()] + "-" + y;

 }
 
 function validation(value,fieldSchedule) {

    if (value.trim() == "") {
        sap.m.MessageBox.error(fieldSchedule + " "+oBundle.getText("is_empty"));
        return true;
    } else { return false; }
}

 function scheduleUpload(){

     
           var strCSV = "";

           var oDialogUpload = new sap.m.Dialog({
               title: 'Upload Vehicles',
               type: 'Message',
               icon: 'sap-icon://upload',
               endButton: new sap.m.Button({
                  text:oBundle.getText( 'Cancel'),
                   press: function () { oDialogUpload.close(); }
               }),
               beginButton: new sap.m.Button({
                  text:oBundle.getText( 'Upload_Data'),
                   press: function () {
                       //oDialogUpload.close(); 
                       if (strCSV != "") {

                           var lines = strCSV.split("\n");
                           var headers = lines[0].split(",");

                           var csvCount = lines.length;

                           //console.log(lines);
                           //console.log(csvCount);

                           if (lines.length < 200) {

                               for (var i = 1; i < lines.length - 1; i++) {
                                   var currentline = lines[i].split(",");

                                  var avd = "('"+
                                                'email'+"','"+
                                                currentline[0]+"','"+
                                                currentline[1]+"','"+
                                                currentline[2]+"','"+
                                                currentline[3]+"','"+
                                                currentline[4]+"','"+
                                                currentline[5]+"','"+
                                                currentline[6]+"','"+
                                                currentline[7]+"','"+
                                                currentline[8]+"','"+
                                                currentline[9]+"','"+
                                                currentline[10]+"','"+
                                                currentline[11]+"','"+
                                                'Initiate'+"','"+
                                                 '1'+"','"+
                                                 '24-Nov-2018 10:56 AM'+"'),"+

                                      

                                   //console.log(avd);
                                   oDialogUpload.close();
                               }
                           } else {

                               alertify.alert(oBundle.getText("You_can_add_50_reocrd_in_single_upload"));
                               oDialogUpload.close();
                           }

                       } else {
                           alertify.alert(oBundle.getText("No_CSV_file_selected"));

                       }
                   }
               })
           });

           var uploader = new sap.ui.unified.FileUploader({
               width: '100%',
               uploadUrl: 'upload/',
               change: function (oEvent) {
                   var file = oEvent.getParameter("files")[0];
                   if (file && window.FileReader) {
                       var reader = new FileReader();
                       reader.onload = function (evn) {
                           strCSV = evn.target.result; //string in CSV 
                           //csvJSON(strCSV);
                       };
                       reader.readAsText(file);
                   }
                   //oDialogUpload.close();
               }
           });


           oDialogUpload.addContent(uploader);
           oDialogUpload.open();
       
  }

  
var oTableScheduleCompleted = 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,
    mode: "Delete",
    growingScrollToLoad: false,
    "delete": function (oEvent) {
        var oContext = oEvent.getParameter("listItem").getBindingContext();
        var mid = oContext.getObject().id;
        deleteSchedule(mid);
    },
    columns: [
        new sap.m.Column({ width: "25%", header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Schedule"), design: sap.m.LabelDesign.Bold }) }),
        new sap.m.Column({ width: "15%", header: new sap.m.Label({ wrapping: true, text: oBundle.getText("License_Number"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Desktop", popinDisplay: "Inline", demandPopin: true
        }),
        new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("Completed"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Desktop", popinDisplay: "Inline", demandPopin: true
        }),
        new sap.m.Column({ width: "20%", header: new sap.m.Label({ text: oBundle.getText("Workorder"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Desktop", popinDisplay: "Inline", demandPopin: true
        })
    ],
    headerToolbar: new sap.m.OverflowToolbar({
        content: [
            new sap.m.ToolbarSpacer(),
            new sap.m.SearchField({
            placeholder: oBundle.getText("Search"),
            width: "300px",
            liveChange: function (event) {

                var oBinding = oTableScheduleCompleted.getBinding("items");
                var searchStr = this.getValue();
                if (oBinding) {
                    var oFilters = [new sap.ui.model.Filter("schedule_id", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("schedule_title", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("license_number", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("task_list", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("workorder_number", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("location_id", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("location_name", sap.ui.model.FilterOperator.Contains, searchStr),
                    ];
                    var filterObj = new sap.ui.model.Filter(oFilters, false);
                    oBinding.filter(filterObj);
                } else {
                    oBinding.filter([]);
                }
            }
        })
     ]})
});

 var scheduleCompletedTemplate = new sap.m.ColumnListItem({
          cells: [
                new sap.m.VBox({
                    items:[
                    new sap.m.HBox({
                            items:[new sap.m.Label({ text: "{schedule_id}"}),new sap.m.Label({ text: "-"}),
                            new sap.m.Label({ text: "{cycle_count}"}), 
				        ]}),
                    new sap.m.Label({text: "{schedule_title}"}).addStyleClass("sapUiTinyMarginTop"),
				]}).addStyleClass("sapUiTinyMargin"),
                new sap.m.Label({text: "{license_number}"}),
                new sap.m.VBox({
                    items:[
                     new sap.m.HBox({
                        items:[
                        new sap.ui.core.Icon({
                             src: { path: "interval_type",
                                    formatter: function (interval_type) {
                                        if (interval_type == "1" || interval_type == "3") {
                                                return "sap-icon://performance";
                                        }else{
                                            this.setVisible(false);
                                        }
                         }}}),
                        new sap.m.HBox({
                            items:[
                                new sap.m.Label({ text: oBundle.getText("At")}).addStyleClass("sapUiTinyMarginEnd"),
                                new sap.m.Label({ text: "{completion_mile}"}).addStyleClass("sapUiTinyMarginEnd"),
                                new sap.m.Label({ text: "{vehicle_meter_unit}"})
				        ]}).addStyleClass("sapUiTinyMarginBeginEnd"),

				    ]}).addStyleClass("sapUiTinyMarginTop"),
                     new sap.m.HBox({
                        items:[
                        new sap.ui.core.Icon({
                             src: { path: "interval_type",
                                formatter: function (interval_type) {
                                     if (interval_type == "2" || interval_type == "3") {
                                            return "sap-icon://calendar";
                                    }else{
                                        this.setVisible(false);
                                    }
                         }}}),
                        new sap.m.HBox({
                            items:[
                                new sap.m.Label({ text: oBundle.getText("On")}).addStyleClass("sapUiTinyMarginEnd"),
                                new sap.m.Label({ text: "{completion_date}"}),new sap.m.Label({ text: "by"}).addStyleClass("sapUiTinyMarginBeginEnd"),
                                new sap.m.Label({ text: "{completion_by}"})
				        ]}).addStyleClass("sapUiTinyMarginBeginEnd"),

                     
				    ]}).addStyleClass("sapUiTinyMarginTop")
				]}),
                new sap.m.HBox({
                     items:[
                         new sap.m.Link({emphasized: true,
                         text: {path: "workorder_number",
                            formatter: function (wo_number) {
                                 if (wo_number != null || wo_number != "") {
                                   return wo_number;
                                } else {
                                   this.setVisible(false);
                                }
                        }},
                        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){
                                workorderViewGrab(result[0],"1");
                            }else{
                                sap.m.MessageBox.error(oBundle.getText("Workorder_not_available_might_be_deleted"));
                            } 
                        }
                    })
			]}).addStyleClass("sapUiTinyMargin")    
      ]});



function getCompletedSchedule() {

     oTableScheduleCompleted.setBusy(true);

     Car_Schedule.where(filterQueryScheduleComplete1, emailUser).take(1000).orderByDescending("createdAt").read().done(function (result) {

        var results=funFilterJsonByVehicleNumber(result);
      
        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        oTableScheduleCompleted.setModel(oModel);
        oModel.setSizeLimit(results.length);
         oTableScheduleCompleted.bindItems({
            path: "/modelData",
            template : scheduleCompletedTemplate
        });

        oTableScheduleCompleted.setBusy(false);
        
    });


};


/*
function getScheduleHistory(obj){
    
    var oTableScheduleOverview = new sap.m.Table({
        growing: true, noDataText:oBundle.getText("No_Data"),
        growingTriggerText:oBundle.getText("More"),
        sticky:[sap.m.Sticky.ColumnHeaders,sap.m.Sticky.HeaderToolbar,sap.m.Sticky.InfoToolbar],
        growingThreshold: 25,
        growingScrollToLoad : false,
        columns: [
            // new sap.m.Column({width:"100px",header: new sap.m.Label({text: oBundle.getText("Action"),design: sap.m.LabelDesign.Bold})}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true,text: oBundle.getText("Schedule"),design: sap.m.LabelDesign.Bold})}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Vehicle_Details"), 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("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("Workorder"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Last_Service_Reading"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Completion_Mile"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Last_Service_Date"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Completion_Date"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
                
        ]
    });
    var oTableSchOverviewTemplate = new sap.m.ColumnListItem({
        cells: [
            // new sap.m.Label({ wrapping: true, text: "{schedule_id}"}),
            new sap.m.HBox({
                items:[new sap.m.Label({ text: "{schedule_id}"}),new sap.m.Label({ text: "-"}),
                new sap.m.Label({ text: "{cycle_count}"})
            ]}),
            new sap.m.VBox({
                items:[new sap.m.Label({wrapping:true, text: "{license_number}" }),
                new sap.m.Label({wrapping:true, text: "{vehicle_name}"}).addStyleClass("sapUiTinyMarginTop"),
            ]}),
        
            new sap.tnt.InfoLabel({colorScheme:6,
                text: { path: "status",
                formatter: function (status) {
                    if(status=="1"){
                        this.setColorScheme(3);
                        return oBundle.getText("Incomplete");
                    }else {
                        this.setColorScheme(8);
                        return oBundle.getText("Complete");
                    }
                }
            }}),
            new sap.m.Label({ wrapping: true, text: "{workorder_number}"}),
            new sap.m.Label({ wrapping: true, text: "{last_service_reading}"}),
            new sap.m.Label({ wrapping: true, text: "{completion_mile}"}),
            new sap.m.Label({ wrapping: true, text: "{last_service_date}"}),
            new sap.m.Label({ wrapping: true, text: "{completion_date}"}),
            
        ],
    });
    
    
    
    
    Car_Schedule.where({master_email:emailUser,schedule_id:obj['schedule_id']}).take(100).orderByDescending("createdAt").read().done(function (result) {

        var results=(result);
      
        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        oTableScheduleOverview.setModel(oModel);
        oModel.setSizeLimit(results.length);
        oTableScheduleOverview.bindItems({
            path: "/modelData",
            template : oTableSchOverviewTemplate
        });

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


function duplicateSchedule(obj){
    var current_date = getIndonesianTime();

    HVI_Index.where({ id: emailUser }).read().done(function (results) {

        var newSCHNo = Number(sessionStorage.getItem('sc_start_no')) + Number(results[0]['schedule']) + 1;
        var newSchNumber = sessionStorage.getItem('sc_prefix') + newSCHNo;


        HVI_Index.update({ id: emailUser, schedule: (Number(results[0]['schedule']) + 1) }).done(function () {

            Car_Schedule.insert({ master_email: emailUser, schedule_id: newSchNumber, cycle_count: "1", schedule_title: obj['schedule_title'],
	            status: "1", created_date: current_date, created_by: operatedBy, due_soon_flag: "0", due_flag: "0",
	            license_number: obj['license_number'], vehicle_name:obj['vehicle_name'],vehicle_meter_unit: obj['vehicle_meter_unit'], 
                last_service_reading: obj['last_service_reading'], last_service_date: obj['last_service_date'], task_list: obj['task_list'],
	            repeat_type: obj['repeat_type'], interval_type: obj['interval_type'],
	            interval_reading: obj['interval_reading'], interval_duration: obj['interval_duration'], duration_unit: obj['duration_unit'],
                on_date: obj['on_date'], notify_reading: obj['notify_reading'], notify_duration: obj['notify_duration'], 
                notify_duration_unit: obj['notify_duration_unit'], note:obj['note'],location_id:obj['location_id'],
                team_id:obj['team_id'],team_name:obj['team_name'],wo_flag:obj['woFlag']
	        }).done(function () {
                busyDialog.close();
	            getScheduleDetails();
            })

         });
    });

};*/

/*
var oLayoutScheduleMain = new sap.m.App({height:"100%",initialPage:"schedule_page"}); 

var schedulePage = new sap.m.Page("schedule_page", {
    title:oBundle.getText("Service_Schedule"),
    showHeader:true,
    enableScrolling:true,
    content : [oTableSchedule]
});

var scheduleCompletedPage = new sap.m.Page("schedule_completed_page", {
    title:oBundle.getText("Completed_Schedule"),
    showHeader:true,
    enableScrolling:true,
    showNavButton: true,
    navButtonPress: function(){ oLayoutScheduleMain.backToTop(); },
    content : [oTableScheduleCompleted]
}); 


oLayoutScheduleMain.addPage(schedulePage).addPage(scheduleCompletedPage);
*/

var oTableUpcommingSchedule = oTableSchedule.clone();
var upcommingScheduleTemplate = scheduleTemplate.clone();
oTableUpcommingSchedule.destroyHeaderToolbar();

oTableUpcommingSchedule.setHeaderToolbar(new sap.m.OverflowToolbar({
    content: [   
            new sap.m.ToolbarSpacer(),
            new sap.m.SearchField({
                placeholder: oBundle.getText("Search"),
                width: "300px",
                liveChange: function (event) {

                    var oBinding = oTableUpcommingSchedule.getBinding("items");
                    var searchStr = this.getValue();
                    if (oBinding) {
                      var oFilters = [new sap.ui.model.Filter("schedule_id", sap.ui.model.FilterOperator.Contains, searchStr),
                      new sap.ui.model.Filter("schedule_title", 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("task_list", sap.ui.model.FilterOperator.Contains, searchStr),
                      new sap.ui.model.Filter("workorder_number", sap.ui.model.FilterOperator.Contains, searchStr),
                      new sap.ui.model.Filter("location_id", sap.ui.model.FilterOperator.Contains, searchStr),
                      new sap.ui.model.Filter("location_name", sap.ui.model.FilterOperator.Contains, searchStr),
                      ];
                        var filterObj = new sap.ui.model.Filter(oFilters, false);
                        oBinding.filter(filterObj);
                    } else {
                        oBinding.filter([]);
                    }
                }
            }),
            new sap.m.MenuButton({
                icon: "sap-icon://menu",
                menu: new sap.m.Menu({
                    itemSelected: function(oEvent) {
                        var key = oEvent.getParameter("item").getKey();
                        if(key == "1"){
                            if(subscription_status != 'Inactive' && subscription_status != 'Cancelled'){
                                scheduleExcelExport("OverDueScheduleExport",oTableUpcommingSchedule);
                            }else{
                                sap.m.MessageBox.error(oBundle.getText("Your_subscription_is_inactive_please_buy_subscription"));
                                return;
                            }
                        }
                    },
                    items: [
                        new sap.m.MenuItem({
                            text: oBundle.getText("Excel_Export"),
                            icon: "sap-icon://excel-attachment",
                            key: "1"
                        }),
                    ]
                })
            })

  ]})
);

//Due Soon
var oTableDuesoonSchedule = oTableSchedule.clone();
var oTableDuesoonScheduleTemplate = scheduleTemplate.clone();
oTableDuesoonSchedule.destroyHeaderToolbar();

oTableDuesoonSchedule.setHeaderToolbar(new sap.m.OverflowToolbar({
    content: [   
            
            new sap.m.ToolbarSpacer(),
            new sap.m.SearchField({
                placeholder: oBundle.getText("Search"),
                width: "300px",
                liveChange: function (event) {

                    var oBinding = oTableDuesoonSchedule.getBinding("items");
                    var searchStr = this.getValue();
                    if (oBinding) {
                        var oFilters = [new sap.ui.model.Filter("schedule_id", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("schedule_title", 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("task_list", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("workorder_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("location_id", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("location_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        ];
                        var filterObj = new sap.ui.model.Filter(oFilters, false);
                        oBinding.filter(filterObj);
                    } else {
                        oBinding.filter([]);
                    }
                }
            }),
            // new sap.m.Button({icon: "sap-icon://sort",press: function () {
            //     VSDupDuesoonSchedule.open();
            // }}),
            new sap.m.MenuButton({
                icon: "sap-icon://menu",
                menu: new sap.m.Menu({
                    itemSelected: function(oEvent) {
                        var key = oEvent.getParameter("item").getKey();
                        if(key == "1"){
                            if(subscription_status != 'Inactive' && subscription_status != 'Cancelled'){
                                scheduleExcelExport("oTableDuesoonSchedule",oTableDuesoonSchedule);
                            }else{
                                sap.m.MessageBox.error(oBundle.getText("Your_subscription_is_inactive_please_buy_subscription"));
                                return;
                            }
                        }
                    },
                    items: [
                        new sap.m.MenuItem({
                            text: oBundle.getText("Excel_Export"),
                            icon: "sap-icon://excel-attachment",
                            key: "1"
                        }),
                    ]
                })
            })
  ]})
);


function scheduleExcelExport(tableName,table){
   
    var filename = "OverDueScheduleExport.xlsx";
    
    if(tableName == 'oTableUpcommingSchedule'){
        filename = "OverDueScheduleExport.xlsx";
    }else if(tableName == 'oTableDuesoonSchedule'){
        filename = "DueSoonScheduleExport.xlsx";
    }

    var xlsHeader = [
        oBundle.getText("Schedule_Number"), 
        oBundle.getText("Schedule_Title"), 
        oBundle.getText("Created_By"), 
        oBundle.getText("Created_Date"),
        oBundle.getText("Status"), 
        oBundle.getText("Repeat_Type"), 
        oBundle.getText("Interval_Reading"), 
        oBundle.getText("Interval_Duration"), 
        oBundle.getText("Duration_Unit"), 
        oBundle.getText("Notify_Reading"), 
        oBundle.getText("Notify_Duration"), 
        oBundle.getText("Notify_Duration_Unit"),
        oBundle.getText("Last_Meter_Reading"), 
        oBundle.getText("Due_Hours"), 
        oBundle.getText("Last_Service_Date"), 
        oBundle.getText("Due_Date"),
        oBundle.getText("license_Number"), 
        oBundle.getText("Vehicle_Model"),
        oBundle.getText("Workorder"),
        oBundle.getText("Tasks"), 
        oBundle.getText("Note")
                
    ];

    var dataObject = [];
    var tableItem = table.getItems();
    for(var i=0;i<tableItem.length;i++){
        var item = tableItem[i].getBindingContext().getObject();


        var dueHours = '';
        var dueDate = '';
        
        var hoursDue = (milesFormatter(item['repeat_type'],item['license_number'],item['last_service_reading'],item['interval_reading'],item['interval_type'],item['vehicle_meter_unit']))
        var dateDue  = (durationFormatter(item['repeat_type'],item['interval_type'],item['last_service_date'],item['interval_duration'],item['duration_unit'],item['on_date']))
        if(nullCheckAll(hoursDue)){
            dueHours = hoursDue.slice(3);
        }else if(nullCheckAll(dateDue)){
            dueDate = new Date(dateDue.slice(3));
        }

        var durationUnit = oBundle.getText('Day');
        if(item.duration_unit == '1'){
            durationUnit = oBundle.getText('Day');
        }else if(item.duration_unit == '2'){
            durationUnit = oBundle.getText('Week');
        }else if(item.duration_unit == '3'){
            durationUnit = oBundle.getText('Month');
        }else if(item.duration_unit == '4'){
            durationUnit = oBundle.getText('Year');
        }
        var notifyDurationUnit = oBundle.getText('Day');
        if(item.notify_duration_unit == '1'){
            notifyDurationUnit = oBundle.getText('Day');
        }else if(item.notify_duration_unit == '2'){
            notifyDurationUnit = oBundle.getText('Week');
        }else if(item.notify_duration_unit == '3'){
            notifyDurationUnit = oBundle.getText('Month');
        }
        dataObject.push({
            "1":item.schedule_id +"-"+ item.cycle_count,
            "2":item.schedule_title,
            "3":item.created_by,
            "4":item.created_date,
            "5":item.status == '1'?oBundle.getText("Open"):oBundle.getText("Close"),
            "6":item.repeat_type == '2'?oBundle.getText("One_time"):oBundle.getText("Repeat"),
            "7":item.interval_reading + " " + item.vehicle_meter_unit,
            "8":item.interval_duration,
            "9":durationUnit,
            "10":item.notify_reading + " " + item.vehicle_meter_unit,
            "11":item.notify_duration,
            "12":notifyDurationUnit,
            "13":item.last_service_reading,
            "14":dueHours.slice(0,-6),
            "15":item.last_service_date,
            "16":dueDate,
            "17":item.license_number,
            "18":item.vehicle_model,
            "19":item.workorder_number,
            "20":item.task_list,
            "21":item.note,
            
    });    
       
    }

    var createXLSLFormatObj = [];

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

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

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

var oLayoutScheduleMain = new sap.uxap.ObjectPageLayout({ headerContentPinnable: false, 
        preserveHeaderStateOnScroll: true, useIconTabBar: true, toggleHeaderOnTitleClick: true,
        headerTitle: new sap.uxap.ObjectPageDynamicHeaderTitle({
            heading: [new sap.m.Title({ text: oBundle.getText("Schedules"), level: "H1", titleStyle: "H2" })],
            /*actions:[new sap.m.Button({ text: oBundle.getText("Parts Category"), 
                        type:sap.m.ButtonType.Emphasized,icon: "sap-icon://group-2",
                        press: function(){
                            partsCategoryDialog(2);
                        } 
                    })
        ]*/
    }),
    sections: [
        new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("All_Schedule"),
            subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTableSchedule]})
        }),
        new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("Overdue"),
        subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTableUpcommingSchedule]})
        }),
        new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("Duesoon"),
            subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTableDuesoonSchedule]})
        }),
        // new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("Completed_Schedule"),
        //     subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTableScheduleCompleted] })
        // })
]});


