import { Component, OnInit } from '@angular/core';
import { MdDialog } from '@angular/material';
import { Router } from '@angular/router';
import { ContactService } from '../../../contact.service';
import { DailyDetailsComponent } from '../../../device-report/daily-details/daily-details.component';
declare var jsPDF : any;
declare var $: any;
const PDF_EXTENSION = ".pdf";
import * as moment from 'moment';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { NgModel } from '@angular/forms';
import { ReportService } from '../../report.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-daily-report',
  templateUrl: './daily-report.component.html',
  styleUrls: ['./daily-report.component.scss']
})
export class DailyReportComponent implements OnInit {
    bsConfig: Partial<BsDatepickerConfig>;
deviceArray=[]
deviceArr: any=[];
  showSelectdevice:boolean=false;
  identifier = 'daily_report';
  reportArr: any[];
  from_date
  data_descip:any
  selected = -1;
  private finalise = new Subject<void>();
  constructor(private contactService: ContactService,private router: Router,public dialog: MdDialog,private _service:ReportService) {
    this._service.invokeEvent.pipe(
      takeUntil(this.finalise)
    ).subscribe(value => {
        if(value){
         this.getReport(value); 
       }
      console.log(value);
      
      }); 
   }
 ngOnDestroy(){
    this.finalise.next(void 0);
  }
ingData:any
from1:any;
to1:any;
from2:any;
to2:any;
too:any;
date1 : any;
Fromdate:any;
todate:any;
options=[];
option:any;
dataSelect:any=[];


   fs :any;
   ls :any;
   emailid:any;
   or:any;
   useridd:any;
   device_data:any;
   time:any;
   Load:Boolean = false;
   final : any;
   custtype:any;
   cust:boolean=false;
   devicess:any;
   finall:any;
   logo:any;
   text:any;
   ideal(){
    this.router.navigateByUrl("device-report/ideal-report");
  }
  from:any;
  to:any;
  before:any;
  mb:any;
  logoutbut:boolean;
  dealer:boolean;
  superAdmin:Boolean = false;
  finalArr=[]
   ngOnInit() {
    this.dataSelect = [];
    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.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.mb =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    this.deviceArray=JSON.parse(localStorage.getItem('vehicaleData'));
    
    // this.getDevices();
    // this.dailyReport();
    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();

  //  
  }

 

 

  tab:any;
  exportExcels()
	{
   


	 var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    var table = $('#deviceTable').clone();
    table[0].querySelector("thead").remove();
    console.log(table[0].querySelector("thead"));
    
    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);
	}

//   dailyReport() {
//     this.to = this.date1;
//     var x = new Date(this.to).setHours(23,59,59);
//     console.log(x);
//     var to_date = new Date(x).toISOString();
    
//     var d = new Date(this.date1);
//     let a = d.setHours(0, 0, 0, 0)
//     this.from = new Date(a).toISOString();
//     console.log(to_date);
//     console.log(this.from);
//     window.localStorage['from_date'] = this.from;
//     window.localStorage['to_date'] = to_date;
//     var deviceID;

//     if((this.dataSelect.length!=0)&&(this.dataSelect[0].did!='all')){
//        deviceID = this.dataSelect[0].did;
//     }
//     this.Load = true;
//     this.contactService.getDeviceReport(this.useridd,to_date, this.from,deviceID,this.skip,this.limit).subscribe(
//       data => {
//         this.Load = false;
//         this.device_data = data
//         this.finall = this.device_data.data;
    
//         if(this.finall.length==0){       
        
//           this.lastcall=true;
//         }
//         // console.log('dailyReport=>',this.finall);
//       },(err)=>{
//         // console.log("error");
//         this.Load = false;
//         this.firstcall=true;
//       });
//   }

//   // search filter
//   devicesss:any;
//   getDevices(){
//     // let a = {
//     //   value: "All Devices",
//     //   did : "all",
//     //   id : "all"
//     // }
    
//     //     this.options.push(a);
//     this.contactService.getDevice(this.emailid,this.useridd).subscribe(

//       data => {
//         this.devicesss = data

