import { Component, OnInit } from '@angular/core';
import { ContactService } from '../../../contact.service';
import { MdDialog, MdSnackBar } from '@angular/material';
import { BsDatepickerConfig } from 'ngx-bootstrap';
declare var jsPDF : any;
declare var $: any;
const PDF_EXTENSION = ".pdf";import * as moment from 'moment';
import { ReportService } from '../../report.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-idle-report',
  templateUrl: './idle-report.component.html',
  styleUrls: ['./idle-report.component.scss']
})
export class IdleReportComponent implements OnInit {
  options: any=[];
  devicesss: any;
  superAdmin: any;
  supAdmin: any;
  fs: any;
  minIdleTime:any= 5;
  identifier:any='idle_report';
  ls: any;
  emailid: any;
  or: any;
  useridd: any;
  mb: any;
  custtype: any;
  Dealer: any;
  finalArr=[]
  finall: any;
  from_date=new Date();
  to_date=new Date();
  colorTheme = 'theme-dark-blue';
  bsConfig: Partial<BsDatepickerConfig>;
  private finalise = new Subject<void>();
  constructor(private contactService: ContactService,private _service:ReportService , public dialog: MdDialog, public snackBar: MdSnackBar) { 
    this._service.invokeEventForidleReport.pipe(
      takeUntil(this.finalise)
    ).subscribe(value => {
        if(value){
         this.getReport(value); 
       }
      console.log(value);
      
      }); 
    // this.bsConfig = Object.assign({ dateInputFormat: 'MMMM Do YYYY, h:mm:ss a' }, { containerClass: this.colorTheme });
    // this.from_date.setHours(0,0,0,0); 
  $('#select').hide();
    console.log("loginDetails=>",JSON.parse(window.atob(window.localStorage.token.split(".")[1])));
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.supAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).supAdmin;
    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;
    this.Dealer = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).Dealer;

  }
