import { Component, OnInit } from '@angular/core';
import { ContactService } from '../../../contact.service';
import { Http, Headers, RequestOptions, ResponseContentType } from '@angular/http';
import { saveAs } from 'file-saver';
import { environment } from '../../../../environments/environment';
import { MdSnackBar, MdDialog } from '@angular/material';
const PDF_EXTENSION = ".pdf"
import * as moment from 'moment';

declare var google: any;
declare var jsPDF : any;
declare var $: any;declare var google: any;

import { PlayTripComponent } from '../../../play-trip/play-trip.component';
import { ReportService } from '../../report.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
const now = new Date();

@Component({
  selector: 'app-trip-load-unload',
  templateUrl: './trip-load-unload.component.html',
  styleUrls: ['./trip-load-unload.component.scss']
})
export class TripLoadUnloadComponent implements OnInit {
  dateStr: any;
  Fromdate = new Date();
  tableSwitch:boolean= true;
  todate = new Date();
  useridd: any;
  fDate: any;
  tDate: any;
  dev_url = environment.hostUrl;
  // dateString=['Today Report','Yesterday Report','Weekly Report','Monthly Report'];
  fromDate: any;
  toDate: any;
  Load: boolean;
  tabelObj: any;
  tabelObj_grouped:any;
  custtype: any;
  superAdmin: any;
  data_descip: string;
  reportArr :any= [];
  emailid: any;
  devicesss: any;
  options: any;
  finall: any;
  private finalise = new Subject<void>();
  constructor(private contactService: ContactService, private _service:ReportService,private http: Http, public snackBar: MdSnackBar,public dialog: MdDialog) { 
    this._service.invokeEventForloadunloadTrip.pipe(
      takeUntil(this.finalise)
    ).subscribe(value => {
        if(value){
         this.getReport(value); 
       }
      }); 
  }
  ngOnDestroy(){
    this.finalise.next(void 0);
  }

  ngOnInit() {
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    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.tDate = new Date();
    var fd = new Date();
    fd.setHours(0, 0, 0, 0);
    this.fDate = fd;
    // this.getDevices();
  
    this.testTable();
    var tt= this;
    setTimeout(()=>{
      tt.testTable_grouped();
     
    },5000)
  
  }

