
import { Component, OnInit } from '@angular/core';
import { ContactService } from '../../../contact.service';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import { MyaccountComponent } from '../../../myaccount/myaccount.component';
import { Params,Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { min } from 'rxjs/operator/min';
import { ReportService } from '../../report.service';
import { SummaryDetailsComponent } from './summary-details/summary-details.component';
import { takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';


declare var google: any;
// declare var jquery:any;
declare var jsPDF : any;
declare var $: any;
const PDF_EXTENSION = ".pdf"
declare var moment :any;
// declare var $:any;
// declare var TableExport:any;

@Component({
  selector: 'app-summary-report',
  templateUrl: './summary-report.component.html',
  styleUrls: ['./summary-report.component.scss']
})
export class SummaryReportComponent implements OnInit {
  finalArr=[]
  sumReport: any;
  date1:any;
  neww:any;
  fs : any;
  Load:boolean=false;
  ls : any;
  emailid : any;
  or : any;
  useridd :any;
  time :any;
  device_data:any;
  devicess:any;
  final:any;
  custtype:any;
  cust: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;
  before:any;
  superAdmin:Boolean = false;
  xlbutton: boolean= false;
  dataSelect: any[];
  closeProcess: any;
  lattitude: any;
  longitude: any;
  lattitude1: any;
  longitude1: any;
  addressLink: string;
  addressLink1: string;
private finalise = new Subject<void>();
  constructor(private contactService: ContactService,private router: Router,public dialog: MdDialog,private _service:ReportService,private _flashMessagesService: FlashMessagesService) {
  this._service.invokeEventForsummaryReport.pipe(
      takeUntil(this.finalise)
    ).subscribe(value => {
        if(value){
         this.getReport(value); 
       }
      });
   }

   ngOnDestroy(){
    this.closeProcess= 0;
    this.finalise.next(void 0);
  }

  ngOnInit() {

    var fTime = new Date();
    // fTime.setDate(fTime.getDate()-1);
    // fTime.setHours(0,0,0,0); 
    // this.Fromdate=new Date(fTime);
    $('#select').hide();
    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.testTable();  
  }

  selectedPeople:any;
  people= ['1','2','3',];

  device_summary =[];
  summary:any;
  d_name:any;
  total_running_time:any;
  stop_time:any;
  overSpeed:any;
  route_violation:any;
  trips:any;
  total_km:any;
  address_show:any;
  end_add_show:any;
  start_add:any;
  end_add:any;
  start_add_lat:any;
  start_add_long:any;
  end_add_lat:any;
  end_add_long:any;
  uId:any;
  
  deviceArr = [];

  getReport(event){
     if (event == 'getExcel') {
      this.exportExcel();
    } else if(event=='getPdf')
  {
    this.expotToPdf();
  }else{
      var deviceId: any;
      var tpdata = event ; 
      var that = this;
     
      var fd = new Date(tpdata.fromDate);
      var td  = new Date(tpdata.toDate);
      if(event.deviceArr.length==0){
        deviceId=[];
      }else{
        deviceId= event.deviceArr;
      }
      this.deviceArr = deviceId; 
      
      this.Fromdate = fd.toISOString();
      this.todate = td.toISOString();
      console.log("b4");
   
    
      
      this.tabelObj.ajax.reload();      
        
    
    }
    
  
  }
  // summary_report(Fromdate,todate){
  //   // console.log(this.dataSelect[0]);
  //   // console.log(this.dataSelect) 
  //   console.log($('#select').multipleSelect('getSelects','value'));
  //   this.deviceArr =  $('#select').multipleSelect('getSelects','value');
  //   console.log(Fromdate,todate);
  //   var devID;
  //   // if(!option){
  //     this.uId = this.useridd;
  //     if((this.deviceArr==undefined)||(this.deviceArr.length==0)){
  //       devID=[];
  //     }else{
  //       devID= this.deviceArr;
  //       console.log("device ID=>",devID);
  //     }

  //     if(Fromdate == null){
  //       this._flashMessagesService.show("Please select fromdate ", { cssClass: 'alert-danger', timeout: 3000 });
  //       return;
  //     }
  //     if(todate == null){
  //       this._flashMessagesService.show("Please Select todate", { cssClass: 'alert-danger', timeout: 3000 });
  //       return ;
  //     }
  //   let f1 = new Date(Fromdate).setHours(0,0,0,0);
  //   console.log("f1",f1);
    
  //   let f_date = new Date(f1).toISOString();
  //   let t1 = new Date(todate).setHours(23,59,59,999);
  //   console.log('t1',t1);
  //   let t_date =  new Date(t1).toISOString();
  //   // console.log(f_date);
  //   // console.log(t_date);
  //   this.device_summary=[];
  //   var outerThis = this;
  //   // console.log(this.useridd);
  //   // console.log(this.uId);
  //   this.Load = true;
  //   this.contactService.summary_rep_new(f_date, t_date, this.uId,devID)
  //     .subscribe(res=>{
  //       if(res.message == 'Fromdate is mandatory'){
  //         this._flashMessagesService.show(res.message, { cssClass: 'alert-danger', timeout: 3000 });
  //         this.Load = false;
  //         return
  //       }
  //       if(res.message == 'todate is mandatory'){
  //         this._flashMessagesService.show(res.message, { cssClass: 'alert-danger', timeout: 3000 });
  //         this.Load = false;
  //         return
  //       }
  //       if(res.message == 'user is mandatory'){
  //         this._flashMessagesService.show(res.message, { cssClass: 'alert-danger', timeout: 3000 });
  //         this.Load = false;
  //         return
  //       }

     
        
  //       this.Load = false;
  //        console.log("summary console =>",res);
  //       this.summary=res;
  //       if(this.summary.length == 0){
  //         this._flashMessagesService.show("No record found", { cssClass: 'alert-danger', timeout: 3000 });
  //       }
  //       console.log(this.summary);
  //       var i = 0;
  //       // howManyTimes =  this.summary.length;
  //       this.closeProcess= this.summary.length;
        
  //       var hourconversion = 2.7777778 / 10000000 ; 
       
  //       for(var j=0;j<this.summary.length;j++){
  //         this.device_summary.push({
  //           "devicename": this.summary[j].devObj[0]?this.summary[j].devObj[0].Device_Name:'NA',
  //           "TotalrunningTime":this.millisecondConversion(this.summary[j].today_running),
  //           "stopTime": this.millisecondConversion(this.summary[j].today_stopped),
  //           "idleTime": this.millisecondConversion(this.summary[j].t_idling),
  //           "ourTime": this.millisecondConversion(this.summary[j].t_ofr),
  //           "nogps" :this.millisecondConversion(this.summary[j].t_noGps),
  //           "overSpeed": this.millisecondConversion(this.summary[j].today_overspeeds),
  //           "routeViolation": this.summary[j].today_routeViolations,
  //           "start_add": this.summary[j].start_location,
  //           "end_add": this.summary[j].end_location,
  //           "trip": this.summary[j].today_trips,
  //           "totalkm":this.summary[j].today_odo,
  //           "fuelConsumption" : ((this.summary[j].devObj[0].Mileage == null)||(this.summary[j].devObj[0].Mileage == undefined))?"NA":(this.summary[j].today_odo/parseFloat(this.summary[j].devObj[0].Mileage)).toFixed(2)
  //           // "todayRunning" : todayRunning,
  //           // "todayStopped" : todayStopped
  //         })
  //       }
        
  //       // function f() {
  //       //   if((outerThis.summary[i].start_location!=null)&&(outerThis.summary[i].end_location!=null)){
  //       //     outerThis.start_add_lat =  outerThis.summary[i].start_location.lat;
  //       //     outerThis.start_add_long= outerThis.summary[i].start_location.long;
           
  //       //   }else{
  //       //     outerThis.start_add_lat = null;
  //       //     outerThis.start_add_long= null;
          
  //       //   }

  //       //   if((outerThis.summary[i].end_location!=null)&&(outerThis.summary[i].end_location!=null)){
  //       //     outerThis.end_add_lat= outerThis.summary[i].end_location.lat;
  //       //     outerThis.end_add_long= outerThis.summary[i].end_location.long;

  //       //   }else{

  //       //     outerThis.end_add_lat=null;
  //       //     outerThis.end_add_long=null;

  //       //   }
       
  //       //   var geocoder = new google.maps.Geocoder();
  //       //   var latlng_start = new google.maps.LatLng(outerThis.start_add_lat,outerThis.start_add_long);
  //       //   var end_add = new google.maps.Geocoder();
  //       //   var latlng_end = new google.maps.LatLng(outerThis.end_add_lat,outerThis.end_add_long);

  //       //   var request={
  //       //     latLng:latlng_start
  //       //   }

  //       //   var request_end={
  //       //     latLng:latlng_end
  //       //   }
      
       
  //       //   geocoder.geocode(request, function(data,status){
  //       //     if(status == google.maps.GeocoderStatus.OK){
  //       //       if(data[0]!=null){
              
  //       //          this.start_add = data[0].formatted_address;
  //       //          if(this.start_add=="Antarctica"){
  //       //           this.start_add="NA";
  //       //          }
  //       //          outerThis.address_show = this.start_add;
               
               
  //       //       }else{
  //       //         this.start_add="NA";
  //       //       }
  //       //     }
  //       //     else{
           
  //       //       this.start_add ="NA";
  //       //       outerThis.address_show = this.start_add
           
  //       //     }  
  //       //     outerThis.device_summary[i-1].address= outerThis.address_show;
           
  //       //   })


  //       //   geocoder.geocode(request_end, function(data1,status){
  //       //     if(status == google.maps.GeocoderStatus.OK){
  //       //       if(data1[0]!=null){
              
  //       //          this.end_add = data1[0].formatted_address;
  //       //          if(this.end_add=="Antarctica"){
  //       //           this.end_add="NA";
  //       //          }
  //       //          outerThis.end_add_show = this.end_add;
               
               
  //       //       }else{
  //       //         this.end_add="NA"
  //       //       }
  //       //     }
  //       //     else{
           
  //       //       this.end_add ='NA';
  //       //       outerThis.end_add_show  = this.end_add;
           
  //       //     }  
  //       //     outerThis.device_summary[i-1].address_end= outerThis.end_add_show;
  //       //     // console.log(outerThis.address_show);
  //       //   })
  //       //   i++;
  //       //   if( i < outerThis.closeProcess ){
  //       //       setTimeout( f,5000 );
  //       //   }
  //       // }
  //       // f();

  //       this.xlbutton = true;
    
    
  //     },(error)=>{
  //       this.Load=false;
  //       // console.log(error.status);
  //       // console.log("No Record Found !!!");
  //       this._flashMessagesService.show('Internal Server Error', { cssClass: 'alert-danger', timeout: 3000 });
  //     })
  // }


  tabelObj: any ;
  identifier:String = 'summary_report';
testTable() {
  const that = this;
  console.log("inside function");
 
  $(document).ready(function() {
 
     that.tabelObj = $('#deviceTable').DataTable({
        dom: 'lBftip',
        buttons: [
          'copy',
          'print',
          'excel'
        ],       
          "processing": false,
          "searching": true, 
          pagingType: 'full_numbers',
          pageLength: 25,
          serverSide: false,
          "scrollY":'63vh',     
          "scrollX": true,
          "scrollCollapse": true,     
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
          "rowCallback": function(row: Node, data: any | Object, index: number){
          $('#edit', row).bind('click', () => {   
              var internalThat  = that;
              // console.log('rowrowrowrow=>',row);
              console.log('datadatadatadata',data);
          
              let dialogRef = that.dialog.open(SummaryDetailsComponent, {
                // width: '950px',
                // height: '1160px',   
                data: { trips:data.trip}
                
              });             
            }); 
          },
          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
            }

            var suburl = "";
            that.device_summary =[];

            if((temp.from_date != undefined)&&(temp.to_date != undefined)){
              suburl += "/summary/summaryReport?from=" + temp.from_date +'&to=' + temp.to_date + '&user=' + temp.user;
              if(that.deviceArr.length != 0){  
                suburl +='&device='+that.deviceArr;
              }
              that.contactService.get(suburl).subscribe((resp:any) => {   
                  // console.log(ignReport.length); 
                  that.summary =[];
                  that.Load= false;    
                  that.device_summary = [];      
                  that.summary = resp ; 
                  console.log(that.summary);
                  var hourconversion = 2.7777778 / 10000000 ; 
              that.summary= resp ; 
              if (that.summary.length != 0) {
                var j = 0;
                 that.finalArr = [];
                for (var i = 0; i < that.summary.length; i++) {
  
                  that.clocation_1(that.summary[i], function (err, succ) {
                    if (err) {
                      console.log(err);
                      j++;
                    } else {
                      that.finalArr.push(succ);
                      console.log(that.finalArr);
                      j++;
                      if (j === that.summary.length) {
                        that.Load = false;
                        var x = [];
                        that.finalArr.sort(function(a,b){
                          // Turn your strings into dates, and then subtract them
                          // to get a value that is either negative, positive, or zero.
                          var aDate:any = new Date(a.Date);
                          var bDate:any = new Date(b.Date);  
                          return bDate - aDate;
                        });
                
                        
                        callback({ data: that.finalArr });
                      }
                    }
                  })
  
                 
                }
              } else {
                that.Load = false;
                callback({ data: [] });
  
              }
                 
              }, err => {   
                that.Load= false;    
                console.log("error",err) ;     
              });
            }else{
              that.Load= false;    
              let ta = [];
              callback({data : ta });  

            }

 
        },  
      
          "columns": [
            {
              "data": "devObj",
              "defaultContent": "",
              "render": function (data, type, row) {  
                        
                return (data.length != 0) ? data.Device_Name : '';
              }
            },
     
                    {
              "data": "startAddress",
              "defaultContent": "",
              render: function (data, type, row) {
                console.log(data);
                
                  if(data!=""){
                     return  data?data:''; 
                  }else{
                    let lat = row.start_location.lat?row.start_location.lat:null;
                    let long = row.start_location.long?row.start_location.long:null;       
                    var addressLink = '<a href="https://maps.google.com/?q='+ lat +','+long +' "  target="_blank" title="Click to get vehicle Start location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>';            

                    return  addressLink;  
                  }
              
              }
            },    
            {
              "data": "endAddress",
              "defaultContent": "",
              render: function (data, type, row) {
               if(data!=""){
                     return  data?data:''; 
                  }else{
                    let lat = row.end_location.lat?row.end_location.lat:null;
                    let long = row.end_location.long?row.end_location.long:null;       
                    var addressLink = '<a href="https://maps.google.com/?q='+ lat +','+long +' "  target="_blank" title="Click to get vehicle Start location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>';            

                    return  addressLink;  
                  } 
              
              }
            }, 
            {
              "data": "total_odo",
              "defaultContent": "",
              render: function (data, type, row) {

                return data?data.toFixed(2) : "00.00";
              }
            }
            ,    
            // {
            //   "data": "devObj",
            //   "defaultContent": "",
            //   render: function (data, type, row) {
              
            //     console.log(data.Mileage);
          
            //   var milage =   (data.length==0)?"NA":((data[0].Mileage == null)||(data[0].Mileage == undefined))?"NA":(row.today_odo/parseInt(data[0].Mileage)).toFixed(2);
            //     return milage ? milage : "00:00";
            //   }
            // },
       
      
            // {
            //   "data": "today_trips",
            //   "defaultContent": "",
            //   render: function (data, type, row) {

            //     return data?data:"0";
            //   }
            // },
       
            {
              "data": "today_running",
              "defaultContent": "",
              render: function (data, type, row) {
                console.log("running",that.millisecondConversion(data));
                
                return data?that.millisecondConversion(data):"00:00";
              }
            },
             
         
        
            {
              "data": "today_stopped",
              "defaultContent": "",
              render: function (data, type, row) {
                 console.log("today_stopped",data);
                return data?that.millisecondConversion(data):0;
              }
            },
         
       
            // {
            //   "data": "t_idling",
            //   "defaultContent": "",
            //   render: function (data, type, row) {

            //     return data?that.millisecondConversion(data):"00:00";
            //   }
            // },
            {
          "data":null,
          "defaultContent": "",
          "render":function(data,type,row){   
            return '<button class="btn btn=info btn-sm"><i id="edit" title="Edit Vehicle" style="font-size:20px;color: green" class="fas fa-info-circle"></i></button>'    
              }
            }
        
         
            // {
            //   "data": "t_ofr",
            //   "defaultContent": "",
            //   render: function (data, type, row) {

            //     return data?that.millisecondConversion(data):"00:00";
            //   }
            // },
            // {
            //   "data": null,
            //   "defaultContent": "",
            //   render: function (data, type, row) {
            //     console.log('datatatatatatatatatata=>',data);
            //     var dateDiff = ((data.today_running!=undefined)?data.today_running:0) + ((data.t_idling !=undefined)?data.t_idling:0);
            //     return data?that.millisecondConversion(dateDiff):"00:00";
            //   }
            // },
         
          
            // {
            //   "data": "t_noGps",
            //   "defaultContent": "",
            //   render: function (data, type, row) {

            //   return data?that.millisecondConversion(data):"00:00";
            //   }
            // },
         
            // {
            //   "data": "today_overspeeds",
            //   "defaultContent": "",
            //   render: function (data, type, row) {

            //     return data?that.millisecondConversion(data):"0.0";
            //   }
            // },
            // {
            //   "data": "today_maxSpeed",
            //   "defaultContent": "",
            //   render: function (data, type, row) {

            //     return data?data:0;
            //   }
            // },      
            // {
            //   "data": "today_ign_on",
            //   "defaultContent": "",
            //   render: function (data, type, row) {

            //     return data?data:0;
            //   }
            // },    {
            //   "data": "today_ign_off",
            //   "defaultContent": "",
            //   render: function (data, type, row) {

            //     return data?data:0;
            //   }
            // },
            // {
            //   "data": "today_routeViolations",
            //   "defaultContent": "",
            //   render: function (data, type, row) {

            //     return data?data:0;
            //   }
            // }                       
          ],  
          "columnDefs": [
            { className: "dt-body-left", "targets": [ 0,1,2,3,4,5,6] },
          //   {
          //     "targets": '_all',
          //     "createdCell": function (td, cellData, rowData, row, col) {
          //         $(td).css('padding', '18px')
          //     }
          // }   
           
         
          ] 
      });

  });

}



  // exportExcel(tableID, filename){
  //   // TableExport(document.getElementsByTagName("table"));
  
  //     var downloadLink;
  //     var dataType = 'application/vnd.ms-excel';
  //     var tableSelect = document.getElementById(tableID);
  //     var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
      
  //     // Specify file name
  //     filename = filename?filename+'.xls':'excel_data.xls';
      
  //     // Create download link element
  //     downloadLink = document.createElement("a");
      
  //     document.body.appendChild(downloadLink);
      
  //     if(navigator.msSaveOrOpenBlob){
  //         var blob = new Blob(['\ufeff', tableHTML], {
  //             type: dataType
  //         });
  //         navigator.msSaveOrOpenBlob( blob, filename);
  //     }else{
  //         // Create a link to the file
  //         downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
      
  //         // Setting the file name
  //         downloadLink.download = filename;
          
  //         //triggering the function
  //         downloadLink.click();
  //     }
  // }
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+"</tr>";
	    }

	    tab_text=tab_text+"</table>";
	    // tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
	    // tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your 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);
  }
  

  filterStates(val) {


    if (val==""){

      this.dataSelect = [];
      // console.log("deviceValue",this.dataSelect);
    } else{
 
      const filterValue:any = val;
      
       this.dataSelect = this.options.filter(function(d){
        var t = d.value.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase());
      //  this.option = this.options[i];
    
     
        return t > -1;    
      });
      
        return this.dataSelect;
    }
   
  
  
  }
  


  getlink(report : any){
      // console.log("report=>",report);
    var lat = report.start_add?report.start_add.lat:0;
    var lng = report.start_add?report.start_add.long:0;
    this.addressLink =  'https://maps.google.com/?q=' + lat + ',' + lng;  
    return this.addressLink ; 
  }
  
  getlink1(report:any){
   
    // console.log("report=>",report);
    var lat = report.end_add?report.end_add.lat:0;
    var lng = report.end_add?report.end_add.long:0;
    this.addressLink1 =  'https://maps.google.com/?q=' + lat + ',' + lng;
    return this.addressLink ; 
  }


  millisecondConversion(duration){
    console.log("duration",duration);
    
      // var  minutes = Math.floor((duration / (1000 * 60)) % 60);
      // var  hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
  
      // hours = (hours < 10) ? 0 + hours : hours;
      // minutes = (minutes < 10) ? 0 + minutes : minutes;
    
      // return hours + ":" + minutes ;
      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;

    
  }
  clocation_1(latlngObj, cb) {
    var outerThis = this;
    var la = '';

    let latLng = {
      lat: "0",
      long: "0"
    };
    if (latlngObj.start_location) {
      latLng = {
        lat: latlngObj.start_location.lat ? latlngObj.start_location.lat : 0,
        long: latlngObj.start_location.long ? latlngObj.start_location.long : 0
      }
    }
    if (latlngObj.today_start_location) {
      latLng = {
        lat: latlngObj.today_start_location.lat ? latlngObj.today_start_location.lat : 0,
        long: latlngObj.today_start_location.long ? latlngObj.today_start_location.long : 0
      }
    }

    // if () {
    //   latLng = {
    //     lat: 0,
    //     long: 0
    //   }
    // }

    outerThis.contactService.getAddressByApi(latLng).subscribe(res => {
      if (res.message == "Address not found in databse") {
        latlngObj['startAddress'] = "NA";
        // cb(null,latlngObj);
        var latLng_1 = {
          lat: "0",
          long: "0"
        };
        if (latlngObj.last_location) {
          latLng_1 = {
            lat: latlngObj.last_location.lat ? latlngObj.last_location.lat : 0,
            long: latlngObj.last_location.long ? latlngObj.last_location.long : 0
          }

        }
        if (latlngObj.end_location) {
          latLng_1 = {
            lat: latlngObj.end_location.lat ? latlngObj.end_location.lat : 0,
            long: latlngObj.end_location.long ? latlngObj.end_location.long : 0
          }
        }


        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res => {
          if (res.message == "Address not found in databse") {
            latlngObj['endAddress'] = "NA";
            cb(null, latlngObj);


          } else {
            latlngObj['endAddress'] = res.address;
            cb(null, latlngObj);
          }

        })

      } else {
        latlngObj['startAddress'] = res.address;
        var latLng_1 = {
          lat: "0",
          long: "0"
        };
        if (latlngObj.last_location) {
          latLng_1 = {
            lat: latlngObj.last_location.lat ? latlngObj.last_location.lat : 0,
            long: latlngObj.last_location.long ? latlngObj.last_location.long : 0
          }

        }
        if (latlngObj.end_location) {
          latLng_1 = {
            lat: latlngObj.end_location.lat ? latlngObj.end_location.lat : 0,
            long: latlngObj.end_location.long ? latlngObj.end_location.long : 0
          }
        }


        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res => {
          if (res.message == "Address not found in databse") {
            latlngObj['endAddress'] = "NA";
            cb(null, latlngObj);


          } else {
            latlngObj['endAddress'] = res.address;
            cb(null, latlngObj);
          }

        })

        // cb(null,latlngObj);
      }
    })

  }

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

    this.downloadPdf()
    
  }

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