//         for(let i=0;i<this.devicesss.devices.length;i++){

//           if(this.devicesss.devices[i].type_of_device =="Tracker"){

//             let a ={
//               value : this.devicesss.devices[i].Device_Name,      
//               did:this.devicesss.devices[i].Device_ID,
//               id:this.devicesss.devices[i]._id,

//             }
//             this.options.push(a);
//           }

//         }
//           // console.log("deviceObj",this.options);
//           let that = this;
//           setTimeout(()=>{
//             that.loadropdown();
//           },100)  
//       });
//   }


// filterStates(val) {

//   // console.log(val)
//   // console.log(this.options)

//   if (val) {
//     const filterValue:any = val
//      this.dataSelect = this.options.filter( function(d){
  
//       return d.value.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase()) > -1;    
//     });
//     return this.dataSelect;
//   }

// }

skip: number = 0;
limit: number = 10;
firstcall: boolean = false;
lastcall: boolean = true;

// next(){
//   this.lastcall = false;
//   this.skip += 1;
//   this.dailyReport();
// }

// pre(){
//   // console.log(this.skip)
//     if (this.skip > 0) {
//       this.skip -= 1;
//       this.lastcall = false;
//       this.dailyReport();
//     } else {
//       this.lastcall = true;
//       this.firstcall = false;
//     }