  deviceArr = [];
  tab: any;

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

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

    }

    tab_text = tab_text + "</table>";

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

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

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

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

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

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

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

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

    return (sa);

    
  }


  testTable() {
    const that = this;
    console.log("inside function");
    $(document).ready(function () {
      that.tabelObj = $('#deviceTable').DataTable({  
        "processing": true,
        "searching": true,
        pagingType: 'full_numbers',
        pageLength: 25,
        serverSide: false,
        deferRender: true,
        scrollY:    '55vh',
        scrollX : true,
        scrollCollapse: true,
     
        "sScrollX": "100%",
        scroller:       true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        ajax: (dataTablesParameters, callback) => {
          console.log('temptemptemptemptemp', dataTablesParameters);
          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 = "";
          // https://www.oneqlik.in/trackRouteMap/getTripReport?userid=59cbbdbe508f164aa2fef3d8
          suburl += "/trackRouteMap/getTripReport?userid=" + that.useridd +'&from='+from_date.toISOString()+ '&to='+ to_date.toISOString();
          if (that.deviceArr.length != 0) {
            suburl += '&device=' + that.deviceArr;
          }

          console.log('that.deviceArr',that.deviceArr);
       
            that.contactService.get(suburl).subscribe(resp => {
              console.log('resp=>',resp); 
              // var tripData = [];
              // tripData = resp ; 

              // that.reportArr = [];
              that.reportArr= resp ; 
              that.Load = false; 
            
              callback({ data: resp });
       
            }, err => {
              that.Load = false;
              var errCode = err.status;
              if(errCode == 500){
                callback({ data: [] });
              }
              console.log("error", err);
            });
        },
        "rowCallback": function(row: Node, data: any | Object, index: number){  
          $('#playTrip', row).bind('click', () => {  
            console.log(data);
           console.log(data.reportingDateTime);
           console.log(data.exitDateTime);
            var fd = new Date(data.loadingPoint.reportingDateTime).toISOString();
            var td = new Date(data.destination.exitDateTime).toISOString();
              var replayObj= {
                fromdate:fd,
                todate : td,
                user : that.useridd,
                device:{imei: data.deviceId,_id: data.device_id,iconType:'car'},
                geofences:[data.Source, data.Destination]  ,
                distance: (typeof data.distanceTravelled === 'number')?(parseFloat(data.distanceTravelled).toFixed(2)):0    
              }

              let dialogRef = that.dialog.open(PlayTripComponent, {    
                data: replayObj
              });
            
              dialogRef.afterClosed().subscribe(result => {
                console.log(result);
                if(result == 'cancelled'){
                
                }
              })  
             
              
            }); 
             
        }
      ,
         

        "columns": [
          // {
          //   "data": "_id",
          //   "defaultContent": "",
          //   "visible" : false,
          //   "render": function (data, type, row) {       
           
          //     return data ? data : "";   
          //   }
          // },
          
          {
            "data": "vrn",
            "defaultContent": "",
            "render": function (data, type, row) {       
           
              return data ? data : "";   
            }
          },
          {
            "data": "Source",
            "defaultContent": "",
            "render": function (data, type, row) {       
           
              return data ? data.geoname : "";   
            }
          },
          {
            "data": "Destination",
            "defaultContent": "",
            render: function (data, type, row) {
              return data ? data.geoname : '';
            }
          },
          {
            "data": "loadingPoint",
            "defaultContent": "",
            render: function (data, type, row) {    
            return data ? moment(data.reportingDateTime).format('llll') : "--";
            }
          },
          {
            "data": "loadingPoint",
            "defaultContent": "",
            render: function (data, type, row) {   
              return data ? moment(data.exitDateTime).format('llll') : '--';
            }
          },
          //-------------UNLOADING NEW------------
          {
             "data": "destination",
            "defaultContent": "",
            render: function (data, type, row) {   
              return data.reportingDateTime ? moment(data.reportingDateTime).format('llll') : '--';
            }
          },
          {
             "data": "destination",
            "defaultContent": "",
            render: function (data, type, row) {   
              return data.exitDateTime ? moment(data.exitDateTime).format('llll') : '--';
            }
          },
          // <!-- startSiteEnterAt - Loading Start
          //           startSiteExitAt - Loading Exit
          //           endSitEnterAt - Unloading Start
          //           endSiteExitAt - Unloading Exit -->
          {
            "data": "distanceTravelled",
            "defaultContent": "",
            render: function (data, type, row) {
              return data ? parseFloat(data).toFixed(2) : 0.0;
            }
          },
          {
            "data": "tripTime",
            "defaultContent": "",
            render: function (data, type, row) {
              return data ? that.secondsToHms(data.total) : "0:0";
            }
          },
          {
            "data": "tripTime",
            "defaultContent": "",
            render: function (data, type, row) {
              that.secondsToHms(data.running);
              return data ? that.secondsToHms(data.running) : '0:0';
            }
          },
          {
            "data": "tripTime",
            "defaultContent": "",
            render: function (data, type, row) {
              return data ? that.secondsToHms(data.stoppage) :'0:0';
            }
          },
          {
            "data": "tripTime",
            "defaultContent": "",
            render: function (data, type, row) {
              return  '--';
            }
          }
          ,
          {
            "data": "status",
            "defaultContent": "",
            render: function (data, type, row) {
              return  data;
            }
          }
          ,
          {
            "data": "null",
            "defaultContent": "",
            render: function(data, type, row) {    
              if(row.status  == 'COMPLETED'){
                return '<i id="playTrip" style="color:green;cursor:pointer" class="fas fa-play"></i>';
              }else{
                return '<i class="fas fa-times"></i>';
              }
          
            }
        }    
        ]
        // "columnDefs": [
        //   { className: "dt-body-left", "targets": [0, 1, 2, 3,4,5,6,7] },
        //   {
        //     "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 },

        // ]
      });

    });

  }

  testTable_grouped() {

    const that = this;
    console.log("inside function grouped");
    $(document).ready(function () {
      that.tabelObj_grouped = $('#deviceTable_grouped').DataTable({
      
        "processing": true,
        "searching": true,
        pagingType: 'full_numbers',
        pageLength: 25,
        serverSide: false,
        "scrollX": true,
        "scrollY": '65vh',
        "scrollCollapse": true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        ajax: (dataTablesParameters, callback) => {
          console.log('temptemptemptemptemp', dataTablesParameters);
          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 = "";
        
          suburl += "/trackRouteMap/getTripCountReport?userid=" +that.useridd +'&from='+from_date.toISOString()+ '&to='+ to_date.toISOString();
          if (that.deviceArr.length != 0) {
            suburl += '&device=' + that.deviceArr;
          }
          console.log('B4 grouped data called');
            that.contactService.get(suburl).subscribe(resp => {    
              // console.log('response for grouped Data',resp);
            callback({ data: resp });
            }, err => {
              // that.Load = false;
              console.log('Error Detected in load unload grouped');
              callback({ data: [] });
              // var errCode = err.status;
              // if(errCode == 500){
               
              // }
            });
        },
        "rowCallback": function( row, data, index ) {
          // console.log(data);
         
          // var colorChk = data.utilization?parseFloat(data.utilization).toFixed(2):null;
          // console.log(row);
          if (data.utilization >= 60 )
          {
              $('td', row).css({'background-color': '#3ded1d','border-bottom' :'1px solid white'});
          }
          else if(data.utilization<60)
          {
              $('td', row).css({'background-color': '#FF0800' ,'border-bottom' :'1px solid white'});
          }else{
            $('td', row).css({'background-color': 'grey','border-bottom' :'1px solid white'});
          }
      },
 
        "columns": [
       
          
          {
            "data": "Vehicle Name",
            "defaultContent": "",
            "render": function (data, type, row) {       
           
              return data ? data : "";   
            }
          },
          {
            "data": "Source",
            "defaultContent": "",
            "render": function (data, type, row) {       
              // console.log('datadatadatadatadatadatadatadata',data.source)
              return data ? data.geoname : "--";   
            }
          },
          {
            "data": "Destination",
            "defaultContent": "",
            render: function (data, type, row) {
              // console.log('datadatadatadatadatadatadatadata',data)
              return data ? data.geoname : '--';
            }
          },
          {
            "data": "distanceTravelled",
            "defaultContent": "",
            render: function (data, type, row) {    
            return data ? data.toFixed(2):0;
            }
          },
          {
            "data": "running",
            "defaultContent": "",
            render: function (data, type, row) {    
            return  data ? that.secondsToHms(data) : "0:0";
            }
          },
          {
            "data": "stoppage",
            "defaultContent": "",
            render: function (data, type, row) {    
            return  data ? that.secondsToHms(data) : "0:0";
            }
          },
          {
            "data": "idle",
            "defaultContent": "",
            render: function (data, type, row) {    
            return  data ? that.secondsToHms(data) : "0:0";
            }
          },
          {
            "data": "utilization",
            "defaultContent": "",
            render: function (data, type, row) {    
            var  d = data?parseFloat(data).toFixed(2):'0'
            return  d;
            }
          },
          {
            "data": "efficiency",
            "defaultContent": "",
            render: function (data, type, row) {    
              var  e = data?parseFloat(data).toFixed(2):'0'
            return  e;
            }
          },
          {
            "data": "tripCount",
            "defaultContent": "",
            render: function (data, type, row) {   
              return data ?data:0;
            }
          }
      
        ],
        "columnDefs": [
          // { className: "dt-body-left", "targets": [0, 1, 2, 3,4] },
        ]
      });

    });

  }

  identifier: any = 'loadunloadTrip';
  getReport(event) {
    console.log("inside function");
    if (event == 'getExcel') {
      if(this.detector === 'group'){
        console.log('group');
       
        this.exportExcel_grouped();
        
      }
      if(this.detector === 'detail'){
         console.log('detail');
        // this.exportExcel();
         this.exportExcelforGroup()
        
      }
     
    }else if(event=='getPdf')
  {
    // this.expotToPdf();
  } else {
      var deviceId: any;
      var tpdata = event;
      var that = this;
      var fd = new Date(tpdata.fromDate);
      var td = new Date(tpdata.toDate);

      if (event.deviceArr.length == 0) {
        deviceId = [];
      } else {
       
        deviceId = event.deviceArr;
      }
      this.deviceArr = deviceId;
      this.Fromdate = fd;
      this.todate = td;
     
      this.tabelObj.ajax.reload();
     var pt = this;
     var tmp =  setTimeout(()=>{
        pt.tabelObj_grouped.ajax.reload();
        clearTimeout(tmp);
      },2000)
     
    }

  }


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

    var hDisplay = h > 0 ? h : "0";
    var mDisplay = m > 0 ? m : "0";
    var sDisplay = s > 0 ? s  : "0";
    return hDisplay + ":" +mDisplay; 
}

