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 * as moment from 'moment';

declare var google: any;
declare var jsPDF : any;
declare var $: any;
const PDF_EXTENSION = ".pdf"
import { ReportService } from '../../report.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

declare var google: any;




@Component({
  selector: 'app-geofancing-report',
  templateUrl: './geofancing-report.component.html',
  styleUrls: ['./geofancing-report.component.scss']
})
export class GeofancingReportComponent implements OnInit {
  date1:any;
  finalArr=[]
  finall:any;
  identifier:any= 'geofence_report';
  options= [];
  logo:any;
  Fromdate:any;
  todate:any;
  userName:any;
  before:any;
  deviceArr: any=[];

private finalise = new Subject<void>();
  constructor(private contactService: ContactService,private _service:ReportService,private router: Router,public dialog: MdDialog) {
    this._service.invokeEventForgeofenceReport.pipe(
      takeUntil(this.finalise)
    ).subscribe(value => {
        if(value){
         this.getReport(value); 
       }
     
      
      }); 
   }
 ngOnDestroy(){
    
    this.finalise.next(void 0);
  }
  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;
geo_status=[];
superAdmin:Boolean = false;
  ngOnInit() {
    // var fTime = new Date().setHours(0,0,0);
    // this.Fromdate = new Date(fTime);
    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();
  
   
  }

  // openNav() {
  //   /*  document.getElementById("myNav").style.width = "100%";
  // */
  //    this.router.navigateByUrl("location");
  
  // }


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

  // myaccount(){
   
  //   let dialogRef = this.dialog.open(MyaccountComponent, {
  //     width: '903px',
  //     data: {}
  //   });
  
  //   dialogRef.afterClosed().subscribe(result => {
  
  //     if(result == "succ"){
  // //console.log("Updated")
  //     }
  
  //   });
  // }
  // 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 ++;
  //  }
  
    
  // }

  // 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");
  // }
  
  // route_map(){
  //   this.router.navigateByUrl("routeMapping");

  // }
  // Ddetail(){
  //   this.router.navigateByUrl("driverdetail");
  // }
  // DModel(){
  //   this.router.navigateByUrl("deviceModel");
  // }
  // VType(){
  //   this.router.navigateByUrl("VehicleType");
  // }
  
  
  // routeViolation(){
  //   this.cond = false
  //   this.router.navigateByUrl("device-report/routeViolation");
  
  // }


  // notification(){
  //   this.cond = false
  //   this.router.navigateByUrl("notifications");
  // }
  
  // stoppage_report(){
  //   this.cond = false
  //   this.router.navigateByUrl("device-report/stoppage_report");
  
  // }
  // group(){
  //   this.cond = false
  //   this.router.navigateByUrl("group_view");
  // }
  // addcus(){
  //   this.router.navigateByUrl("add");
  // }
  // report(){
  //   this.cond = false
  //   this.router.navigateByUrl("device-report");
  
  // }
  // report_speed(){
  //   //console.log("report speed call")
  //   this.cond = false
  //   this.router.navigateByUrl("device-report/device-speed-report");
  // }

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

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


  // }

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


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

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

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

  // }

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


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

