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 jsPDF : any;
declare var $: any;
const PDF_EXTENSION = ".pdf"
import * as moment from 'moment';
import { PlayTripComponent } from '../../../play-trip/play-trip.component';
import { ReportService } from '../../report.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-trip-management-report',
  templateUrl: './trip-management-report.component.html',
  styleUrls: ['./trip-management-report.component.scss']
})
export class TripManagementReportComponent implements OnInit {
  dataSelect: any[];
  addressLink1: string;
  finalArr=[]
  private finalise = new Subject<void>();
  constructor(private _service:ReportService,private contactService: ContactService,private router: Router,public dialog: MdDialog) {
    this._service.invokeEventFortripMReport.pipe(
      takeUntil(this.finalise)
    ).subscribe(value => {
        if(value){
         this.getReport(value); 
       }
      });
   }
    ngOnDestroy(){
    
    this.finalise.next(void 0);
  }
  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 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();      
   

  }
    


}


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
            }
            that.finalArr=[]
            var suburl = "";
            if((temp.from_date != undefined)&&(temp.to_date != undefined)){        
              suburl = "/user_trip/listPlannedTrip";
              
              that.contactService.postReports(suburl,
                {
                  "device": that.deviceArr.length ? that.deviceArr[0] : [],
                  "isAnnotated":true,
                  "from":new Date(temp.from_date).toISOString(),
                  "to":new Date(temp.to_date).toISOString()
                  
              }).subscribe((resp:any) => {   
                if(resp.length) {
                  resp.map(ite=>{
                    ite.end_time = ite.end_time ? ite.end_time : ''
                  })
                }
                that.finalArr=resp
                 that.Load = false ;
                 resp.sort((a, b) => new Date(b.start_time).getTime() - new Date(a.start_time).getTime());

                  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": "trip_name",
              render: function(data, type, row) {    
              return data?data:'';
              }
          },
              {
                  "data": "start_time",
                  render: function(data, type, row) {
                    var st = new Date(data);
                    return data ? (moment(st).format('llll')) : "";  
                    
                  }
              },
              {
                "data": "end_time",
                render: function(data, type, row) { 
                  var et = new Date(data);
                  return data ? (moment(et).format('llll')) : "";     
                }
            }  ,
            {
              "data": "trip_status",
              render: function(data, type, row) {
                // var st = new Date(data);
                return data ? data : "";  
                
              }
          },
            {
              "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": "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": "trip_charge",
        render: function(data, type, row) {    
        return data?data:'';
        }
    },
    {
      "data": "cargo_weight",
      render: function(data, type, row) {    
      return data?data:'';
      }
  },
  {
    "data": "cargo_content",
    render: function(data, type, row) {    
    return data?data:'';
    }
},
          
          ],  
          "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')
              }
          }   ,
            { targets: 1, type: 'date' },

         
         
          ] 
      });

  });

}

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

    this.downloadPdf()
    
  }

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

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

      {
       
        trip_name:"Trip name",
start_time: "Start time",
end_time: "End time",
trip_status: "Trip status",
startAddress: "Start Address",
endAddress: "End Address",
trip_charge: "Amount",
cargo_weight: "Weight",
cargo_content: "Material",
        
        
      }
    ];
  }

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

    rowCount = rowCount || 10;
    let body = [];
    for (var j = 0; j < rowCount; j++) {
      var stime = pdfBody[j].start_time ? new Date(pdfBody[j].start_time) : '';
      var endTime = pdfBody[j].end_time? new Date(pdfBody[j].end_time):'';
     
      body.push({
        trip_name:pdfBody[j].trip_name,
        start_time: pdfBody[j].start_time? moment(pdfBody[j].start_time).format('llll'):'',
        end_time: pdfBody[j].end_time ? moment(pdfBody[j].end_time).format('lll'):'',
        startAddress:pdfBody[j].startAddress?pdfBody[j].startAddress:'N/A', 
        endAddress:pdfBody[j].endAddress?pdfBody[j].endAddress:'N/A',
        trip_status:pdfBody[j].trip_status?pdfBody[j].trip_status:'N/A',
        trip_charge:pdfBody[j].trip_charge?pdfBody[j].trip_charge:'N/A',
        cargo_weight:pdfBody[j].cargo_weight?pdfBody[j].cargo_weight:'N/A',
        cargo_content:pdfBody[j].cargo_content?pdfBody[j].cargo_content:'N/A',
      });
    }
    return body;
  }



}