detector='group';
changeDetector(iden){
 
  
  if(iden === 'detail'){
    this.detector = 'detail';
  }
  if(iden === 'group'){
    this.detector = 'group';


  }
}


exportExcelforGroup() {
  var array=[]
  for(var i=0;i<this.reportArr.length;i++){
      array.push({
        'vrn':this.reportArr[i].vrn,
        'Sourcegeoname':this.reportArr[i].Source.geoname,
        'Destinationgeoname':this.reportArr[i].Destination.geoname,
        'loadingreportingDateTime':this.reportArr[i].loadingPoint.reportingDateTime?  moment(this.reportArr[i].loadingPoint.reportingDateTime).format('llll') : '--',
        'loadingexitDateTime':this.reportArr[i].loadingPoint.exitDateTime?  moment(this.reportArr[i].loadingPoint.exitDateTime).format('llll') : '--',
        'destinationreportingDateTime':this.reportArr[i].destination.reportingDateTime?  moment(this.reportArr[i].destination.reportingDateTime).format('llll') : '--',
        'destinationexitDateTime':this.reportArr[i].destination.exitDateTime?  moment(this.reportArr[i].destination.exitDateTime).format('llll') : '--',
        'distanceTravelled':this.reportArr[i].distanceTravelled,
        'tripTimetotal':this.reportArr[i].tripTime.total?this.secondsToHms(this.reportArr[i].tripTime.total):'N/A',
        'tripTimerunning':this.reportArr[i].tripTime.running?this.secondsToHms(this.reportArr[i].tripTime.running):'N/A',
        'tripTimestoppage':this.reportArr[i].tripTime.stoppage?this.secondsToHms(this.reportArr[i].tripTime.stoppage):'N/A',
        'idleTime':'',
        'status':this.reportArr[i].status
      })
  }
    this.downloadFile(array);
  }

  downloadFile(data, filename = 'Loading Unloading Group') {
   console.log(data);
   
    let arrHeader = ['vrn','Sourcegeoname','Destinationgeoname','loadingreportingDateTime','loadingexitDateTime','destinationreportingDateTime','destinationexitDateTime','distanceTravelled','tripTimetotal','tripTimerunning','tripTimestoppage','idleTime','status'];
    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", "Loading Unloading.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;
    
    let str ='Loading Unloading \r\n'
   let row = 'S.No,';

    let newHeaders =['Vehicle Name','Trip Start','Trip End','Loading Start','Loading Exit','Unloading Start','Unloading Exit','Distance','Duration','Running Time','Stoppage Time','Idle Time','Status'];

    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.reportArr);

    
    
  }

