import { Component, OnInit } from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import { Params,Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { ContactService } from '../../../contact.service';
import { MyaccountComponent } from '../../../myaccount/myaccount.component';
import { environment } from '../../../../environments/environment';
import { SearchFilterPipe } from '../../../search-filter.pipe'

declare var google: any;
declare var html2canvas:any;
declare var pdfMake :any ; 
declare var jsPDF : any;
declare var $: any;
const PDF_EXTENSION = ".pdf"
import * as moment from 'moment';
import { WorkingHourDetailComponent } from '../working-hour-detail/working-hour-detail.component';
import { DialogDemoComponent } from '../../../dialog-demo/dialog-demo.component';
import { AcreportInfoComponent } from '../ac-report/acreport-info/acreport-info.component';
import { ReportService } from '../../report.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-working-hour-report',
  templateUrl: './working-hour-report.component.html',
  styleUrls: ['./working-hour-report.component.scss']
})
export class WorkingHourReportComponent implements OnInit {
  ignition_data: any =[];

  fs : any;
  ls : any;
  emailid : any;
  date1 = new Date();
totalWorkingHours=[]
  before:any;
  or : any;
  useridd :any;
  time :any;
  device_data:any;
  devicess:any;
  final:any;
  custtype:any;
  cust:boolean=false;
  Load : Boolean = false;
  date : any;
  devicesss:any;
  mb:any;
  logoutbut:boolean;
  dealer:boolean;
  text:any;
  option:any; 
  finall:any;
  Fromdate:any;
  todate:any;
  options=[];
  logo:any;
  dataForDigital1
  dataForDigital2
  superAdmin:Boolean = false;
  dev_url = environment.hostUrl;
  t:any;
  dataSelect:any;
  errorMsg: any;
  errorDialog: boolean=false;
  searchText:any;
  tabelObj:any; 
  tabelObj1:any; 
  tableFlag: boolean=true;
  identifier : String = "working_report";
  stoppage_data:any;
  arrival_time:any;
  departure_time:any;
  report_to_show =[];
  Durations:any;
  address_show:any;
  start_add_lat:any;
  start_add_long:any;
  uId:any;
  vName:any;
  deviceArr = [];
  data_descip: string;
  digital_input: any;
  private finalise = new Subject<void>();
  constructor(private contactService: ContactService,private router: Router,public dialog: MdDialog,private _service:ReportService) { 
    this._service.invokeEventForworkingHoursReport.pipe(
      takeUntil(this.finalise)
    ).subscribe(value => {
        if(value){
         this.getReport(value); 
       }
      });
  
  }
  ngOnDestroy(){
    this.finalise.next(void 0);
  }
  ngOnInit() {
 
    this.t = document.getElementById("download");
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.fs = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).fn;
    this.ls = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).ln;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.or = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._orgName;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.mb =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;

      if(this.custtype == true){
        this.cust = true;
      }  
      if(this.mb.charAt(0)=="n"){
        this.mb = ' '
      }

      if( window.localStorage['Custumer'] == 'ON'){
        this.logoutbut = false
        this.dealer = true
     }
     else{
         this.logoutbut = true
     }
          
     this.logo=window.localStorage['logo'];
     this.text=window.localStorage['text'];
     
     this.getUserDeatils()
     
  }

  getUserDeatils(){
    this.contactService.getUserObj(this.useridd).subscribe(res=>{
      this.digital_input=res.digital_input?res.digital_input:1;
      if(this.digital_input==1){
          this.testTable();
      }else{
          this.testTable2();
      }
  })
  }
