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';
import { ReportService } from '../../report.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
// declare function show
declare var google: any;
declare var jsPDF: any;
declare var $: any;
const PDF_EXTENSION = ".pdf";
declare var moment: any;
@Component({
  selector: 'app-disatance-report',
  templateUrl: './disatance-report.component.html',
  styleUrls: ['./disatance-report.component.scss']
})
export class DisatanceReportComponent implements OnInit {
  finalArr = []
  dataSelect: any[];
  closeProcess: number;
  deviceArr: any = [];
  reportArr: any = [];
  firstcall: boolean = true;
  lastcall: boolean = true;
  skip: number = 0;
  tabelObj: any;
  devices: any;
  value
  distanceVariation
  private finalise = new Subject<void>();
  constructor(private contactService: ContactService, private _service: ReportService, private router: Router, public dialog: MdDialog, private _flashMessagesService: FlashMessagesService) {
    this._service.invokeEventForDistance.pipe(
      takeUntil(this.finalise)
    ).subscribe(value => {
      if (value) {
        this.value = value
        this.getReport(value);
      }
      console.log(value);
      this.devices = JSON.parse(localStorage.getItem('vehicaleData'))
      console.log(this.devices);


    })

  }

  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.testTable();

  }



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


  data_descip: any;
  TODATE
  FROMDATE
  tpdata
  getReport(event) {
    if (event == 'getExcel') {
      this.exportExcel();
    } else if (event == 'getPdf') {
      this.expotToPdf();
    } else {
      var deviceId: any;
      this.tpdata = event;
      var that = this;
      var fd = new Date(this.tpdata.fromDate);
      var td = new Date(this.tpdata.toDate);
      var toDATE = new Date(this.tpdata.fromDate);
      this.TODATE = moment(this.tpdata.toDate).format('LL')
      this.FROMDATE = moment(this.tpdata.fromDate).format('LL')
      var date: any = toDATE.setDate(toDATE.getDate() + 1)
      // this.FROMDATE=new Date(date).toISOString().replace(/T.*/,'').split('-').reverse().join('-')
      // this.TODATE=td.toISOString().replace(/T.*/,'').split('-').reverse().join('-')
      console.log("FROM", this.FROMDATE, "==", this.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);
            //   var fromDate=new Date(that.Fromdate)
            // var date=new Date(fromDate.setDate(fromDate.getDate()+1)).toISOString() 

            let dialogRef = that.dialog.open(DetailComponent, {
              // width: '950px',
              // height: '1160px',  
              data: data.details

            });
          });

          $('#refresh', row).bind('click', () => {
            var internalThat = that;
            console.log('rowrowrowrow=>', row);
            console.log('datadatadatadata', data);

            let geocoder = new google.maps.Geocoder();
            let t_latlng
            var d_lat;
            var d_lng;
            console.log();

            if (typeof (data.startAddress) == 'object') {
              t_latlng = new google.maps.LatLng(data.startLat, data.startLng);
              d_lat = data.startLat;
              d_lng = data.startLng
            } else {
              t_latlng = new google.maps.LatLng(data.endLat, data.endLng);
              d_lat = data.endLat;
              d_lng = data.endLng
            }

            let request = {
              latLng: t_latlng
            };
            geocoder.geocode(request, function (data, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                if (data[0] != null) {
                  var liveAdd = data[0].formatted_address;
                  // //console.log(outerThis.liveAdd);
                  that.saveAddress(d_lat, d_lng, liveAdd)
                }
              }
              else {

                // that.liveAdd = 'NA';


              }

            })
          })
          // else{

          //   outerThis.liveAdd = res.address;
          // }
          // console.log("ADDRESS---->",outerThis.liveAdd);

          // })



          // });

        },
        ajax: (dataTablesParameters, callback) => {
          console.log(that.Fromdate);
          var date
          var deviceID;
          // if(that.Fromdate){
          //   var fromDate=new Date(that.Fromdate)
          //   date=new Date(fromDate.setDate(fromDate.getDate()+1)).toISOString()

          // }
          console.log(date);
          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/getDistanceNew?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: any) => {
              that.Load = false;
              that.reportArr = [];
              that.reportArr = resp;

              if (that.reportArr.length != 0) {
                var j = 0;
                that.finalArr = [];
                for (var i = 0; i < that.reportArr.length; i++) {
                  if (that.reportArr[i].reportData){

                    that.clocation_1(that.reportArr[i].reportData, function (err, succ) {
                      if (err) {
                        console.log(err);
                        j++;
                      } else {
                        console.log(succ);
                        that.finalArr.push(succ);
                        console.log(that.finalArr);
                        j++;
                        if (j === that.reportArr.length) {
                          that.Load = false;
                          callback({ data: that.finalArr });
                        }
                      }
                    })
                  }else{
                    that.Load = false;
                    callback({ data: [] });
                  }



                }
              } 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;
            that.data_descip = "Select vehicle";
            var x = document.getElementById("toast")
            x.className = "show";
            setTimeout(function () { x.className = x.className.replace("show", ""); }, 1500);
            callback({ data: [] });
          }
        },

        "columns": [
          {
            "data": "VRN",
            "render": function (data, type, row) {
              return data ? data : '';
            }
          },
          {
            "data": "from_date",
            "render": function (data, type, row) {
              // let date=new Date(that.Fromdate).getDate()+"/"+new Date(that.Fromdate).getMonth()+"/"+new Date(that.Fromdate).getFullYear()                 
              return that.FROMDATE;
            }
          },
          {
            "data": "to_date",
            "render": function (data, type, row) {
              // let date=new Date(that.todate).getDate()+"/"+new Date(that.todate).getMonth()+"/"+new Date(that.todate).getFullYear()                                   
              return that.TODATE;
            }
          },
          {
            "data": "startAddress",
            "defaultContent": "",
            render: function (data, type, row) {
              var address
              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 `<button class="btn btn=info btn-sm"><i id="refresh" title="Refresh Address" style="font-size:20px;color: green" class="fas fa-redo"></i></button>`;
              } else {
                return data ? data : '--';
              }


            }
          },
          {
            "data": "endAddress",
            "defaultContent": "",
            render: function (data, type, row) {
              var address
              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 `<button class="btn btn=info btn-sm"><i id="refresh" title="Refresh Address" style="font-size:20px;color: green" class="fas fa-redo"></i></button>`;
              } 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>'
          // },
        ]
      });

    });

  }
  saveAddress(lat, lng, address) {
    var addressObj = {
      "lat": lat,
      "long": lng,
      "address": address
    }
    this.contactService.saveAdd(addressObj).subscribe(res => {
      console.log(res);
      this.getReport(this.value);
    }, err => {
      //console.log("couldn't save address");
    })

  }



  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;
    this.finalise.next(void 0);
  }


  clocation_1(latlngObj, cb) {

    var outerThis = this;
    var la = '';

    let latLng = {
      lat: "0",
      long: "0"
    };

    latLng = {
      lat: latlngObj.start_location ? latlngObj.start_location.lat ? latlngObj.start_location.lat : 0:0,
      long: latlngObj.start_location ? latlngObj.start_location.long ? latlngObj.start_location.long : 0: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.end_location ? latlngObj.end_location.lat ? latlngObj.end_location.lat : 0:0,
          long: latlngObj.end_location ? latlngObj.end_location.long ? latlngObj.end_location.long : 0: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);
          }

        },err=>{
          latlngObj['endAddress'] = 'N/A';
          cb(null, latlngObj);
        })

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

        latLng_1 = {
          lat: latlngObj.end_location ? latlngObj.end_location.lat ? latlngObj.end_location.lat :0: 0,
          long: latlngObj.end_location ? latlngObj.end_location.long ? latlngObj.end_location.long :0: 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'] = 'N/A';
            cb(null, latlngObj);


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

        },err=>{
          latlngObj['endAddress'] = 'N/A';
          cb(null, latlngObj);
        })

        // cb(null,latlngObj);
      }
    },err=>{
      latlngObj['startAddress'] = 'N/A';
      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 = 'Distance Report') {

    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", "Distance 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 = '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;
    }
  }

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

    this.downloadPdf()

  }
  // downloadPdf() {
  //     let fileName =
  //       "Distance 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('Distance 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.finalArr.length, this.finalArr),
  //       options

  //     });
  //     doc.save(fileName);
  //   }



  startAddress;

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

        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",
            styles: { fontSize: 13, textColor: "[255,72,72]" },
            margin: { bottom: 140, left: 40, 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: 'Device Name',
        fromDate: 'From Date',
        toDate: 'To Date',
        startAddress: 'Start Location',
        endAddress: 'End Location',
        distance: "Total KM"
      }
    ];
  }


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

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

        device: pdfBody[j].device.Device_Name,
        fromDate: this.FROMDATE,
        toDate: this.TODATE,
        startAddress: pdfBody[j].startAddress,
        endAddress: pdfBody[j].endAddress,
        distance: pdfBody[j].distance.toFixed(2),

      });
    }
    return body;
  }






}