downloadGroupPdf() {
    let fileName =
      "Loading Unloading Trip" +
      new Date().getTime() +
      PDF_EXTENSION;
    var pdfsize = "a2";

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

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

    doc.autoTable({
      head: this.headRows(),
      // margin: { top: 80 },
      body: this.bodyRows(this.reportArr.length, this.reportArr),
      options
      
    });
    doc.save(fileName);
  }
  headRows() {
var row
    if(this.detector === 'group'){
     row=[
      {
        "Vehicle Name":'Vehicle Name',
        Source:'Trip Start Geofence',
        Destination:'Trip End Geofence',
        distanceTravelled:'Distance',
        running:'Running',
         stoppage:'Stop',
          idle:'Idle',
          utilization:'Utilization %',
          efficiency:'Efficiency %',
        tripCount:"No. of trips"
      
      }
    ];
     
     
      
    }
    if(this.detector === 'detail'){
    
      row=[
      {
        vrn:'Vehicle Name',
        Source:'Trip Start Geofence',
        Destination:'Trip End Geofence',
        distanceTravelled:'Distance',
        running:'Running',
         stoppage:'Stop',
          idle:'Idle',
          utilization:'Utilization %',
          efficiency:'Efficiency %',
        tripCount:"No. of trips"
      
      }
    ];
      
    }
    return row
  }

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

    rowCount = rowCount || 10;
    let body = [];
    for (var j = 0; j < rowCount; j++) {
      body.push({
       "Vehicle Name":pdfBody[j]["Vehicle Name"],
       Source:pdfBody[j].Source,
       Destination:pdfBody[j].Destination,
       distanceTravelled:pdfBody[j].distanceTravelled,
       running:pdfBody[j].running,
       stoppage:pdfBody[j].stoppage,
       idle:pdfBody[j].idle,
        utilization:pdfBody[j].utilization,
         efficiency:pdfBody[j].efficiency,
         tripCount:pdfBody[j].tripCount,
      
      });
    }
    return body;
  }





}
// {
//             "data": "vrn",
//             "defaultContent": "",
//             "render": function (data, type, row) {       
           