// this.contactService.acReportMain(this.Fromdate,this.todate,this.useridd,this.vname).subscribe(res=>{1stAction: "OFF"
// 1stTime: 5002.068983333334
// 2stAction: "ON"
// 2stTime: 6529.886616666667
// VehicleName: "JCB"
// imei: "862007228064955"
  testTable2(){
   
  const that = this;
  console.log("inside digital 2");
  $(document).ready(function() {
     that.tabelObj1 = $('#deviceTable').DataTable({
          "processing": true,
          "searching": true, 
          pagingType: 'full_numbers', 
          pageLength: 25,
          serverSide: false,
          "scrollY":'65vh',  
          "scrollCollapse": true,     
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
          ajax: (dataTablesParameters,callback) => {
              var deviceID;
              that.Load = true;
              var from_date = that.Fromdate;
              var to_date = that.todate;
              var user = that.useridd;
              var temp = {
              from_date : from_date,
              to_date : to_date,
              user : user
              }
              // https://socket.oneqlik.in/notifs/ACSwitchReport
              var suburl = "";
              
              suburl += "/notifs/acReportForMobile?from_date=" + temp.from_date +'&to_date=' + temp.to_date + '&_u=' + temp.user;
              if(that.deviceArr.length != 0){  
                suburl +='&device='+that.deviceArr[0];
              }
              
              if((temp.from_date != undefined)&&(temp.to_date != undefined) && that.deviceArr.length!=0){
                that.contactService.get(suburl).subscribe((resp:any) => {   
                  var rowData=resp[0]?resp[0]:[]
                  console.log(rowData);  
                that.dataForDigital2=rowData[0]?rowData[0].ign:[]
                  // that.calculateACHours(resp[0]?resp[0].s:[])
                  // var wrReport = [];
                  // for(var r in resp){
                  //       // console.log('foreach',resp[r]);
                  //       var tempObj = {
                  //         'vehName' : r,
                  //         'ON-OFF_time': resp[r]['ON-OFF_time'],
                  //         'OFF-ON_time' :resp[r]['OFF-ON_time'],
                  //         'Imei' :resp[r]['deviceId']
                  //       }
                  //       wrReport.push(tempObj);
                  // }
                  // console.log('result',wrReport);
                  that.Load = false;
                   callback({data : rowData });
                  // callback({data : that.reportArray });
              }, err => {   
                that.Load= false;    
                console.log("error",err) ; 
                var tt = [];  
                callback({data : tt });  
              });
  
              }else{
                 this.Load = false;
               this.data_descip = "Select vehicle" ;  
                 var x = document.getElementById("toast")
                 x.className = "show";
                 setTimeout(function(){ x.className = x.className.replace("show", ""); }, 1500);
                let ta = [];
                that.Load = false;
                callback({data : ta });
              }
                      
        },  
        "rowCallback": function(row: Node, data: any | Object, index: number){  
          $('#getDetail', row).bind('click', () => {         
            console.log("Row Data",data);
                data['fromDate'] = that.Fromdate;
                data['toDate'] = that.todate


            // let dialogRef = that.dialog.open(WorkingHourDetailComponent, {    
            //   width: '548px',
            //   data: { device :data}
            // });
            let dialogRef = that.dialog.open(WorkingHourDetailComponent, {
                width: '800px',  
                data: {"deviceInfo":that.dataForDigital2,"digitalInput":that.digital_input}   

               });
          
            dialogRef.afterClosed().subscribe(result => {
              console.log(result);
              if(result == 'close'){
                    console.log(close);
              }
            })  
               
            });
          }, 
      
          "columns": [
              {
                  "data": "deviceName",
                  "visible": true,
                  "render": function(data, type, row) {
                      
                    return data?data : '';                  
                  }
              },
              {
                "data": "Device_ID",
                "visible": true,
                "render": function(data, type, row) {
                    
                  return data?data : '';                  
                }
            },
     
              {
                  "data": "workingHours",
                  "visible": true,
                  render: function(data, type, row) {
                    // var engine_on_time = parseFloat(data) + parseFloat(row['Idle Time']) ;          
                    return data ?data: 0.0; 
                  }
              },
              { 
                "data": "stopHours",
                "visible": true,
                render: function(data, type, row) {
                  return data ? data : 0.0; 
                }
            },
            {
              "data": "_id",
              "visible": true,
              render: function(data, type, row) {
                return '<i id="getDetail" title="Get Detail" style="cursor:pointer;font-size:24px" class="fas fa-info-circle"></i>';        
              }
          }
          ],  

      });
      

  });
}

