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



declare var google: any;
declare var $: any;
import * as moment from 'moment';
import { PlayTripComponent } from '../../play-trip/play-trip.component';

@Component({
  selector: 'app-trip-report',
  templateUrl: './trip-report.component.html',
  styleUrls: ['./trip-report.component.scss']
})
export class TripReportComponent implements OnInit {
  dataSelect: any[];
  addressLink1: string;

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

  date1:any;
  neww:any;
  fs : any;
  ls : any;
  emailid : any;
  or : any;
  useridd :any;
  time :any;
  device_data:any;
  devicess:any;
  identifier : String = "trip_report";
  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;
  superAdmin:Boolean = false;
  ngOnInit() {
  
    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();
       
  }

  
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;
devId:any;

Durations:any;
deviceArr: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; 
    this.Fromdate = fd;
    this.todate = td;
 
  
   
    this.tabelObj.ajax.reload();      
   

  }
    


}


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

  // console.log(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;
  }

}

addressLink = "";
getlink(report : any){
 
  // console.log("report=>",report);
  var lat = report.start_lat?report.start_lat:0;
  var lng = report.start_long?report.start_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_lat?report.end_lat:0;
  var lng = report.end_long?report.end_long:0;
  this.addressLink1 =  'https://maps.google.com/?q=' + lat + ',' + lng;
  return this.addressLink ; 
}

tabelObj: any ;
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":'65vh',  
          "scrollCollapse": true,     
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
          ajax: (dataTablesParameters,callback) => {
            console.log('temptemptemptemptemp',dataTablesParameters);
              var deviceID;
              that.Load = true
              console.log('that.deviceArr',that.deviceArr);    
            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 = "";
            if((temp.from_date != undefined)&&(temp.to_date != undefined)){        
              suburl += "/user_trip/trip_detail?from_date=" + temp.from_date +'&to_date=' + temp.to_date + '&uId=' + temp.user;
              if(that.deviceArr.length != 0){  
                suburl +='&device='+that.deviceArr;
              }
              that.contactService.get(suburl).subscribe(resp => {   
              
                 that.Load = false ;
                  callback({data : resp });
              }, err => {   
                that.Load= false;    
                console.log("error",err) ;     
              });

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

            }

       
        },  
        "rowCallback": function(row: Node, data: any | Object, index: number){  
          $('#playTrip', row).bind('click', () => {  
            console.log(data);
            var fd = new Date(data.start_time).toISOString();
            var td = new Date(data.end_time).toISOString();
              var replayObj= {
                fromdate:fd,
                todate : td,
                user : that.useridd,
                device:{imei: data.device.Device_ID,_id: data.device._id,iconType:data.device.iconType},
                distance: (typeof data.distance === 'number')?(parseFloat(data.distance).toFixed(2)):0
                
              }

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

      
          "columns": [
              {
                  "data": "device",
                  "render": function(data, type, row) {    
                    console.log(data);
                    return data?data.Device_Name : '';                  
                  }
              },
              {
                  "data": "start_time",
                  render: function(data, type, row) {
                    var st = new Date(data);
                    return data ? (moment(st).format('llll')) : "";  
                    
                  }
              },
              {
                  "data": "startAddress",
                  "defaultContent": "_id",
                  render: function(data, type, row) {
                    var lat = row.start_lat?row.start_lat:0;
                    var long = row.start_long?row.start_long:0;   
                    var addressLink_start = '<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 data?data : addressLink_start;  
                
                  }
              },        
            {
              "data": "end_time",
              render: function(data, type, row) { 
                var et = new Date(data);
                return data ? (moment(et).format('llll')) : "";     
              }
          }  ,
          {
            "data": "endAddress",
            "defaultContent": "_id",
            render: function(data, type, row) { 
              var lat = row.end_lat?row.end_lat:0;
              var long = row.end_long?row.end_long:0;
              var addressLink_end = '<a href="https://maps.google.com/?q='+ lat +','+long +' "  target="_blank" title="Click to get vehicle End location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>';      
              return data?data : addressLink_end;  
           
            }
        },
        {
          "data": "distance",
          render: function(data, type, row) {    
          return data?(data/1000).toFixed(2):'';
          }
      }      ,
      {
        "data": "null",
        "defaultContent": "",
        render: function(data, type, row) {    
        return '<i id="playTrip" class="fas fa-play" title="Trip replay" style="color:green;cursor :pointer"></i>';
        }
    }      
          ],  
          "columnDefs": [
            { className: "dt-body-left", "targets": [ 0,1,2,3,4,5 ] },
            {
              "targets": '_all',
              "createdCell": function (td, cellData, rowData, row, col) {
                  $(td).css('padding', '18px')
              }
          }   ,
       

          { "width": "15%", "targets": 0 },
             { "width": "20%", "targets": 1 },
          { "width": "20%", "targets": 3 },
         
          ] 
      });

  });

}


}