//               return data ? data : "";   
//             }
//           },
//           {
//             "data": "Source",
//             "defaultContent": "",
//             "render": function (data, type, row) {       
           
//               return data ? data.geoname : "";   
//             }
//           },
//           {
//             "data": "Destination",
//             "defaultContent": "",
//             render: function (data, type, row) {
//               return data ? data.geoname : '';
//             }
//           },
//           {
//             "data": "loadingPoint",
//             "defaultContent": "",
//             render: function (data, type, row) {    
//             return data ? moment(data.reportingDateTime).format('llll') : "--";
//             }
//           },
//           {
//             "data": "loadingPoint",
//             "defaultContent": "",
//             render: function (data, type, row) {   
//               return data ? moment(data.exitDateTime).format('llll') : '--';
//             }
//           },
//           //-------------UNLOADING NEW------------
//           {
//              "data": "destination",
//             "defaultContent": "",
//             render: function (data, type, row) {   
//               return data.reportingDateTime ? moment(data.reportingDateTime).format('llll') : '--';
//             }
//           },
//           {
//              "data": "destination",
//             "defaultContent": "",
//             render: function (data, type, row) {   
//               return data.exitDateTime ? moment(data.exitDateTime).format('llll') : '--';
//             }
//           },
//           // <!-- startSiteEnterAt - Loading Start
//           //           startSiteExitAt - Loading Exit
//           //           endSitEnterAt - Unloading Start
//           //           endSiteExitAt - Unloading Exit -->
//           {
//             "data": "distanceTravelled",
//             "defaultContent": "",
//             render: function (data, type, row) {
//               return data ? parseFloat(data).toFixed(2) : 0.0;
//             }
//           },
//           {
//             "data": "tripTime",
//             "defaultContent": "",
//             render: function (data, type, row) {
//               return data ? that.secondsToHms(data.total) : "0:0";
//             }
//           },
//           {
//             "data": "tripTime",
//             "defaultContent": "",
//             render: function (data, type, row) {
//               that.secondsToHms(data.running);
//               return data ? that.secondsToHms(data.running) : '0:0';
//             }
//           },
//           {
//             "data": "tripTime",
//             "defaultContent": "",
//             render: function (data, type, row) {
//               return data ? that.secondsToHms(data.stoppage) :'0:0';
//             }
//           },
//           {
//             "data": "tripTime",
//             "defaultContent": "",
//             render: function (data, type, row) {
//               return  '--';
//             }
//           }
//           ,
//           {
//             "data": "status",
//             "defaultContent": "",
//             render: function (data, type, row) {
//               return  data;
//             }
//           }