timeconversion(total_min){
 
  var hours = parseInt(total_min) / 60
  var rhours = Math.floor(hours);
  var minutes = (hours - rhours) * 60;
  var rminutes = Math.round(minutes);

  var Durations = rhours + " " + 'hrs' + " " + rminutes + " " + 'min';
  return Durations ;
}

  

tab:any;
exportExcel()
{

    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    var table = $('#deviceTable').clone();
    table[0].querySelector("thead").remove();
    table[0].prepend($(".dataTable thead").clone()[0]);
    this.tab = table[0];//document.getElementById('deviceTable'); // id of table

    for(j = 0 ; j < this.tab.rows.length ; j++) 
    {     
        tab_text=tab_text+this.tab.rows[j].innerHTML+"</tr>";
      
    }

    tab_text=tab_text+"</table>";
   
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}
optionVal:any;

getAdd(latitude,longitude){
  var latti =0;
  var longi = 0
  if(latitude != undefined){
    latti = latitude;

  }
  if(longitude != undefined){
    longi = longitude

  }
    return 'https://maps.google.com/?q='+ latti + ',' + longi ; 
}

// callfunction(): void {
//   // this.Load = true;
//   this.tabelObj.draw();
// }

getReport(event){
  console.log("inside function");
  if(event == 'getExcel'){
    this.exportExcel();
   } else if(event=='getPdf')
  {
    this.expotToPdf();
  }else{
    this.totalWorkingHours=[]
    this.workingHoursArray=[]
     this.workingHoursArray1=[];
     this.reportArray=[]
    var deviceId: any;
    var tpdata = event ; 
    var that = this;
    var fd = tpdata.fromDate;
    var td  = tpdata.toDate;
    if(event.deviceArr.length==0){
      deviceId=[];
    }else{
      deviceId= event.deviceArr;
    }
    this.deviceArr = deviceId; 
    this.Fromdate = fd;
    this.todate = td;
    console.log(this.digital_input);
    
    if(this.digital_input==1){
      this.tabelObj.ajax.reload(); 
    }else{
    this.tabelObj1.ajax.reload(); 

    }
  }
 
}

// --------------------- New Method for working Hours---------------------------------