// }
tabelObj: any;
callfunction(): void {
  this.Load = true;
  this.deviceArr =  $('#select').multipleSelect('getSelects','value');
  this.tabelObj.draw();
}
dtOptions:any={}
testTable() {
  const that = this;

  this.Load = true;
  $(document).ready(function() {
      that.tabelObj = $('#deviceTable').DataTable({
        dom: 'lBftip',
        buttons: [
          'copy',
          'print',
          'excel'
        ],       
          "processing": true,
          "searching": false,
          pagingType: 'full_numbers',
          pageLength: 25,
          serverSide: true,
          "scrollY":'60vh', 
          "scrollX": true, 
          "scrollCollapse": true, 
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
          "rowCallback": function(row: Node, data: any | Object, index: number){

             $('#recalculate', row).bind('click', () => {   
              console.log(data);
              var from_date = that.from;
            var to_date =that.date1;
            var user = that.useridd;
            var temp = {
            from_date : from_date,
            to_date : to_date,
            user : user
            }
            var suburl = "";
            suburl += "/summary/distance?from=" + temp.from_date +'&to=' + temp.to_date + '&user=' + temp.user+'&device='+data.imei+'&recalculate='+true;
              that.contactService.get(suburl).subscribe(resp => {  
                console.log(resp);
                that.contactService.post('/summary/recalculate',{id:data._id,distance:resp[0].distance}).subscribe(res=>{
                  console.log(res);
                  that.tabelObj.ajax.reload();
                })
              })
              });

            $('#edit', row).bind('click', () => {   
              var internalThat  = that;         
              let dialogRef = that.dialog.open(DailyDetailsComponent, {
                width: '1020px',
                // height: '1160px',   
                data: { data:data,date:that.date1}
                
              });
          
              // dialogRef.afterClosed().subscribe(result => {
              //   console.log("result",result);
              //   that.ngOnInit();
             
              //     if(result=="done"){
              //       console.log("resultdone",result)
              //       that.tost1("update");
              //       window.localStorage['DataUpdate'] = 'True';
              //       that.sidebar.sidebarData();       
              //     }
              // });              
            }); 
            },
          ajax: (dataTablesParameters: any, callback) => {
                  that.Load = true;
              dataTablesParameters.op = {};
              dataTablesParameters.select = [];
              dataTablesParameters.find = {};
              var currDay = new Date().getDay();
              var currMonth = new Date().getMonth();
              var currYear = new Date().getFullYear();
              var selectedDay = new Date(that.date1).getDay();
              var selectedMonth  = new Date(that.date1).getMonth();
              var selectedYear = new Date(that.date1).getFullYear();
       
              if((currDay== selectedDay)&&(currMonth==selectedMonth) && (currYear == selectedYear)){
                 var devname = "Device_Name";
                 var devid = "Device_ID";
                  var distanceVariation="distanceVariation"
                 var today_odo = "today_odo";
                 var today_running = "today_running";
                 var today_stopped = "today_stopped";
                 var today_trips = "today_trips"; 
                 var maxSpeed = "maxSpeed";
                 var Mileage = "Mileage";
                 var start_location_lat = "today_start_location.lat";
                 var start_location_long = "today_start_location.long";
                 var end_location_lat = "last_location.lat";
                 var end_location_long = "last_location.long";
              
              }else{
              
                var devid = "imei";
                var devname = "ID.Device_Name";
                var distanceVariation="distanceVariation"
                var today_odo = "today_odo";
                var today_running = "today_running";
                var today_stopped = "today_stopped";
                var today_trips = "today_trips"; 
                var maxSpeed = "ID.maxSpeed";
                var Mileage = "Mileage";
                var start_location_lat = "start_location.lat";
                var start_location_long = "start_location.long";
                var end_location_lat = "end_location.lat";
                var end_location_long = "end_location.long";

              }

              dataTablesParameters.columns = [
                // {data: "_id" },
                {data: devname},
                {data:distanceVariation},
                {data: devid},
                {data : today_odo},
                {data : today_running},
                {data : Mileage},           
                {data: today_stopped},
                {data :today_trips},
                {data :maxSpeed},
                {data :"t_idling"},
                {data: "t_noGps"},
                {data : "t_ofr" },
                {data : start_location_lat},
                {data : start_location_long},
                {data : end_location_lat},
                {data : end_location_long},
                {data: null, defaultContent: ''}
              ]        


          
              
                var deviceID;
                dataTablesParameters.find.user_id = that.useridd;

                if(that.deviceArr.length != 0){
                
                  var dev_in = {'$in': that.deviceArr};
                     dataTablesParameters.find.devId = dev_in;
                }
        
              // if ((that.dataSelect.length!=0)&&(that.dataSelect[0].did!='all')) {
              //     dataTablesParameters.find.devId = that.dataSelect[0].did;
              // }

              if (that.date1) {
                  var fdate = new Date(that.date1).toISOString()  
                  // dataTablesParameters.find['created_on'] = dataTablesParameters.find['created_on'] ? dataTablesParameters.find['created_on'] : {};
                  dataTablesParameters.find.date = fdate        
              };

              var suburl = "";
              suburl += "/devices/daily_report"; 
              if(that.date1 && that.deviceArr.length != 0) {             
              that.contactService.post(suburl, dataTablesParameters).subscribe((resp:any) => {
                that.reportArr = [];
                that.reportArr = resp['data'];
                if(that.reportArr.length != 0){
                  var j = 0 ;
                  that.finalArr = [];
                  for(var i = 0 ;i<that.reportArr.length;i++){
                    // if(that.reportArr[i].distanceVariation){
                    //   console.log("IN");
                      
                    //   if(that.reportArr[i].distanceVariation[0]=="+"){
                    //     that.reportArr[i].today_odo=that.reportArr[i].today_odo+(that.reportArr[i].today_odo/100)*Number(that.reportArr[i].distanceVariation.substring(1))
                    //    console.log("IN",(that.reportArr[i].today_odo/100)*Number(that.reportArr[i].distanceVariation.substring(1)));
                    //   }else{

                    //     that.reportArr[i].today_odo=that.reportArr[i].today_odo-(that.reportArr[i].today_odo/100)*Number(that.reportArr[i].distanceVariation.substring(1))
                    //   console.log("IN-",that.reportArr[i].today_odo);
                    //   }
                    // }
                   
                  that.clocation_1(that.reportArr[i],function(err,succ){
                    if(err){
                      console.log(err);
                        j++ ; 
                    }else{
                      that.finalArr.push(succ);
                      console.log(that.finalArr);
                        j++ ; 
                        if(j  === that.reportArr.length){
                          callback({data : that.finalArr});
                        }
                    }
                  })

                     that.Load= false;                 
                  }
                }else{
                
                   that.Load= false;       
                  callback({data : []});

                }
                
                  // that.Load= false;         
                  // callback(resp);
              }, err => {   
                that.Load= false;    
                  
              });
            }else{  
              that.data_descip = "Select vehicle" ;  
                 var x = document.getElementById("toast")
                 x.className = "show";
                 setTimeout(function(){ x.className = x.className.replace("show", ""); }, 1500);
                that.Load= false;       
                  callback({data : []});
            }
          },  
          "columns": [
              {
                  "data": "Device_Name",
                  "defaultContent": "",
                  "render": function(data, type, row) {
            
                     if(row.Device_Name){
                      return row.Device_Name
                     }
                     if(row.ID != null){
                      return row.ID.Device_Name;
                     }else{
                       return "";
                     }
                      
                  }
              },
              {
                  "data": "Device_ID",
                  "defaultContent": "",
                  render: function(data, type, row) {
                      return row.Device_ID ? row.Device_ID : row.imei;
                      // if(row.Device_ID){
                      //   return row.Device_ID;
                      //  }else{
                      //   row.imei;
                      //  }
                
                  }
              },
              {
                  "data": "today_odo",
                  render: function(data, type, row) {
                      return data.toFixed(2);
                  }
              }, 
              {
                "data": "Mileage",
                "defaultContent": "_id",
                render: function(data, type, row) {                            
                  var mileage = ((data == undefined)||(data == NaN))?"NA":(row.today_odo/parseFloat(data)).toFixed(2);
                    return mileage;
                }
            },         
              {
                "data": "today_running",
                render: function(data, type, row) {
                  var ign_on:any;
               
                  if(data != undefined){
                   ign_on =  that.millisecondConversion(parseInt(data));
                  }else{
                    ign_on = '0:0'
                  }
              
            

                    return ign_on;
                }
            },         
            { 
              "data": "today_stopped",
              render: function(data, type, row) {

               
                if((data!=undefined)&&(data!=null)&&(data!=NaN)){
                  var stopped = that.millisecondConversion(data); 
                }else{
                  var stopped = "0:0"; 
                }
                return stopped;
              }
          },  
          {
            "data" : "t_idling",
            render : function(data,type,row){
             
              if((data!=undefined)&&(data!=null)&&(data!=NaN)){
                var idleTime = that.millisecondConversion(data); 
              }else{
                var idleTime = "0:0"; 
              }     
              return idleTime ; 
            }
          },  
          {
            "data" : "t_ofr",
            render : function(data,type,row){
            
              if((data!=undefined)&&(data!=null)&&(data!=NaN)){
                var ofr = that.millisecondConversion(data); 
              }else{
                var ofr = "0:0"; 
              }       
                return ofr ;          
            }

          },  
          {
            "data" : "t_noGps",
            render : function(data,type,row){
            
              if((data!=undefined)&&(data!=null)&&(data!=NaN)){
                if((data < 60000)&&(data == undefined)){
                  var seconds = Math.floor((data / 1000) % 60);
                  seconds = (seconds < 10) ? 0 + seconds : seconds;
               
                  var n_gps = "0:0:" + seconds;
                }else{
                  var n_gps_1 = that.millisecondConversion(data);
                  var n_gps = n_gps_1 + ':0' 
                }
              }else{
                var n_gps = "0:0:0"; 
              }       
                return n_gps ;          
            }

          },     
          {
            "data": "today_trips",
            render: function(data, type, row) {
                return data;
            }
        },   
        {
          "data": "maxSpeed",
          "defaultContent": "_id",
          render: function(data, type, row) {
              // return data;
              if(row.maxSpeed){
                return row.maxSpeed
               }
               if(row. ID!= null){
                return row.ID.maxSpeed;
               }else{
                 return 0;
               }
          }
      },
      {
        "data": "startAddress",
        "defaultContent": "",
        render: function(data, type, row) {
       
      
          return data?data : ""; 

        }
    },
    {
      "data": "endAddress",
      "defaultContent": "",
      render: function(data, type, row) {
        
          return data?data : "";
      }
  } ,
   {
          "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":null,
          "defaultContent": "",
          "render":function(data,type,row){   
            return '<i id="recalculate" title="Recalculate Distance" style="font-size:20px;color: blue" class="fas fa-redo"></i>'    
      }
    },              
          ], 
             "columnDefs": [
            { className: "dt-body-left", "targets": [ 0,1,2,3,4,5,6,7,8,9,10,11,12,13 ] },
            {
              "targets": '_all',
              "createdCell": function (td, cellData, rowData, row, col) {
                  $(td).css('padding', '18px')
              }
          } 
          // { "width": "40px", "targets": [11,12] }  
           
         
          ]   
      });
      that.colSwitch()
  });

}