//     var doc = new jsPDF("p", "pt", pdfsize);
  
//   doc.setFontSize(15);
//   doc.text('Summary 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.finalArr.length, this.finalArr),
//       options
      
//     });
//     doc.save(fileName);
//   }

startAddress;

endAddress;
f_date
t_date
downloadPdf() {
  var outerThis=this
    let fileName =
      "Summary 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("Summary 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.finalArr.length, outerThis.finalArr),
      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'];

      {
        vehicleName:'Vehicle Name',
        startAddress:'Start Point',
        endAddress:'End Point',
        total_odo:'Total Km',
        today_running:'Running (HH:MM)',
        today_stopped:'Stop (HH:MM)',
        
      }
    ];
  }

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

    rowCount = rowCount || 10;
    let body = [];
    for (var j = 0; j < rowCount; j++) {
      body.push({

       vehicleName:pdfBody[j].devObj.Device_Name,
       startAddress:pdfBody[j].startAddress,
       endAddress:pdfBody[j].endAddress?pdfBody[j].endAddress:'N/A',  
       total_odo:pdfBody[j].total_odo?(pdfBody[j].total_odo).toFixed(2):0, 
       today_running:this.millisecondConversion(pdfBody[j].today_running),
        today_stopped:this.millisecondConversion(pdfBody[j].today_stopped)
      });
    }
    return body;
  }

  



  }



         //   if((outerThis.summary[i].start_location!=null)&&(outerThis.summary[i].end_location!=null)){
        //     outerThis.start_add_lat =  outerThis.summary[i].start_location.lat;
        //     outerThis.start_add_long= outerThis.summary[i].start_location.long;
           
        //   }else{
        //     outerThis.start_add_lat = null;
        //     outerThis.start_add_long= null;
          
        //   }

        //   if((outerThis.summary[i].end_location!=null)&&(outerThis.summary[i].end_location!=null)){
        //     outerThis.end_add_lat= outerThis.summary[i].end_location.lat;
        //     outerThis.end_add_long= outerThis.summary[i].end_location.long;

        //   }else{

        //     outerThis.end_add_lat=null;
        //     outerThis.end_add_long=null;

        //   }

  




