import { Component, OnInit } from '@angular/core';
import { ReportService } from '../../report.service';
declare var jsPDF : any;
declare var $: any;
const PDF_EXTENSION = ".pdf";
declare var html2canvas:any;
declare var pdfMake :any ; 
declare var _:any;
import * as moment from 'moment';
import { ContactService } from '../../../contact.service';
import { ViewRawComponent } from './view-raw/view-raw.component';
import { MdDialog } from '@angular/material';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
  selector: 'app-push-data-report',
  templateUrl: './push-data-report.component.html',
  styleUrls: ['./push-data-report.component.scss']
})
export class PushDataReportComponent implements OnInit {
deviceArr = [];
  Fromdate: Date;
  finalArr=[];
  data_descip
  Load:boolean=false
  todate: Date;
  tabelObj: any;
  useridd: any;
  private finalise = new Subject<void>();
  constructor(private reportService:ReportService,private contactService:ContactService,public dialog: MdDialog) { 
    this.reportService.invokeEventForDataPushReport.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.testTable()
  }

  getReport(event){
  
  console.log("inside function");
    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;
    this.todate = td;
     this.tabelObj.ajax.reload();   
  }
 
}

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,
          "scrollY":'65vh',  
          "scrollCollapse": true,     
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
          "rowCallback": function(row: Node, data: any | Object, index: number){
             $('#raw', row).bind('click', () => {  
              if(that.dialog.openDialogs && that.dialog.openDialogs.length > 0){
      return false;
    }
    let dialogRef = that.dialog.open(ViewRawComponent, {
//  width: '503px',
//  height:'400px',
    data: data.raw?data.raw:{}
 });
 dialogRef.afterClosed().subscribe((result) => {
      dialogRef = null;
     
      //add code to perform any other actions on pop-up close.
    });
    
                     
            });
          },
          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 = "";
            that.finalArr=[]
            
            if((temp.from_date != undefined)&&(temp.to_date != undefined)){
              suburl += "/pullData/getPushData?from_date=" + new Date(temp.from_date).toISOString() +'&to_date=' + new Date(temp.to_date).toISOString() + '&_u=' + temp.user;
              if(that.deviceArr.length != 0){  
                suburl +='&device='+that.deviceArr;
              }
              that.contactService.get(suburl).subscribe((resp:any) => {   
                // console.log(ignReport.length);  
                that.finalArr=resp;
                for(var i=0;i<resp.length;i++){
                  resp[i].last_device_time=resp[i].last_device_time?resp[i].last_device_time:'N/A'
                  console.log(typeof(resp[i].response));
                  
                  if(typeof(resp[i].response)=="object"){
                    resp[i].response=JSON.stringify(resp[i].response)
                  }
                }
                // that.getWorkingHour(resp);
                that.Load = false;
                callback({data : resp });
            }, err => {   
              that.Load= false;    
              console.log("error",err) ;     
            });

            }else{
              let ta = [];
              that.Load = false;
              callback({data : ta });
            }
          
        },  
      
          "columns": [
              {
                  "data": "vehicleNo",
                  "defaultContent": "",
                  "render": function(data, type, row) {
                      
                    return data?data : '';                  
                  }
              },
              {
                  "data": "Unit",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    return data?data:'';        
                  }
              },
              {
                  "data": "DATE",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    var expDate = new Date(data);
                    return data ? (moment(expDate).format('D MMM YYYY, h:mm:ss a')) : "";  
                
                  }
              },
               {
                  "data": "last_device_time",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    // return data ? data : "";  
                     var expDate = new Date(data);
                    return data ? (moment(expDate).format('D MMM YYYY, h:mm:ss a')) : "";  
                
                  }
              },
              {
                  "data": "DeviceCompanyId",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    return data ? data : "";  
                
                  }
              },
              
              {
                  "data": "Latitude",
                  "defaultContent": "",
                  render: function(data, type, row) {
                   var lat=row.Latitude?row.Latitude:0
                   var long=row.Longitude?row.Longitude:0       
                   return lat+', '+long;  
                
                  }
              },
              {
                  "data": "gmt",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    var expDate = new Date(data);
                    return data ? (moment(expDate).format('D MMM YYYY, h:mm:ss a')) : "";
                    // return data ? data : "";  
                
                  }
              },
              {
                  "data": "gps_datetime",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    var expDate = new Date(data);
                    return data ? (moment(expDate).format('D MMM YYYY, h:mm:ss a')) : "";
                
                  }
              },
              
              {
                  "data": "response",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    return data ? data : "";  
                
                  }
              }, 
              {
                  "data": null,
                  "defaultContent": "",
                  render: function(data, type, row) {
                   return `<button class="btn btn=info btn-sm"><i id="raw"  style="font-size:20px;color: green" class="fas fa-info"></i></button> `
                
                  }
              },
        
              
          //   {
          //     "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>';            
          //         if(data){
          //           return data ;
          //         }else{
          //           return addressLink;     
          //         }
          //     }
          // }                       
          ],  
          "columnDefs": [
            { className: "dt-body-left", "targets": [ 0,1,2,3,4,5,6,7,8,9] },
            {
              "targets": '_all',
              "createdCell": function (td, cellData, rowData, row, col) {
                  $(td).css('padding', '18px')
              }
          } ,
          { "width": "30px", "targets": 0 },
          { "width": "30px", "targets": 1 },
          { "width": "30px", "targets": 2 },
          { "width": "30px", "targets": 3 },
           { "width": "30px", "targets": 4 },
           { "width": "30px", "targets": 5 },
            { "width": "30px", "targets": 6 },
            { "width": "30px", "targets": 7 },
            { "width": "30px", "targets": 8 },
            { "width": "30px", "targets": 9 },
       
          ] 
      });

  });

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


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

    this.downloadPdf()
    
  }
// downloadPdf() {
//     let fileName =
//       "Push Data 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('Push Data ', 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 =
      "Data Push 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("Data Push 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'},
      // tableLineColor: [0, 0, 0], //choose RGB
        // tableLineWidth: 0.5, //table border width
        // bodyStyles: {
        //     margin: 40,
        //     fontSize: 10,
        //     lineWidth: 0.2,
        //     lineColor: [0, 0, 0]
        // },
      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",margin:{bottom:140,left:20,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'];

      {
        vehicleNo:'Vehicle',
        Unit:'IMEI',
        DeviceCompanyId:'Integration ID',
        last_device_time:"Last Device Time",
        DATE:'Date Time',
        Latitude:'Latitude',
        Longitude:'Longitude',
        gmt:"GMT",
        gps_datetime:"GPS DATE",
        response:'Response',
        
      }
    ];
  }

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

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

       vehicleNo:pdfBody[j].vehicleNo,
        Unit:pdfBody[j].Unit,
        DeviceCompanyId:pdfBody[j].DeviceCompanyId,
        last_device_time:pdfBody[j].last_device_time?(moment(pdfBody[j].last_device_time).format('D MMM YYYY, h:mm:ss a')):'N/A',
        DATE:pdfBody[j].DATE?(moment(pdfBody[j].DATE).format('D MMM YYYY, h:mm:ss a')):'N/A',
        Latitude:pdfBody[j].Latitude,
        Longitude:pdfBody[j].Longitude,
        gmt:pdfBody[j].gmt?pdfBody[j].gmt:'',
        gps_datetime:pdfBody[j].gps_datetime?pdfBody[j].gps_datetime:'',
        response:pdfBody[j].response?pdfBody[j].response:'N/A'
      

      });
    }
    return body;
  }

}
