import { Component, OnInit } from '@angular/core';
import { ContactService } from '../../../contact.service';
import * as moment from 'moment';
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';
@Component({
  selector: 'app-poi-report',
  templateUrl: './poi-report.component.html',
  styleUrls: ['./poi-report.component.scss']
})
export class POIReportComponent implements OnInit {
 finalArr=[]
  option: any;
  Fromdate = new Date();
  todate = new Date();
  emailid: any;
  identifier = 'poi_report';
  useridd: any;
  tabelObj: any ;
  deviceName:any;
  routeName:any;
  private finalise = new Subject<void>();
  constructor(public contactService: ContactService,private _service:ReportService) { 
      this._service.invokeEventForpoiReport.pipe(
      takeUntil(this.finalise)
    ).subscribe(value => {
        if(value){
         this.getReport(value); 
       }
      }); 
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
  }
 ngOnDestroy(){
   
    this.finalise.next(void 0);
  }
  ngOnInit() {
    this.Fromdate.setHours(0, 0, 0);
    this.testTable();
   
  }

 

testTable() {
    const that = this;
    // console.log("selectedRoute=>",this.routeSelect);
    $(document).ready(function() {
        that.tabelObj = $('#deviceTable').DataTable({
            serverSide: true,
            "processing": true,
            "searching": false,
            "pageLength": 25,
            "scrollY":'65vh',  
            "scrollCollapse": true,   
            ajax: (dataTablesParameters: any, callback) => {

                dataTablesParameters.op = {};
                dataTablesParameters.select = [];
                dataTablesParameters.find = {};
                // console.log(dataTablesParameters);
                // console.log("callback", callback);

                // dataTablesParameters.find = {
                //   _id: that.useridd         
                // };
                dataTablesParameters.columns = [
                    { data: "_id" },
                    { data: "device.Device_Name" },
                    { data: "device.Device_ID" },
                    { data: "address" },
                    { data: "arrivalTime" },
                    { data: "departureTime" },
                    { data: "poi.poi.poiname" },
                  ]
                //   console.log("selectedRoute=>",that.routeSelect);
                //   console.log("VehicleID",that.deviceSelect);

                // ==========================================
                if (that.Fromdate) {
                    var arrGtObj = { "arrivalTime": { "$gte": that.Fromdate } }
                    var depGtObj = { "departureTime": { "$gte": that.Fromdate } }
                }

                if (that.todate) {
                    var arrLtObj = { "arrivalTime": { "$lte": that.todate } }
                    var depLtObj = { "departureTime": { "$lte": that.todate } }
                }

                if (arrGtObj || arrLtObj) {
                    var arrAndObj1 = { "$and": [] }
                    if (arrGtObj)
                        arrAndObj1["$and"].push(arrGtObj);
                    if (arrLtObj)
                        arrAndObj1["$and"].push(arrLtObj);
                }

                if (depGtObj || depLtObj) {
                    var arrAndObj2 = { "$and": [] }
                    if (depGtObj)
                        arrAndObj2["$and"].push(depGtObj);
                    if (depLtObj)
                        arrAndObj2["$and"].push(depLtObj);
                }

                if (arrAndObj1 || arrAndObj2) {
                    var orArr = []
                    if (arrAndObj1)
                        orArr.push(arrAndObj1);
                    if (arrAndObj2)
                        orArr.push(arrAndObj2);
                }
                var finalObj = { "$or": orArr};
           
                dataTablesParameters.find = finalObj;
              
                if (that.deviceObj.length != 0){
                    // console.log(that.deviceSelect);
                    dataTablesParameters.find.device = that.deviceObj[0];        
                }

                if (that.poi_id.length != 0) {
                    
                    // console.log("routeId=>",that.routeSelect[0].id);              
                    dataTablesParameters.find.poi = that.poi_id[0];        
                }

                dataTablesParameters.find.user = that.useridd;

                that.finalArr=[]
                var suburl = "";
                suburl += "/poi/datatable";
                // console.log(suburl);
                // console.log(dataTablesParameters);
                // console.log(suburl)
                if(that.Fromdate && that.todate){
                    that.contactService.post(suburl, dataTablesParameters).subscribe((resp:any) => {
                        console.log("poiResp",resp);
                        that.finalArr=resp
                        callback(resp);
                    }, err => {           
                        // console.log(err.status);
                    });
                }else{
                     callback([]);
                }
            },
            "columns": [
                {
                    "data": "device.Device_Name",
                    "defaultContent": "",
                    "render": function(data, type, row) {
                        return data ? data : "";
                    }
                },
                {
                    "data": "device.Device_ID",
                    "defaultContent": "",
                    "render": function(data, type, row) {
                        return data ? data : "";
                    }
                },
                {
                    "data": "poi.poi.poiname",
                    "defaultContent": "",
                    render: function(data, type, row) {
                        // console.log("poiData=>",data);
                        return data ? data : "";
                    }
                },
                {
                    "data": "arrivalTime",
                    "defaultContent": "",
                    render: function(data, type, row) {
                        var A_time = new Date(data);
                        return data ? (moment(A_time).format('llll')) : "";
                    }
                },
                {
                    "data": "departureTime",
                    "defaultContent": "",
                    render: function(data, type, row) {
                        var D_time = new Date(data);
                        return data ? (moment(D_time).format('llll')) : "";
                    }
                },
                {
                    "data": "address",
                    "defaultContent": "",
                    "render": function(data, type, row) {
                        var created_time = new Date(data);
                        return data?data:"";
                    }
                },             
            ],
        });

        that.tabelObj.columns().every( function () {
            var that = this;
     
            $( 'input', this.footer() ).on( 'keyup change', function () {
                if ( that.search() !== this.value ) {
                    that
                        .search( this.value )
                        .draw();
                }
            } );
        } );
       
    });

}


searchFilter(){
    // DataTable
    var table = $('#deviceTable').DataTable();
 
    // Apply the search
    table.columns().every( function () {
        var that = this;
 
        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );

}
deviceObj = [];
// getAllDevice() {
//     this.contactService.getDevice(this.emailid,this.useridd)
//         .subscribe(res => {
//             // console.log(res);
//             // console.log("allDevices=>", res);
//             this.deviceObj = [];
//             var Alldevices = {
//                 id: "all",
//                 viewValue: "ALL Devices"
//             }
//             this.deviceObj.push(Alldevices);

//             for (var i = 0; i < res.devices.length; i++) {
//                 Alldevices = {
//                     id: res.devices[i]._id,
//                     viewValue: res.devices[i].Device_Name ? res.devices[i].Device_Name : ""
//                 }

//                 this.deviceObj.push(Alldevices)
//             }
//             // console.log("deviceArray", this.deviceObj);

//         }, err => {
//             // console.log(err.status);
//         })
// }




deviceSelect: any = [];

filterDevices(dlr) {

    // console.log("deviceData=>", dlr);
    if (dlr) {
        // console.log(dlr);

        const filterdealerValue: any = dlr;

        this.deviceSelect = [];
        this.deviceSelect = this.deviceObj.filter(function(pp) {
         
            // console.log("dealerValue=>",pp);
            var t = pp.viewValue.toLocaleLowerCase().indexOf(filterdealerValue.toLocaleLowerCase());

            return t > -1;
        });
        // console.log(this.deviceSelect);
        return this.deviceSelect;
    }

}

// Routename filter 
route_detail_show=[];
poiArr=[];
// getPOI(){
//     // console.log("Mapping history !!!");
//     this.contactService.getPOI(this.useridd)
//     .subscribe(res=>{
//     //   console.log("routedet",res);
//       this.route_detail_show=res;

//       var poiObj = {
//           poiname: "All POI",
//           id : "All"
//       }
//       this.poiArr.push(poiObj);
//       for(var i=0;i<this.route_detail_show.length;i++){
//         poiObj ={
//             poiname: this.route_detail_show[i].poi.poiname,
//             id : this.route_detail_show[i]._id
//           }

//           this.poiArr.push(poiObj);
//       }

//     //   console.log("routeDetails=>",this.poiArr);
//     })
//   }
  routeSelect=[];
//   filterRoutes(route_ID){
//     //   console.log(route_ID);
//       if (route_ID) {
//         //   console.log(route_ID);
//           const filterRouteValue: any = route_ID;
  
//           this.routeSelect = [];
          
//         //   console.log("routeData=>", this.route_detail_show);
//           this.routeSelect = this.poiArr.filter(function(rte) {
//             // console.log("routeObj=>",rte);
//               var r = rte.poiname.toLocaleLowerCase().indexOf(filterRouteValue.toLocaleLowerCase());     
//               return r > -1;
//           });
//         //   console.log("filtered route=>",this.routeSelect);
//           return this.routeSelect;
//       }

//   }

  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>";
        // console.log('tab_text',JSON.parse(tab_text));
        //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);
}

