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 { DetailComponent } from './details/details.component';
// declare function show
declare var google: any;
declare var $: any;
declare var moment:any;

// function show(){
//     alert('Hello!!!');
// }

@Component({
  selector: 'app-distance-report',
  templateUrl: './distance-report.component.html',
  styleUrls: ['./distance-report.component.scss']
})
export class DistanceReportComponent implements OnInit {
  dataSelect: any[];
  closeProcess: number;
  deviceArr: any=[];
  reportArr: any=[];
firstcall:boolean=true;
  lastcall:boolean=true;
  skip:number=0;
  tabelObj: any ;

  constructor(private contactService: ContactService,private router: Router,public dialog: MdDialog,private _flashMessagesService:FlashMessagesService) {

   }

  fs : any;
  ls : any;
  emailid : 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;
  before:any;
  date1:any;
  daily_report_data:any;
  superAdmin:Boolean = false;
  ngOnInit() {
    // var fTime = new Date().setHours(0,0,0);
    // this.Fromdate = new Date(fTime);
  //  show()
      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.contactService.getDevice(this.emailid,this.useridd).subscribe(

    //   data => {
    //     this.devicesss = data
     
    //     this.finall = (this.devicesss.devices);

    //     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,
    //           viewValue:this.devicesss.devices[i].Device_Name,
    //           did:this.devicesss.devices[i].Device_ID,
    //           id:this.devicesss.devices[i]._id,
    //           user:this.devicesss.devices[i].user,
    //           email: this.devicesss.devices[i].Email_ID,
    //           deviceType: this.devicesss.devices[i].type_of_device
    //         }
    //         this.options.push(a);
    //       }

    //     }
    //       // console.log(this.options);
     

    //   });


    this.testTable();
    // this.testTables()
  }

//   ign(){
//     this.router.navigateByUrl("device-report/ign-report");
  
//   }

//   ignition_report(){
//     this.cond = false
//     this.router.navigateByUrl("device-report/ignition_report");


//   }

//   notification(){
//     this.cond = false
//     this.router.navigateByUrl("notifications");
//   }



//   ideal(){
//     this.router.navigateByUrl("device-report/ideal-report");
//   }
//   geo(){
//     this.router.navigateByUrl("geofencing");
    
//   }

//   Ddetail(){
//     this.router.navigateByUrl("driverdetail");
//   }
//   DModel(){
//     this.router.navigateByUrl("deviceModel");
//   }
//   VType(){
//     this.router.navigateByUrl("VehicleType");
//   }

//   myaccount(){
   
//     let dialogRef = this.dialog.open(MyaccountComponent, {
//       width: '903px',
//       data: {}
//     });
  
//     dialogRef.afterClosed().subscribe(result => {
  
//       if(result == "succ"){
//         // console.log("Updated")
//       }
  
//     });
//   }
// openNav() {
//   /*  document.getElementById("myNav").style.width = "100%";
// */
//    this.router.navigateByUrl("location");

// }
// logout(){
//   window.localStorage.clear();
//   this.router.navigateByUrl("login");
// }
// devi(){
//   this.router.navigateByUrl("dashboard");

// }
// soon(){
//   this.router.navigateByUrl("const?_i="+window.localStorage.token);
  
// }

// vehicleRoute(){
//   this.router.navigateByUrl("vehicleRoute");

// }

// dealerInfo(){
//   this.cond = false
//   this.router.navigateByUrl("dealerInfo");
// }

// new(){
//   this.router.navigateByUrl("new");
  
// }
// cond:Boolean = false;
// point : any = 0;
//  a(){
//   // console.log(this.point);
//    if(this.point == 0){
//     this.cond = true;
//     this.point ++;
//    }
//  else if(this.point % 2 == 0){
//   this.cond = true;
//   this.point ++;
//  }
//  else{
//    this.cond = false
//    this.point ++;
//  }

  
// }
// addcus(){
//   this.router.navigateByUrl("add");
// }
// report(){
//   this.cond = false
//   this.router.navigateByUrl("device-report");

// }
// report_speed(){
//   // console.log("report speed call")
//   this.cond = false
//   this.router.navigateByUrl("device-report/device-speed-report");
// }
// mydealer(){
//   window.localStorage['token'] =  window.localStorage['Dealer_token'];
//   localStorage.removeItem('devices');
//   window.localStorage['DataUpdate'] = 'True';
//   if(window.localStorage['DataLoaded'] = 'True'){
//     window.localStorage['Custumer'] = 'OFF'
//     this.router.navigateByUrl("add")
//    // this.router.navigateByUrl("const?_status="+"OK");
//   }
// }

// summaryReport(){

//   this.cond = false
//   this.router.navigateByUrl("device-report/summary-report");
// }

// driverPerformance(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/Driver-performance");
// }

// geofancingReport(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/geofancing");
// }


// route_map(){
//   this.router.navigateByUrl("routeMapping");

// }

// overspeed(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/overspeed");

// }

// routeViolation(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/routeViolation");

// }

// stoppage_report(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/stoppage_report");

// }
// distance_report(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/distance_report");
// }

// group(){
//   this.cond = false
//   this.router.navigateByUrl("group_view");
// }
// trip_report(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/trip_report");

// }


// alert_report(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/alert_report");
// }

   
uId:any;
d_name:any;
d_report:any;
total_dist:any;
total_km:any;
start_add_lat:any;
start_add_long:any;
end_add_lat:any;
end_add_long:any;
device_summary=[];
address_show:any;

end_add_show:any;
identifier:any = 'distance_report';

// distanceRep(Fromdate,todate){
//   // console.log(this.dataSelect)
//   this.device_summary=[];
//   var devId='';
//   var userID = this.useridd;
//   if((this.dataSelect==undefined)||(this.dataSelect.length==0)){
//     devId="";
//   }else{
//     devId= this.dataSelect?this.dataSelect[0].id:"";
//   }


// let f_date = Fromdate.toISOString();
// let t_date =  todate.toISOString();


// var outerThis = this;
// this.Load=true;
// this.contactService.distanceReport(f_date, t_date, userID,devId)
//     .subscribe(res=>{
//       this.Load=false;
//       // console.log(res);
//       this.d_report=res;
//         var i = 0;
//         // howManyTimes =  this.d_report.length;
//         this.closeProcess=this.d_report.length;
//         for(var k=0;k<this.d_report.length;k++){
//           this.d_name = outerThis.d_report[k].device.Device_Name;
//           this.total_km = outerThis.d_report[k].distance;
//           this.device_summary.push({
//             "devicename": outerThis.d_name,
//             "totalkm":outerThis.total_km
//           })
//         }      
//         function f() {
//           outerThis.start_add_lat = outerThis.d_report[i].startLat?outerThis.d_report[i].startLat:null;
//           outerThis.start_add_long = outerThis.d_report[i].startLng?outerThis.d_report[i].startLng:null;

//           outerThis.end_add_lat= outerThis.d_report[i].endLat?outerThis.d_report[i].endLat:null;
//           outerThis.end_add_long= outerThis.d_report[i].endLng?outerThis.d_report[i].endLng:null         
//           var geocoder = new google.maps.Geocoder();
//           var latlng_start = new google.maps.LatLng(outerThis.start_add_lat,outerThis.start_add_long);
//           var geocoder_end = 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){
//                 // console.log(data[0].formatted_address);
              
//                  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;
//             // console.log(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,4000 );
//           }
//         }
//         f();

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

// }


data_descip:any;
getReport(event){
  if(event == 'getExcel'){
    this.exportExcel();
  }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; 
    console.log('this.deviceArr',this.deviceArr);
    this.Fromdate = fd.toISOString();
    this.todate = td.toISOString();
 
      var diff = moment(this.todate).diff(this.Fromdate, 'days')
      if(diff>=31){

          this.data_descip = 'Report is unavailable for more than a month';
          launch_toast();

      }else if(diff>=15 && this.deviceArr.length>=10){
        // if(this.deviceArr.length>=10){
  
          this.data_descip = 'Please select less than 10 vehicals';
          launch_toast();
        // }
      }else{
        this.skip = 0;
        this.firstcall=false;
        this.lastcall= true;
        this.tabelObj.ajax.reload();     
      }
    }
    
  function launch_toast() {
    // console.log(divid);
    var x = document.getElementById("toast")
    //console.log(x);
    x.className = "show";
    setTimeout(function () { x.className = x.className.replace("show", ""); }, 4500);
  }
  
}

testTable() {
  const that = this;
  console.log("inside function");
  $(document).ready(function() {
     that.tabelObj = $('#deviceTable').DataTable({
        // dom: 'Bfrtip',
        // buttons: [
        //   'copy',
        //   'print',
        //   'excel'
        // ],       
          "processing": false,
          "searching": true, 
          pagingType: 'full_numbers',
          pageLength: 25,
          serverSide: false,
          responsive: true,
          "scrollY":'60vh',  
          "scrollCollapse": true, 
          
          // "deferLoading": 25 ,  
          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(DetailComponent, {
                // width: '950px',
                // height: '1160px',   
                data: { _id: data.device._id, des: data.Device_Des, sim:data.sim_number, dname:data.Device_Name, speed:data.SpeedLimit,iconType:data.iconType,drname:data.driver_name,dcontact:data.contact_number,expdate:data.expiration_date,model:data.maxSpeed,mainmodel:data.device_model,assigned_to:data.user,vehicleType:data.vehicleType,devIMEI:data.Device_ID,S_provider:data.sim_provider,tot_ODO:data.total_odo,itiId:data.integrationId,simNUM2:data.sim_number2,simProvider2:data.sim_provider2,devObj:data,from_date :that.Fromdate,to_date : that.todate}
                
              });             
            }); 
            },
          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 = "";
            // var limit = 26;
            suburl += "/summary/distance?from=" + temp.from_date +'&to=' + temp.to_date + '&user=' + temp.user + '&skip='+that.skip ;
            if(that.deviceArr.length != 0){  
              suburl +='&device='+that.deviceArr;
            }
            if(that.deviceArr.length != 0 && temp.from_date && temp.to_date ){
            that.contactService.get(suburl).subscribe(resp => {   
                that.Load = false;  
                that.reportArr = [];
                that.reportArr= resp ; 
            
                if (that.reportArr.length != 0) {
                  var j = 0;
                  var finalArr = [];
                  for (var i = 0; i < that.reportArr.length; i++) {
    
                    that.clocation_1(that.reportArr[i], function (err, succ) {
                      if (err) {
                        console.log(err);
                        j++;
                      } else {
                        finalArr.push(succ);
                        console.log(finalArr);
                        j++;
                        if (j === that.reportArr.length) {
                          that.Load = false;
                          callback({ data: finalArr });
                        }
                      }
                    })
    
                   
                  }
                } else {
                  that.Load = false;
                  that.firstcall=true;
                  that.lastcall=(that.skip>0)?false:true;
                  callback({ data: [] });
    
                }
            }, err => {   
              that.Load= false;    
              callback({ data: [] });
              console.log("error",err) ;     
            });
          }else{
            that.Load= false;    
              callback({ data: [] });
          }
        },  
      
          "columns": [
              {
                  "data": "device",
                  "render": function(data, type, row) {                   
                    return data?data.Device_Name : '';                  
                  }
              },
               {
                  "data": "from_date",
                  "render": function(data, type, row) { 
                    let date=new Date(that.Fromdate).getDate()+"/"+new Date(that.Fromdate).getMonth()+1+"/"+new Date(that.Fromdate).getFullYear()                 
                    return date;                  
                  }
              },
               {
                  "data": "to_date",
                  "render": function(data, type, row) { 
                    let date=new Date(that.todate).getDate()+"/"+new Date(that.todate).getMonth()+1+"/"+new Date(that.todate).getFullYear()                                   
                    return date;                  
                  }
              },
              {
                  "data": "startAddress",
                  "defaultContent": "",
                  render: function(data, type, row) {            
                  
                    var aiden = typeof(data) ;
                    if(aiden == 'object'){
                      var addressLink = '<a href="https://maps.google.com/?q='+ data.latlng.lat +','+data.latlng.long +' "  target="_blank" title="Click to get vehicle start location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>'; 
                      return addressLink;
                    }else{
                      return data?data : '--';   
                    }
                     
                    
                  }
              },
              {
                  "data": "endAddress",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    var biden = typeof data ; 
                    if(biden === 'object'){
                      var addressLink = '<a href="https://maps.google.com/?q='+ data.latlng.lat +','+data.latlng.long +' "  target="_blank" title="Click to get vehicle last location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>'; 
                      return addressLink; 
                    }else{
                      return data?data : '--';   
                    }
                 
                  }
              },        
            {
              "data": "distance",
              render: function(data, type, row) { 
           
                return data?data.toFixed(2):0;
              }
          } ,
         {
          "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>'    
      }
    }
// <i class="fas fa-info-circle"></i>
          ],  
          "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')
          //     }
          // } ,
          // { "width": "10px", "targets": 0 },
          // { "width": "40px", "targets": 1 },
          // { "width": "100px", "targets": 2 },
          // { "width": "70px", "targets": 3 },  
          //           { "width": "10px", "targets": 3 },   
 
    //       {
    //     targets: -1, //-1 es la ultima columna y 0 la primera
    //     data: null,
    //     defaultContent: '<div class="btn-group"> <button (click)="show()">view</button></div>'
    // },
          ] 
      });

  });

}



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];
  
	    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, ""); 

	    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) {

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

     
  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;

  }
   
 
  }

  ngOnDestroy(){
    this.closeProcess= 0;

  }

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

    let latLng = {
      lat: "0",
      long: "0"
    };
  
      latLng = {
        lat: latlngObj.startLat ? latlngObj.startLat : 0,
        long: latlngObj.startLng ? latlngObj.startLng : 0
      }
    
  
    // if () {
    //   latLng = {
    //     lat: 0,
    //     long: 0
    //   }
    // }

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

        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res => {
          if (res.message == "Address not found in databse") {
            var bdata = {
              iden : 'noaddress',
              latlng : latLng_1
            }
        
            latlngObj['endAddress'] = bdata;
            cb(null, latlngObj);


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

        })

      } else {
        latlngObj['startAddress'] = res.address;
        var latLng_1 = {
          lat: "0",
          long: "0"
        };
    
          latLng_1 = {
            lat: latlngObj.endLat ? latlngObj.endLat : 0,
            long: latlngObj.endLng ? latlngObj.endLng : 0
          }
        
 


        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res => {
          if (res.message == "Address not found in databse") {
            var cdata = {
              iden : 'noaddress',
              latlng : latLng_1
            }
        
            latlngObj['endAddress'] = cdata;
            cb(null, latlngObj);


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

        })

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

  }

  
  next() {
    // this.deviceData =[];
    this.lastcall=false;
    this.skip += 1; 
    // this.sidebarData();
    // this.ngOnInit();
    this.tabelObj.ajax.reload();     
  }
  pre() {
    // this.deviceData=[]
    // console.log(this.skip)
    if(this.skip>0){
      this.skip -= 1;   
      this.lastcall=false;
      // this.sidebarData();
      // this.ngOnInit();
      this.tabelObj.ajax.reload();     
    }else{
      this.lastcall=true;
      this.firstcall=false;
    }
   
  }
  
// --------------------New Method for excel export-------------------
exportExcels() {
   for(var i=0;i<this.reportArr.length;i++){
    this.reportArr[i].deviceName=this.reportArr[i].device.Device_Name;
   }

    this.downloadFile(this.reportArr);
  }

  downloadFile(data, filename = 'Trip Details') {
   
    let arrHeader = ["deviceName", "startAddress", "endAddress", "distance"];
    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", "Trip Details.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 = 'Distance Report \r\n'+"From ="+this.Fromdate+"   To="+this.todate+" \r\n \r\n";
    let row = 'S.No,';

    let newHeaders =["Device Name", "Start Location", "End Location", "Total K.M"];

    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;
    }
  }


  
 

}