testTable() {
  this.reportArray=[]
    this.workingHoursArray1=[]
  this.workingHoursArray=[];
  this.totalWorkingHours=[]
  const that = this;
  console.log("inside function");
  $(document).ready(function() {
     that.tabelObj = $('#deviceTable').DataTable({
          "processing": true,
          "searching": true, 
          pagingType: 'full_numbers',
          pageLength: 25,
          serverSide: false,
          "scrollY":'65vh',  
          "scrollCollapse": true,     
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
          ajax: (dataTablesParameters,callback) => {
              var deviceID;
              that.Load = true;
              var from_date = that.Fromdate;
              var to_date = that.todate;
              var user = that.useridd;
              var temp = {
              from_date : from_date,
              to_date : to_date,
              user : user
              }
              
              if((temp.from_date != undefined)&&(temp.to_date != undefined)){
                var suburl = "";
                suburl += "/notifs/ignitionReportForMobile?from_date=" + (temp.from_date).toISOString() +'&to_date=' + (temp.to_date).toISOString() + '&_u=' + temp.user;
                if(that.deviceArr.length != 0){  
                  suburl +='&device='+that.deviceArr;
                }
                that.contactService.get(suburl).subscribe((resp:any) => {   
                  // console.log("Before",resp);  
                  resp.sort((a, b) => {
                     return new Date(a.timestamp).getTime() - new Date( b.timestamp).getTime();

                   });
                    // console.log("After",resp);  
                //  that.rowData=resp
                  // that.calculateWorkingHours(resp)
                  that.dataForDigital1=resp[0]?resp[0].ign:[]
                  var wrReport = [];
                  // for(var r in resp){
                  //       // console.log('foreach',resp[r]);
                  //       var tempObj = {
                  //         'vehName' : r,
                  //         'ON-OFF_time': resp[r]['ON-OFF_time'],
                  //         'OFF-ON_time' :resp[r]['OFF-ON_time'],
                  //         'Imei' :resp[r]['deviceId']
                  //       }
                  //       wrReport.push(tempObj);
                  // }
                  // // console.log('result',wrReport);
                  that.Load = false;
                  callback({data : resp });
              }, err => {   
                that.Load= false;    
                console.log("error",err) ; 
                var tt = [];  
                callback({data : tt });  
              });
  
              }else{
                let ta = [];
                that.Load = false;
                callback({data : ta });
              }
                      
        },  
        "rowCallback": function(row: Node, data: any | Object, index: number){  
          $('#getDetail', row).bind('click', () => {         
            console.log("Row Data",data);
                data['fromDate'] = that.Fromdate;
                data['toDate'] = that.todate


            let dialogRef = that.dialog.open(WorkingHourDetailComponent, {    
              width: '548px',
              data: {"deviceInfo":that.dataForDigital1,"digitalInput":that.digital_input}   
            });
          
            dialogRef.afterClosed().subscribe(result => {
              console.log(result);
              if(result == 'close'){
                    console.log(close);
              }
            })  
               
            });
          }, 
      
          "columns": [
          //   {
          //     "data": "deviceId",
          //     "visible": false,
          //     render: function(data, type, row) {
              
          //       return data ? data : "";  
            
          //     }
          // },
              {
                  "data": "deviceName",
                  "visible": true,
                  "render": function(data, type, row) {
                      
                    return data?data : '';                  
                  }
              },
              {
                "data": "Device_ID",
                "visible": true,
                "render": function(data, type, row) {
                    
                  return data?data : that.deviceArr[0];                  
                }
            },
     
              {
                  "data": "workingHours",
                  "visible": true,
                  render: function(data, type, row) {
                    // console.log(row);
                    // var engine_on_time = parseFloat(data) + parseFloat(row['Idle Time']) ;          
                    return data ? data : 0.0; 
                  }
              },
              { 
                "data": "stopHours",
                "visible": true,
                render: function(data, type, row) {
                  return data ? data : 0.0; 
                }
            },
            {
              "data": "_id",
              "visible": true,
              render: function(data, type, row) {
                return '<i id="getDetail" title="Get Detail" style="cursor:pointer;font-size:24px" class="fas fa-info-circle"></i>';        
              }
          }
        
          
     
          ],  

      });
      

  });


}
workingHoursArray=[]
async newMethod(data){
  console.log("hhhh",data);
  var tempArry=[]
  var stopHr=0;
  var workinHr=0
  var result = await data.reduce(function (r, a) {
        r[a.device.Device_ID] = r[a.device.Device_ID] || [];
        r[a.device.Device_ID].push(a);
        return r;
    }, Object.create(null));
  console.log(result);

  for(var i=0;i<this.deviceArr.length;i++){
    for(var j=0;j<result[this.deviceArr[i]].length;j++){
      console.log("1");
      
      // if(j!==result[this.deviceArr[i]].length){
         console.log("11",result[this.deviceArr[i]][j]);
      if(result[this.deviceArr[i]][j].switch=="OFF"){
         console.log("111",(result[this.deviceArr[i]][j].timestamp).replace('Z', '').replace('T', ''));
         if(result[this.deviceArr[i]][j+1]){
        if((new Date(result[this.deviceArr[i]][j].timestamp).getTime())>(new Date(result[this.deviceArr[i]][j+1].timestamp).getTime())){
          workinHr=(new Date(result[this.deviceArr[i]][j].timestamp).getTime()-new Date(result[this.deviceArr[i]][j+1].timestamp).getTime())/1000;
          stopHr=(new Date(this.todate).getTime()-new Date(this.Fromdate).getTime())/1000;
          
        }
      }
      }
    // }
    }
    tempArry.push({deviceName:result[this.deviceArr[i]][j-1].vehicleName,Device_ID:this.deviceArr[i],stopHours:this.secondsToHms(stopHr),workingHours:this.secondsToHms(workinHr)})
    stopHr=0;
    workinHr=0;
  }
  this.totalWorkingHours=tempArry
  console.log("TEMP==>",tempArry);
  

}
workingHoursArray1=[]
reportArray=[]
calculateACHours(data){
  var total=0
  console.log(data);
  for(let i=0;i<data.length;i++){
    if(i!==(data.length-1)){
    if(data[0].switch=="OFF"){
    if(data[i].switch=="OFF" && data[i+1].switch=="ON"){
      // console.log("DATE---------->",data[i].timestamp,"==",new Date((data[i].timestamp).replace('Z', '').replace('T', ':')));
      var date=new Date((data[i].timestamp).replace('Z', '').replace('T', ':'));
      var date1=new Date((data[i+1].timestamp).replace('Z', '').replace('T', ':'))
      this.workingHoursArray1.push({deviceName:data[i].vehicleName,timestamp:this.timeDifference(date,date1),Device_ID:this.deviceArr[0]})
      // this.workingHoursArray.push({deviceName:data[i].vehicleName,timestamp:this.timeDifference(new Date(data[i].timestamp),new Date(data[i+1].timestamp)),Device_ID:this.deviceArr[0]})
    }
  }
  else{
    if(data[i].switch=="ON" && data[i+1].switch=="OFF"){
      // console.log("DATE----------1>",data[i].timestamp,"==",new Date((data[i].timestamp).replace('Z', '').replace('T', ':')));
       var date=new Date((data[i].timestamp).replace('Z', '').replace('T', ':'));
      var date1=new Date((data[i+1].timestamp).replace('Z', '').replace('T', ':'))
      this.workingHoursArray1.push({deviceName:data[i].vehicleName,timestamp:this.timeDifference(date,date1),Device_ID:this.deviceArr[0]})
    }
  }
}else{
  for(var j=0;j<this.workingHoursArray1.length;j++){
    total=total+this.workingHoursArray1[j].timestamp;
  }
 var time= Math.abs(this.timeDifference(this.Fromdate,this.todate));
        var stopHrs=this.secondsToHms((time-total))
  this.reportArray.push({Device_ID:this.deviceArr[0],deviceName:data[0].vehicleName,workingHours:this.secondsToHms(total),stopHours:stopHrs});
  }

  }
  console.log("JEDHJDH",this.workingHoursArray1,this.reportArray);
  
  

}