ngOnDestroy(){
    this.finalise.next(void 0);
  }
  ngOnInit() {
    // this.getDevices();
    this.testTable();
  }

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

  //     });
  
  //   }


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

    tabelObj: any;
    Load : boolean=false;
    vCount = 0;
    deviceArr:any=[];
    callfunction(): void {
      // this.Load = true;
      this.deviceArr =  $('#select').multipleSelect('getSelects','value');
      this.tabelObj.draw();
    }
    dtOptions:any={};
    repCount = 0 ;
    testTable() {
      const that = this;
      console.log("inside function");
      // this.Load = true;
      that.finalArr = [];
      $(document).ready(function() {
          that.tabelObj = $('#deviceTable').DataTable({
            dom: 'lBftip',
            buttons: [
              'copy',
              'print',
              'excel'
            ],       
              "processing": true,
              "searching": false,
              pagingType: 'full_numbers',
              pageLength: 25,
              serverSide: true,
              "scrollY":'65vh',
              "scrollCollapse": true,     
              lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
              ajax: (dataTablesParameters: any, callback) => {
               
                  dataTablesParameters.op = {};
                  dataTablesParameters.select = [];
                  dataTablesParameters.find = {};   
                  dataTablesParameters.columns = [
                    // {data: "_id" },
                    {data: '_id'},
                    {data: 'device'},
                    {data: 'device.Device_Name'},
                    {data : 'start_time'},
                    {data : 'end_time'},
                    {data : 'lat'},           
                    {data: 'long'},
                    {data :'ac_status'},       
                    {data :'idle_time'},             
                    {data : 'address'},
                    {data: null, defaultContent: ''}
                  ]  

              
                 
                 if(that.repCount != 0){
              
                  console.log(that.repCount);
                  // dataTablesParameters.find.user = that.useridd;
                  if(that.deviceArr.length != 0){
                    console.log('that.deviceArr',that.deviceArr);
                    var dev_in = {'$in': that.deviceArr};
                       dataTablesParameters.find.device = dev_in;
                       if (that.from_date) {
                        var fdate = new Date(that.from_date).toISOString()  
                       
                        dataTablesParameters.find.start_time = {$gte: fdate}        
                    };
                    if (that.to_date) {
                      var tdate = new Date(that.to_date).toISOString()        
                      dataTablesParameters.find.end_time = {$lte: tdate}        
                  };

                  // that.minIdleTime =
                  that.Load = true; 
                  dataTablesParameters.find.idle_time   = {$gte : that.minIdleTime * 60000};
                  var suburl = "";
                  suburl += "/stoppage/idleReportdatatable";
                  that.contactService.post(suburl, dataTablesParameters).subscribe((resp:any) => {
                   
                      console.log("Response from datatable=>",resp);     
                      that.Load= false;  
                       callback({data : resp});
                      // if(resp.length>0){
                      //   that.finalArr=resp       
                      //   callback({data : resp});
                      // }else{
                      //   that.finalArr=[]       
                      //   callback({data : [] });

                      // }
                  }, err => {  
                    callback({data : [] });
                    that.Load= false;    
                    let message1="Server Error, Please try again ";
                    let action:any;
                    that.snackBar.open(message1, action, {
                      duration: 5000,
                      
                    });  
                    console.log("error",err) ;     
                  });
                  }else{
                    that.Load= false;    
                    let message1="Please Select Device";
                    let action:any;
                    that.snackBar.open(message1, action, {
                      duration: 5000,
                      
                    });  
                    return;
                  }
                 }else{
                  that.repCount =  that.repCount + 1 ; 
                  that.Load= false;    
                 }
                                            
           
              },  
              "columns": [
                  {
                      "data": "device",
                      "visible" :true,
                      "render": function(data, type, row) {
                      
                       return data.Device_Name?data.Device_Name:"";
                          
                      }
                  },
                  {
                      "data": "start_time",
                      "visible" :true,
                      render: function(data, type, row) {
                        var Start_time ;
                        if(data !=null){
                          var ft= new Date(data);
                         Start_time = moment(ft).format('llll');

                          
                        }else{
                          Start_time = 'NA';

                        }
                        
                        // return data ? (moment(created_time).format('llll')) : "";
                          return Start_time;
                        
                    
                      }
                  },
                  {
                      "data": "end_time",
                      "visible" :true,
                      render: function(data, type, row) {
                        var end_time ;
                        if(data !=null){
                          var ft= new Date(data);
                         end_time = moment(ft).format('llll');

                          
                        }else{
                          end_time = 'NA';

                        }
                        
                    
                          return end_time;
                      }
                  }, 
                  {
                    "data": "idle_time",
                    "visible" : true,
                    render: function(data, type, row) {  
                      var duration;
                      // if((row.start_time == undefined)||(row.end_time == undefined)){
                      //   duration = 'NA'
                      // }else{

                      //   var stime = new Date(row.start_time);
                      //   var etime = new Date(row.end_time);
                      //   var tdiff = etime.getTime() - stime.getTime()
                      

                      // }
                      if((data != null)||(data!=undefined)){
                        duration = that.millisecondConversion(data);
                      }else{
                        duration = "0:0";
                      }
                    
                      // that.millisecondConversion(2000);
                        return duration;
                    }
                },    
         
                  {
                    "data": "long",
                    "visible" :true,
                    render: function(data, type, row) {
                    
                      var lattitude;
                      var longitude;
                      if((row.lat == undefined)||(row.long == undefined)||(row.lat == null)||(row.long == null)){
                          lattitude = 0;
                          longitude = 0;
                          var addressLink = 'NA';
                      }else{
                        lattitude = row.lat;
                        longitude = row.long;
                        var alink =  "https://maps.google.com/?q=" + lattitude + "," + longitude+" "
                        var addressLink =  '<a  href=' + alink  + 'target="_blank" ><img height="20px" width="20px" src="../../../assets/image/addressICON.png"></a>'
                      }
                        var tempAdd = row.address;
                        if(tempAdd != undefined){
                              return tempAdd;
                        }else{
                          return addressLink;
                        }
                      
                    }
                },         
                { 
                  "data": "ac_status",
                  "visible" :true,
                  render: function(data, type, row) {
               
                  var aStatus;
                  if(data == null){
                    aStatus = 'NA';
                  }
                  if(data == '0'){
                    aStatus = 'OFF';

                  }
                  if(data == '1'){
                    aStatus = 'ON';

                  }       
                  return aStatus;
                  }
              },                    
              ], 
              "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": "20%", "targets": 0 },
            
            
              { "width": "20%", "targets": 3 },  
             
             
              ]   
          });
    
      });
    
    }
    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);
    }

    millisecondConversion(duration){
    
        // var seconds = Math.floor((duration / 1000) % 60);
        // 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;
        // seconds = (seconds < 10) ? 0 + seconds : seconds;
      
        // return hours + ":" + minutes + ":" + seconds;
      console.log(duration)
        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;

      
    }

    getReport(event){
      console.log(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);
        that.minIdleTime = event.minidleT; 
        
        if(event.deviceArr.length==0){
          deviceId=[];
        }else{
          deviceId= event.deviceArr;
        }
        this.deviceArr = deviceId; 
        console.log('this.deviceArr',this.deviceArr);
      
        this.from_date = fd;
        this.to_date = td;
        console.log("b4");
        // this.tabelObj.clear();
        // var aa = [];
        // this.tabelObj.rows.add(aa); 
     
          this.Load = true;
        console.log(this.tabelObj);
        this.tabelObj.draw();    
          
      
      
      }
     
    }

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

    this.downloadPdf()
    
  }
// downloadPdf() {
//     let fileName =
//       "Idle 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('Idle 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 =
      "Idle 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.from_date).format('lll'); 
  outerThis.t_date =moment(this.to_date).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("Idle 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'];

      {
        Device_Name:'Vehicle',
        start_time:'Start Time',
        end_time:'End Time',
        idle_time:'Duration',
        ac_status:'AC Status',
        
      }
    ];
  }

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

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

       Device_Name:pdfBody[j].device.Device_Name,
        start_time:moment(new Date(pdfBody[j].start_time)).format('llll'),  
        end_time:moment(new Date(pdfBody[j].end_time)).format('llll'), 
        idle_time:this.millisecondConversion(pdfBody[j].device.idle_time),
        ac_status:pdfBody[j].device.ac_status?pdfBody[j].device.ac_status:'N/A'
      });
    }
    return body;
  }


    

}