  deviceArr :any=[];
  poi_id:any=[];
  getReport(event){
   if (event == 'getExcel') {
      this.exportExcel();
    } else if(event=='getPdf')
  {
    this.expotToPdf();
  }else{
        console.log(event);
      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.deviceObj = deviceId; 
      this.poi_id  = event.poi_id ;

      
      this.Fromdate = fd;
      this.todate = td;

      
      // this.tabelObj.clear();
      // var aa = [];
      // this.tabelObj.rows.add(aa);   
      this.tabelObj.draw(); 
        // this.tabelObj.ajax.reload();        
    }
   
  }

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

    this.downloadPdf()
    
  }

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

//     var doc = new jsPDF("p", "pt", pdfsize);
//   //   var f_date = moment(this.from_date).format('lll'); 
//   // var t_date =moment(this.to_date).format('lll');
//   // var date_combine = f_date + ' to ' + t_date;
//   // doc.setFontSize(30);
//   doc.setFontSize(15);
//   doc.text('POI Report ', 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 =
      "POI 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("POI 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",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'];

      {
        vehicleName:'Vehicle Name',
        Device_ID:'Device Id',
        poi:'Poi Name',
        arrivalTime:'Arrival Time',
        departureTime:'Departure Time',
        address:'Address',
        
      }
    ];
  }

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

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

       vehicleName:pdfBody[j].device.Device_Name,
       Device_ID:pdfBody[j].device.Device_ID,
       poi:pdfBody[j].poi?pdfBody[j].poi:'N/A',  
       arrivalTime:moment(new Date(pdfBody[j].arrivalTime)).format('llll'), 
       departureTime:moment(new Date(pdfBody[j].departureTime)).format('llll'),
        address:pdfBody[j].address?pdfBody[j].address:'N/A'
      });
    }
    return body;
  }

}