calculateWorkingHours(data){
  // workingHoursArray
  var totalTimestamp=0
console.log(data);
for(let i=0;i<data.length;i++){
  if(i!==(data.length-1)){
  if(data[i].vehicleName==data[i+1].vehicleName){
    if(data[0].switch=="OFF"){
    if(data[i].switch=="OFF" && data[i+1].switch=="ON"){
      // console.log("DATE---------->",data[i].timestamp,"==",new Date((data[i].timestamp).replace('Z', '').replace('T', ':')));
      var date=new Date((data[i].timestamp).replace('Z', '').replace('T', ':'));
      var date1=new Date((data[i+1].timestamp).replace('Z', '').replace('T', ':'))
      this.workingHoursArray.push({deviceName:data[i].vehicleName,timestamp:this.timeDifference(date1,date),Device_ID:data[i].device.Device_ID})
      // this.workingHoursArray.push({deviceName:data[i].vehicleName,timestamp:this.timeDifference(new Date(data[i].timestamp),new Date(data[i+1].timestamp)),Device_ID:data[i].device.Device_ID})
    }
  }
  else{
    if(data[i].switch=="ON" && data[i+1].switch=="OFF"){
      // console.log("DATE----------1>",data[i].timestamp,"==",new Date((data[i].timestamp).replace('Z', '').replace('T', ':')));
       var date=new Date((data[i].timestamp));
      var date1=new Date((data[i+1].timestamp))
      // console.log("Diffrence==>",this.timeDifference(date,date1));
      
      this.workingHoursArray.push({deviceName:data[i].vehicleName,timestamp:this.timeDifference(date,date1),Device_ID:data[i].device.Device_ID})
    }
  }
  }
}else{
  this.finalArrayBuild()
}
}
// console.log("TOTAL==",this.workingHoursArray);
}