colSwitch(){
  // var supAdmin=
  this.tabelObj.column( 14).visible( false );
   if(this.superAdmin ==true || localStorage.getItem('superadmin')=="ON"){
     this.tabelObj.column( 14).visible( true );
   }

      // this.tabelObj.column( 28 ).visible( false );
      // this.tabelObj.column( 27 ).visible( false );
      //  this.tabelObj.column( 25).visible( false ); 
      //   this.tabelObj.column( 26).visible( false ); 
 
      //   if((this.superAdmin ==true)||(this.custtype ==true)){
  
      //     this.tabelObj.column( 27).visible( true );       
      //     this.tabelObj.column( 28).visible( true ); 
      //      this.tabelObj.column( 25).visible( true );
      //       this.tabelObj.column( 26).visible( true );
      //      this.tabelObj.column(14).visible( true );
      //      this.tabelObj.column( 13).visible( true );                                  
      //   }

      //   if((this.superAdmin ==false)&&(this.custtype ==false)){
      //     this.tabelObj.column( 9 ).visible( false );
                                     
      //   }
    }

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;
return  hours + ":" + mins;
  
}


loadropdown() {
  let that = this;
  var script = document.createElement("script");
  script.setAttribute("type", "text/javascript");
  script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
  document.getElementsByTagName("head")[0].appendChild(script);
  
  setTimeout(() => {
    that.showSelectdevice = true;
    $('#select').multipleSelect({
      width: 200,
      placeholder: 'Select device.....',
      filter: true,
    })
   // $('#select').show();
 
  }, 100);
}