  // geofancingReport(){
  //   this.cond = false
  //   this.router.navigateByUrl("device-report/geofancing");
  // }
  
 
  geofence=[];
  show_time:any;
  geofence_data=[];
  address_show:any;
 
  
//   geofancing_Report(fd,td,devop){
//     //console.log(devop);//console.log(fd);//console.log(td);//console.log(devop);
//     let f_date = fd.toISOString();
//     let t_date = td.toISOString();
//     //console.log(f_date);//console.log(t_date);
//     let uId = this.useridd;
//     //console.log(uId);
//     let geoId  = devop._id;
// //console.log(geoId);
//      var outerThis = this;
//      this.Load = true; 
//     this.contactService.geofenceData(f_date,t_date,uId,geoId)
//         .subscribe(res=>{
//           this.Load = false; 
//     //console.log(res);
//           this.geofence = res;
//     console.log("this.geofence=>",this.geofence);   
//         },err=>{
//           this.Load = false; 
//           console.log('Error While fetching data');
//         })
//   }
tabelObj:any;
testTable() {
  const that = this;
 
  console.log("inside function");
  $(document).ready(function() {
     that.tabelObj = $('#deviceTable').DataTable({
      // dom: 'Bfrtip',
      // buttons: [
      //     'copy', 'csv', 'excel', 'pdf', 'print'
      // ]  ,
          "processing": true,
          "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;    
              // dataTablesParameters.find._u = that.useridd;
            
              // dataTablesParameters.find._u = user;

              // if(that.deviceArr.length != 0){
         
                // dataTablesParameters.find.vname = deviceId;
              // }
            // if (that.Fromdate) {
                // var fdate = new Date(that.Fromdate).toISOString()      
                // dataTablesParameters.find.f_date = fdate    
                // dataTablesParameters.find.f_date =  from_date;    
            // };

            // if (that.todate) {
              // var fdate = new Date(that.todate).toISOString()      
              // dataTablesParameters.find.t_date = fdate     
                // dataTablesParameters.find.t_date = to_date  ;
          // };
          // this.deviceArr = deviceId; 

          var tempfd = new Date().setHours(0,0,0,0);
          var tf = new Date(tempfd);
          var temptd = new Date();
         
            var from_date = that.Fromdate?that.Fromdate:tf.toISOString();
            var to_date = that.todate?that.todate:temptd.toISOString();
            var user = that.useridd;
            var temp = {
            from_date : from_date,
            to_date : to_date,
            user : user
            }
            var suburl = "";
            suburl += "/notifs/GeoFencingReport?from_date=" + temp.from_date +'&to_date=' + temp.to_date + '&_u=' + temp.user;
            that.finalArr=[]
            // console.log(this.deviceArr);
            if(that.deviceArr.length != 0){  
              suburl +='&geoid='+that.deviceArr[0];
            }else{
            
              let resp =[];

              callback({data : resp });
            }
            if(temp.from_date && temp.to_date && that.deviceArr.length != 0){
            that.contactService.get(suburl).subscribe((resp:any) => {   
                // console.log(ignReport.length);   
                that.Load= false;   
                that.finalArr=resp 
                console.log('respresp=>',resp);      
                callback({data : resp });
            }, err => {   
              that.Load= false;    
              console.log("error",err) ;     
            });
          }else{
            that.Load= false;       
                callback({data : [] });
          }
        },  
      
          "columns": [
              {
                  "data": "vehicleName",
                  "render": function(data, type, row) {
                      
                    return data?data : '';                  
                  }
              },
              {
                  "data": "direction",
                  render: function(data, type, row) {
                    return data?data:'';        
                  }
              },
              {
                  "data": "timestamp",
                  render: function(data, type, row) {
                    var cDate = new Date(data);
                    return data ? (moment(cDate).format('llll')) : "";         
                  }
              },   
            {
              "data": "address",
              "defaultContent": "_id",
              render: function(data, type, row) { 
                  let lat = row.lat;
                  let long = row.long;           
                  var addressLink = '<a href="https://maps.google.com/?q='+ lat +','+long +' "  target="_blank" title="Click to get vehicle last location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>';          
                  return data?data : addressLink;     
       
              }
          }  ,
          {
            "data": "geoid",
            render: function(data, type, row) { 
              
                return data?data.geoname : '';     
     
            }
        }                         
          ],  
          "columnDefs": [
            { className: "dt-body-left", "targets": [ 0,1,2,3,4 ] },
            {
              "targets": '_all',
              "createdCell": function (td, cellData, rowData, row, col) {
                  $(td).css('padding', '18px')
              }
          },
          { "width": "20%", "targets": 0 },
          { "width": "10%", "targets": 1 },
          { "width": "20%", "targets": 2 },
          { "width": "30%", "targets": 3 },  
          { "width": "20%", "targets": 4 },      
         
          ] 
      });

  });

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


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

  getReport(event){
    if(event == 'getExcel'){
      this.exportExcel();
     } 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.toISOString();
      this.todate = td.toISOString();
    
     
      console.log(this.tabelObj);
      this.tabelObj.ajax.reload();      
        
    
    
    }
   
  }
  expotToPdf(){
    console.log(this.finalArr);

    this.downloadPdf()
    
  }

// downloadPdf() {
//     let fileName =
//       "Geofencing Report" +
//       new Date().getTime() +
//       PDF_EXTENSION;
//     var pdfsize = "a2";

//     var doc = new jsPDF("p", "pt", pdfsize);
  
//   doc.setFontSize(15);
//   doc.text('Geofencing Report ', 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.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'];

      {
        vehicleName:'Vehicle Name',
        direction:'In/Out',
        timestamp:'Date Time',
        location:'Location',
        geoname:'Geofence Name',
        
      
      }
    ];
  }

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

    rowCount = rowCount || 10;
    let body = [];
    for (var j = 0; j < rowCount; j++) {
      body.push({
       vehicleName:pdfBody[j].vehicleName,
       direction:pdfBody[j].direction,
       timestamp: moment(pdfBody[j].timestamp).format('lll'),
       location:[pdfBody[j].lat,pdfBody[j].long],
       geoname:pdfBody[j].geoid.geoname?pdfBody[j].geoid.geoname:'--',
      
      });
    }
    return body;
  }



}