timeDifference(date1,date2) {
  
  var a = moment(date1);
var b = moment(date2);
a.diff(b, 'seconds')
// console.log(a.diff(b, 'seconds'));


  var seconds = (date1.getTime() - date2.getTime()) / 1000;
  console.log(date1,'-',date2,'=',seconds);
  return seconds>0?seconds:(-seconds)
}

finalArrayBuild(){
  // var totalWorkingHours=[]
 var tempSec=0;
 var tempDays
 var temMin=0;
 var tempHr=0
 var temp
  var result = this.workingHoursArray.reduce(function (r, a) {
        r[a.Device_ID] = r[a.Device_ID] || [];
        r[a.Device_ID].push(a);
        return r;
    }, Object.create(null));

    // console.log("==",result);
    for(var i=0;i<this.deviceArr.length;i++){
      if(result[this.deviceArr[i]]){
      for(var j=0;j<result[this.deviceArr[i]].length;j++){
        tempSec=tempSec+result[this.deviceArr[i]][j].timestamp;
      }
    }
     
        var time= Math.abs(this.timeDifference(this.Fromdate,this.todate));
       
        
        var stopHrs=this.secondsToHms((time-tempSec))
        console.log("++++111111111111111",stopHrs,result[this.deviceArr[i]],this.deviceArr[i],result);
        if(result[this.deviceArr[i]])
        this.totalWorkingHours.push({Device_ID:result[this.deviceArr[i]][j-1].Device_ID,deviceName:result[this.deviceArr[i]][j-1].deviceName,workingHours:this.secondsToHms(tempSec),stopHours:stopHrs});
      // }
      
      tempSec=0
    }
  console.log("sec==>",this.secondsToHms(tempSec),"TOTAL=-",this.totalWorkingHours);

}

secondsToHms(d) {
    d = Number(d);
    var h = Math.floor(d / 3600);
    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);

    var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
    var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
    var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
    return hDisplay + mDisplay + sDisplay; 

}



millisecondConversion(duration){
    var x = duration;
var d = moment.duration(x, 'milliseconds');
var hours = Math.floor(d.asHours());
var mins = Math.floor(d.asMinutes()) - hours * 60;
    var mainMIn = (hours>=24)?0:mins;
return  hours + ":" + mainMIn 
}



expotToPdf(){
    console.log(this.totalWorkingHours);

    this.downloadPdf()
    
  }

// downloadPdf() {
//     let fileName =
//       "Working Report" +
//       new Date().getTime() +
//       PDF_EXTENSION;
//     var pdfsize = "a2";

//     var doc = new jsPDF("p", "pt", pdfsize);
  
//   doc.setFontSize(15);
//   doc.text('Working Report ', 20, 30);
//     doc.setFontStyle("arial");
//     var header = function(data) {
//     doc.setFontSize(15);
//     doc.setTextColor(40);
//     doc.setFontStyle('normal');
   
//   };

//   var options = {
//     beforePageContent: header,
//     margin: {
//       top: 120
//     },
//     startY: doc.autoTableEndPosY() + 20
//   };

//     doc.autoTable({
//       head: this.headRows(),
//       // margin: { top: 80 },
//       body: this.bodyRows(this.totalWorkingHours.length, this.totalWorkingHours),
//       options
      
//     });
//     doc.save(fileName);
//   }

startAddress;