getReport(event){
  console.log(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);


    
    var x = new Date(tpdata.toDate).setHours(23,59,59);

    this.date1 = new Date(x).toISOString();    
    var d = new Date(this.date1);
    let a = d.setHours(0, 0, 0, 0)
    this.from = new Date(a).toISOString();
  

    
    if(event.deviceArr.length==0){
      deviceId=[];
    }else{
      deviceId= event.deviceArr;
    }
    this.deviceArr = deviceId; 
    
    
 
    // this.tabelObj.clear();
    // var aa = [];
    // this.tabelObj.rows.add(aa); 
      this.tabelObj.ajax.reload();    
  }
 
}

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=>{       
    console.log('resaddresscomingfromAPi',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=>{
          console.log('resaddresscomingfromAPi',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=>{
        console.log('resaddresscomingfromAPi',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);
    }
  })

}

// --------------------New Method for excel export-------------------
exportExcel() {
  for(var i=0;i<this.reportArr.length;i++){
    if(!(this.reportArr[i].Device_ID)){
      this.reportArr[i].Device_ID=this.reportArr[i].imei
    }
    //  if(!(this.reportArr[i].maxSpeed)){
    //   this.reportArr[i].maxSpeed=this.reportArr[i].ID.maxSpeed
    // }
     if(!(this.reportArr[i].Device_Name)){
      this.reportArr[i].Device_Name=this.reportArr[i].ID.Device_Name
    }
    if(this.reportArr[i].Mileage== undefined || (this.reportArr[i].Mileage == NaN))
    {
      this.reportArr[i].Mileage="NA"
    }else{
      this.reportArr[i].Mileage=(this.reportArr[i].today_odo/parseFloat(this.reportArr[i].Mileage)).toFixed(2);
    }
    if(this.reportArr[i].today_running){
      this.reportArr[i].today_running=this.millisecondConversion(parseInt(this.reportArr[i].today_running))
    }else
     this.reportArr[i].today_running='0:0'
    if((this.reportArr[i].today_stopped!=undefined)&&(this.reportArr[i].today_stopped!=null)&&(this.reportArr[i].today_stopped!=NaN)){
      this.reportArr[i].today_stopped=this.millisecondConversion(this.reportArr[i].today_stopped)
    }else
    this.reportArr[i].today_stopped="0:0"

    if((this.reportArr[i].t_idling!=undefined)&&(this.reportArr[i].t_idling!=null)&&(this.reportArr[i].t_idling!=NaN)){
      this.reportArr[i].t_idling=this.millisecondConversion(this.reportArr[i].t_idling)
    }else{
       this.reportArr[i].t_idling="0:0"
    }

     if((this.reportArr[i].t_ofr!=undefined)&&(this.reportArr[i].t_ofr!=null)&&(this.reportArr[i].t_ofr!=NaN)){
      this.reportArr[i].t_ofr=this.millisecondConversion(this.reportArr[i].t_ofr)
    }else{
       this.reportArr[i].t_ofr="0:0"
    }

     if((this.reportArr[i].t_noGps!=undefined)&&(this.reportArr[i].t_noGps!=null)&&(this.reportArr[i].t_noGps!=NaN)){
      if((this.reportArr[i].t_noGps < 60000)&&(this.reportArr[i].t_noGps == undefined)){
                  var seconds = Math.floor((this.reportArr[i].t_noGps / 1000) % 60);
                  seconds = (seconds < 10) ? 0 + seconds : seconds;
                  var n_gps = "0:0:" + seconds;
                  this.reportArr[i].t_noGps=n_gps
                }else{
                  var n_gps_1 = this.millisecondConversion(this.reportArr[i].t_noGps);
                  var n_gps = n_gps_1 + ':0' 
                   this.reportArr[i].t_noGps=n_gps
                }
    }else{
       this.reportArr[i].t_noGps="0:0"
    }
  


  }
    this.downloadFile(this.reportArr);
  }

  downloadFile(data, filename = 'Trip Details') {
   let arrHeader = ["Device_Name", "Device_ID", "today_odo", "Mileage","today_running","today_stopped","t_idling","t_ofr","t_noGps","today_trips","maxSpeed","startAddress","endAddress"];
    let csvData = this.ConvertToCSV(data, arrHeader);
    let blob = new Blob(['\ufeff' + csvData], { type: 'text/csv;charset=utf-8;' });
    let dwldLink = document.createElement("a");
    let url = URL.createObjectURL(blob);
    let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
    if (isSafariBrowser) {  //if Safari open in new window to save file with random filename.
      dwldLink.setAttribute("target", "_blank");
    }
    dwldLink.setAttribute("href", url);
    dwldLink.setAttribute("download", "Daily Report.csv");
    dwldLink.style.visibility = "hidden";
    document.body.appendChild(dwldLink);
    dwldLink.click();
    document.body.removeChild(dwldLink);
  }
  ConvertToCSV(objArray, headerList) {
    let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    // console.log(array,"<===");Distance	126.94
// Running	2:1
// Idle	1:56
// Stop
    
    let str = 'Daily Report \r\n'+new Date(this.date1).getDate()+"/"+(new Date(this.date1).getMonth()+1)+"/"+
    new Date(this.date1).getFullYear()+" \r\n \r\n";
    let row = 'S.No,';

    let newHeaders =["Vehicle Name", "Device IMEI", "Total Distance (Km)", "Fuel consumption (Litre)","Ignition ON Time (Hr:Min)","Ignition OFF Time (Hr:Min)","Idle Time (Hr:Min)","Out of reach (Hr:Min)","No GPS (Hr:Min:Sec)","Trips","Max Speed","Start Location","End Location"];

    for (let index in newHeaders) {
      row += newHeaders[index] + ',';
    }
    row = row.slice(0, -1);
    str += row + '\r\n';
    for (let i = 0; i < array.length; i++) {
      let line = (i + 1) + '';
      if(i<array.length){}
      for (let index in headerList) {
        let head = headerList[index];       
        line += ',' + this.strRep(array[i][head]);
      }
      str += line + '\r\n';
      
    }
    return str;
  }

  strRep(data) {
   
    if(typeof data == "string") {
      let newData = data.replace(/,/g, " ");
       return newData;
    }
    else if(typeof data == "undefined") {
      return "-";
    }
    else if(typeof data == "number") {
      return  data.toString();
    }
    else {
      return data;
    }
  }

  onChange(value){

  this.deviceArr.push(value)  
  console.log("Array=>",this.deviceArr);
  
  }

  equals(objOne, objTwo) {
    if (typeof objOne !== 'undefined' && typeof objTwo !== 'undefined') {
      return objOne.id === objTwo.id;
    }
  }
selectAll(checkAll, select: NgModel, values) {
    //this.toCheck = !this.toCheck;
    if(checkAll){
      select.update.emit(values);

    }
    else{
      select.update.emit([]);
    }
    console.log(this.deviceArr);
    
  }

  expotToPdf(){
     for(var i=0;i<this.reportArr.length;i++){
    if(!(this.reportArr[i].Device_ID)){
      this.reportArr[i].Device_ID=this.reportArr[i].imei
    }
    // if(!(this.reportArr[i].maxSpeed)){
    //   this.reportArr[i].maxSpeed=this.reportArr[i].ID.maxSpeed
    // }
     if(!(this.reportArr[i].Device_Name)){
      this.reportArr[i].Device_Name=this.reportArr[i].ID.Device_Name
    }
    // if(this.reportArr[i].Mileage== undefined || (this.reportArr[i].Mileage == NaN))
    // {
    //   this.reportArr[i].Mileage="NA"
    // }else{
    //   this.reportArr[i].Mileage=(this.reportArr[i].today_odo/parseFloat(this.reportArr[i].Mileage)).toFixed(2);
    // }
    // if(this.reportArr[i].today_running){
    //   this.reportArr[i].today_running=this.millisecondConversion(parseInt(this.reportArr[i].today_running))
    // }else
    //  this.reportArr[i].today_running='0:0'
    // if((this.reportArr[i].today_stopped!=undefined)&&(this.reportArr[i].today_stopped!=null)&&(this.reportArr[i].today_stopped!=NaN)){
    //   this.reportArr[i].today_stopped=this.millisecondConversion(this.reportArr[i].today_stopped)
    // }else
    // this.reportArr[i].today_stopped="0:0"

    // if((this.reportArr[i].t_idling!=undefined)&&(this.reportArr[i].t_idling!=null)&&(this.reportArr[i].t_idling!=NaN)){
    //   this.reportArr[i].t_idling=this.millisecondConversion(this.reportArr[i].t_idling)
    // }else{
    //    this.reportArr[i].t_idling="0:0"
    // }

    //  if((this.reportArr[i].t_ofr!=undefined)&&(this.reportArr[i].t_ofr!=null)&&(this.reportArr[i].t_ofr!=NaN)){
    //   this.reportArr[i].t_ofr=this.millisecondConversion(this.reportArr[i].t_ofr)
    // }else{
    //    this.reportArr[i].t_ofr="0:0"
    // }

    //  if((this.reportArr[i].t_noGps!=undefined)&&(this.reportArr[i].t_noGps!=null)&&(this.reportArr[i].t_noGps!=NaN)){
    //   if((this.reportArr[i].t_noGps < 60000)&&(this.reportArr[i].t_noGps == undefined)){
    //               var seconds = Math.floor((this.reportArr[i].t_noGps / 1000) % 60);
    //               seconds = (seconds < 10) ? 0 + seconds : seconds;
    //               var n_gps = "0:0:" + seconds;
    //               this.reportArr[i].t_noGps=n_gps
    //             }else{
    //               var n_gps_1 = this.millisecondConversion(this.reportArr[i].t_noGps);
    //               var n_gps = n_gps_1 + ':0' 
    //                this.reportArr[i].t_noGps=n_gps
    //             }
    // }else{
    //    this.reportArr[i].t_noGps="0:0"
    // }
    //  if(this.reportArr[i].maxSpeed){
    //   this.reportArr[i].maxSpeed=this.reportArr[i].maxSpeed
    // }
    // if(this.reportArr[i].ID!= null){
    //   this.reportArr[i].maxSpeed=this.reportArr[i].ID.maxSpeed
    // }else{
    //    this.reportArr[i].maxSpeed=0
    // }


  }

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

//     var doc = new jsPDF("p", "pt", pdfsize);
//     var f_date = moment(this.Fromdate).format('lll'); 
//   var t_date =moment(this.todate).format('lll');
//   var date_combine = f_date + ' to ' + t_date;
//   // doc.setFontSize(30);
//   doc.setFontSize(15);
//   doc.text('Daily Report ', 20, 30);
//   // doc.text(date_combine, 250, 60);
//     doc.setFontStyle("arial");

//       var header = function(data) {
//     doc.setFontSize(15);
//     doc.setTextColor(40);
//     doc.setFontStyle('normal');
//     //doc.addImage(headerImgData, 'JPEG', data.settings.margin.left, 20, 50, 50);
//     // doc.text("Testing Report", data.settings.margin.left, 50);
//   };

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

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

startAddress;

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

      {
        Device_Name:'Vehicle',
        Device_ID:'IMEI',
        today_odo:'Total Distance',
        Mileage:'Fuel',
        today_running:'Ignition On',
        today_stopped:'Ignition Off',
        t_idling:'Idle Time',
        t_ofr:'Out Of reach',
        t_noGps:'No GPS',
        today_trips:'Trips',
        maxSpeed:'Max Speed',
        startAddress:'Start Location',
        endAddress:'End Location',
      }
    ];
  }

  bodyRows(rowCount, pdfBody) {
    console.log(pdfBody,"<===PDFBODY");
    
    console.log(rowCount, pdfBody);

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

       Device_Name:pdfBody[j].Device_Name,
        Device_ID:pdfBody[j].Device_ID,
        today_odo:(pdfBody[j].today_odo).toFixed(2),
        Mileage:((pdfBody[j].Mileage == undefined)||(pdfBody[j].Mileage == NaN))?"NA":(pdfBody[j].today_odo/parseFloat(pdfBody[j].Mileage)).toFixed(2),
        today_running:this.millisecondConversion(parseInt(pdfBody[j].today_running)),
        today_stopped:this.millisecondConversion(parseInt(pdfBody[j].today_stopped)),
        t_idling:this.millisecondConversion(parseInt(pdfBody[j].t_idling)),
        t_ofr:this.millisecondConversion(parseInt(pdfBody[j].t_ofr)),
        t_noGps:this.millisecondConversion(parseInt(pdfBody[j].t_noGps)),
        today_trips:pdfBody[j].today_trips,
        maxSpeed:pdfBody[j].maxSpeed,
        startAddress:pdfBody[j].startAddress,
        endAddress:pdfBody[j].endAddress,

      });
    }
    return body;
  }


}



 // let geocoder = new google.maps.Geocoder();
      // let t_latlng = new google.maps.LatLng(latlngObj.lat, latlngObj.long);

      // let request = {
      //   latLng: t_latlng
      // };
      // geocoder.geocode(request, function (data, status) {
      //   if (status == google.maps.GeocoderStatus.OK) {
      //     if (data[0] != null) {
        
      //       var addressObj = {
      //         "lat":latlngObj.lat,
      //         "long":latlngObj.long,
      //         "address":la
      //       }
      //         this.contactService.saveAdd(addressObj).subscribe(res=>{
                  
      //          cb(null,data[0].formatted_address);      
      //         },err=>{  
      //           console.log("couldn't save address");           
      //          cb(null,data[0].formatted_address);      
      //         })        
      //     } else {
         
      //     cb(null,"No address available");
      //     }
      //   }
      //   else {
      //     cb(null,'NA');
      //   }

      // })

// {"$and":[{"$or":[{"user":ObjectId("5cee7da97a38f414a4e5dfa3")},{"dealer":ObjectId("5cee7da97a38f414a4e5dfa3")}]},{"imei":{"$in":["866551039594085","866551039599415"]}},{"dateParts.day":12},{"dateParts.month":8},{"dateParts.year":2021}]}