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


declare var google: any;
// declare var jquery:any;
declare var $:any;
declare var moment :any;
// declare var $:any;
// declare var TableExport:any;

@Component({
  selector: 'app-summary-report',
  templateUrl: './summary-report.component.html',
  styleUrls: ['./summary-report.component.scss']
})
export class SummaryReportComponent implements OnInit {

  sumReport: any;
  date1:any;
  neww:any;
  fs : any;
  Load:boolean=false;
  ls : any;
  emailid : any;
  or : any;
  useridd :any;
  time :any;
  device_data:any;
  devicess:any;
  final:any;
  custtype:any;
  cust:boolean=false;

  date : any;
  devicesss:any;
  mb:any;
  logoutbut:boolean;
  dealer:boolean;
  text:any;
  option:any; 
  finall:any;
  Fromdate:any;
  todate:any;
  options=[];
  logo:any;
  before:any;
  superAdmin:Boolean = false;
  xlbutton: boolean= false;
  dataSelect: any[];
  closeProcess: any;
  lattitude: any;
  longitude: any;
  lattitude1: any;
  longitude1: any;
  addressLink: string;
  addressLink1: string;

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

  

  ngOnInit() {

    var fTime = new Date();
    // fTime.setDate(fTime.getDate()-1);
    // fTime.setHours(0,0,0,0); 
    // this.Fromdate=new Date(fTime);
    $('#select').hide();
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.fs = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).fn;
    this.ls = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).ln;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.or = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._orgName;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.mb =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    // $('.demo').fSelect();
  


    // 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);
    //        let that = this;
    //        setTimeout(()=>{
    //          that.loadropdown();
    //        },100)  

    //   });

      if(this.custtype == true){
        this.cust = true;
      }  
      if(this.mb.charAt(0)=="n"){
        this.mb = ' '
      }


      if( window.localStorage['Custumer'] == 'ON'){
        this.logoutbut = false
        this.dealer = true
     }
     else{
         this.logoutbut = true
     }          
     this.logo=window.localStorage['logo'];
     this.text=window.localStorage['text'];  
     this.testTable();  
  }

  selectedPeople:any;
  people= ['1','2','3',];
//   ign(){
//     this.router.navigateByUrl("device-report/ign-report");
  
//   }


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

//   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(() => {

//       $('#select').multipleSelect({
//         width: 200,
//         placeholder: 'Select device.....',
//         filter: true,
//       })
//      // $('#select').show();
//     }, 100);


//   }


//   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);
  
// }
// 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");

// }

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


// report_speed(){
//   // console.log("report speed call")
//   this.cond = false
//   this.router.navigateByUrl("device-report/device-speed-report");
// }


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

// }


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

// }

// 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");
//   }
// }



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

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


// }

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

// }

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

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

// }

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

// }

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

// }

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

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

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

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

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

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

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

  //       //   }else{

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

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

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

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


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

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


  tabelObj: any ;
  identifier:String = 'summary_report';
testTable() {
  const that = this;
  console.log("inside function");
 
  $(document).ready(function() {
 
     that.tabelObj = $('#deviceTable').DataTable({
        dom: 'lBftip',
        buttons: [
          'copy',
          'print',
          'excel'
        ],       
          "processing": false,
          "searching": true, 
          pagingType: 'full_numbers',
          pageLength: 25,
          serverSide: false,
          "scrollY":'63vh',     
          "scrollX": true,
          "scrollCollapse": true,     
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
          ajax: (dataTablesParameters,callback) => {
            var deviceID;
            that.Load= true;    
            var from_date = that.Fromdate;
            var to_date = that.todate;
            var user = that.useridd;
            var temp = {
            from_date : from_date,
            to_date : to_date,
            user : user
            }

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

            if((temp.from_date != undefined)&&(temp.to_date != undefined)){
              suburl += "/summary/summaryReport?from=" + temp.from_date +'&to=' + temp.to_date + '&user=' + temp.user;
              if(that.deviceArr.length != 0){  
                suburl +='&device='+that.deviceArr;
              }
              that.contactService.get(suburl).subscribe(resp => {   
                  // console.log(ignReport.length); 
                  that.summary =[];
                  that.Load= false;    
                  that.device_summary = [];      
                  that.summary = resp ; 
                  console.log(that.summary);
                  var hourconversion = 2.7777778 / 10000000 ; 
                  // for(var j=0;j<that.summary.length;j++){
                  //   that.device_summary.push({
                  //     "devicename": that.summary[j].devObj[0]?that.summary[j].devObj[0].Device_Name:'NA',
                  //     "TotalrunningTime":that.millisecondConversion(that.summary[j].today_running),
                  //     "stopTime": that.millisecondConversion(that.summary[j].today_stopped),
                  //     "idleTime": that.millisecondConversion(that.summary[j].t_idling),
                  //     "ourTime": that.millisecondConversion(that.summary[j].t_ofr),
                  //     "nogps" :that.millisecondConversion(that.summary[j].t_noGps),
                  //     "overSpeed": that.millisecondConversion(that.summary[j].today_overspeeds),
                  //     "routeViolation": that.summary[j].today_routeViolations,
                  //     "start_add": that.summary[j].start_location,
                  //     "end_add": that.summary[j].end_location,
                  //     "trip": that.summary[j].today_trips,
                  //     "totalkm":that.summary[j].today_odo,
                  //     "fuelConsumption" : ((that.summary[j].devObj[0].Mileage == null)||(that.summary[j].devObj[0].Mileage == undefined))?"NA":(that.summary[j].today_odo/parseFloat(that.summary[j].devObj[0].Mileage)).toFixed(2)
                   
                  //   })
                  // }  
               
                    callback({data : that.summary });    
                 
              }, err => {   
                that.Load= false;    
                console.log("error",err) ;     
              });
            }else{
              that.Load= false;    
              let ta = [];
              callback({data : ta });  

            }

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

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

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

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

                return data?that.millisecondConversion(data):0;
              }
            },
         
       
            {
              "data": "t_idling",
              "defaultContent": "",
              render: function (data, type, row) {

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

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

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

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

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

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

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

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

  });

}



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

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

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

	    tab_text=tab_text+"</table>";
	    // tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
	    // tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
	    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

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

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

	    return (sa);
  }
  

  filterStates(val) {


    if (val==""){

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

  }


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


  millisecondConversion(duration){
   
      // var  minutes = Math.floor((duration / (1000 * 60)) % 60);
      // var  hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
  
      // hours = (hours < 10) ? 0 + hours : hours;
      // minutes = (minutes < 10) ? 0 + minutes : minutes;
    
      // return hours + ":" + minutes ;
      var x = duration;
      var d = moment.duration(x, 'milliseconds');
      var hours = Math.floor(d.asHours());
      var mins = Math.floor(d.asMinutes()) - hours * 60;
      var mainMIn = (hours>=24)?0:mins;
      return  hours + ":" + mainMIn;

    
  }
  



  }



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

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

        //   }else{

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

        //   }

  