endAddress;
f_date
t_date
downloadPdf() {
  var outerThis=this
    let fileName =
      "Working Hours Report" +
      new Date()+
      PDF_EXTENSION;
    var pdfsize = "a2";
    var totalPagesExp = "{total_pages_count_string}";
//  outerThis.startAddress= outerThis.finalArr[0].address;
//  outerThis.endAddress= outerThis.finalArr[outerThis.finalArr.length-1].address
    var doc = new jsPDF("p", "pt", pdfsize);
    outerThis.f_date = moment(this.Fromdate).format('lll'); 
  outerThis.t_date =moment(this.todate).format('lll');
  // var date_combine = f_date + ' to ' + t_date;
  // doc.setFontSize(30);
   var pageHeight = doc.internal.pageSize.height || doc.internal.pageSize.getHeight();
var pageWidth = doc.internal.pageSize.width || doc.internal.pageSize.getWidth();
  doc.setFontSize(15);
  // doc.text(60, 20, 'Travel Path Report (Date='+date_combine+') Device Name='+this.device_name,);
  
  doc.text("Working Hours Report", 500, 30);
    doc.setFontStyle("arial");

      var header = function(data) {
    doc.setFontSize(30);
    doc.setTextColor(40);
    doc.setFontStyle('arial');
  
  };

  var options = {
    beforePageContent: header,
    margin: {
      top: 120
    },
    
    startY: doc.autoTableEndPosY() + 20
  };
 var logo=localStorage.getItem('logo1');
 outerThis.toDataURL(logo, function (dataUrl) {
                
    doc.autoTable({
      head: outerThis.headRows(),
      // margin: { top: 80 },
      //  startY: doc.autoTable.previous.finalY + 200,
      body: outerThis.bodyRows(outerThis.totalWorkingHours.length, outerThis.totalWorkingHours),
      options,
       styles: {overflow: 'linebreak'},
      // tableLineColor: [0, 0, 0], //choose RGB
        // tableLineWidth: 0.5, //table border width
        // bodyStyles: {
        //     margin: 40,
        //     fontSize: 10,
        //     lineWidth: 0.2,
        //     lineColor: [0, 0, 0]
        // },
      theme:'grid',
      didDrawPage: function (data) {
        // Header
        doc.setFontSize(20);
        doc.setTextColor(40);
        doc.setFontStyle('arial');
        // logo=localStorage.getItem('logo1');
          if(logo)
              doc.addImage(dataUrl, 'JPEG', pageWidth-100, 6, 75, 75);
              doc.autoTable({html:"#headerTable",margin:{bottom:140,left:20,right:8,top:40},theme:'plain'});

        // Footer
        var str = "Page " + doc.internal.getNumberOfPages()
        // Total page number plugin only available in jspdf v1.0+
        if (typeof doc.putTotalPages === 'function') {
            str = str + " of " + totalPagesExp;
        }
        doc.setFontSize(10);

        // jsPDF 1.4+ uses getWidth, <1.4 uses .width
        var pageSize = doc.internal.pageSize;
        var pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight();
        doc.text(str, data.settings.margin.left, pageHeight - 10);
    },
    
      margin: {top: 85},
     
    });
    if (typeof doc.putTotalPages === 'function') {
      doc.putTotalPages(totalPagesExp);
    }
    doc.save(fileName);
  })
  }

   toDataURL(url, callback) {
   
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
            var reader = new FileReader();
            reader.onloadend = function () {
                callback(reader.result);
            }
            reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', url);
        xhr.responseType = 'blob';
        xhr.send();
    }
  headRows() {

    return [
  // displayedColumns=['vehicleName','IMEI','totalDistance','fuel','ignOn','ignOff','idleTime','outOfReach','noGps','trips','maxSpeed','startLocation','endLocation','details'];

      {
        deviceName:'Vehicle Name',
        Device_ID:'IMEI',
        workingHours:'Working Hours',
        stopHours:'Stoping Hours',
      
      }
    ];
  }

  bodyRows(rowCount, pdfBody) {
    console.log(rowCount, pdfBody);

    rowCount = rowCount || 10;
    let body = [];
    for (var j = 0; j < rowCount; j++) {
      body.push({
       deviceName:pdfBody[j].deviceName,
       Device_ID:pdfBody[j].Device_ID,
       workingHours:pdfBody[j].workingHours,
       stopHours:pdfBody[j].stopHours,
      });
    }
    return body;
  }


}


