import { Component, OnInit } from '@angular/core';
import { ContactService } from '../../contact.service';
import { Http, Headers, RequestOptions, ResponseContentType } from '@angular/http';
import { saveAs } from 'file-saver';
import { environment } from '../../../environments/environment';
import { MdSnackBar, MdDialog } from '@angular/material';
declare var $: any;
declare var google: any;
import * as moment from 'moment';
import { PlayTripComponent } from '../../play-trip/play-trip.component';
const now = new Date();

@Component({
  selector: 'app-trip-load-unload',
  templateUrl: './trip-load-unload.component.html',
  styleUrls: ['./trip-load-unload.component.scss']
})
export class TripLoadUnloadComponent implements OnInit {
  dateStr: any;
  Fromdate = new Date();
  tableSwitch:boolean= true;
  todate = new Date();
  useridd: any;
  fDate: any;
  tDate: any;
  dev_url = environment.hostUrl;
  // dateString=['Today Report','Yesterday Report','Weekly Report','Monthly Report'];
  fromDate: any;
  toDate: any;
  Load: boolean;
  tabelObj: any;
  tabelObj_grouped:any;
  custtype: any;
  superAdmin: any;
  data_descip: string;
  reportArr :any= [];
  emailid: any;
  devicesss: any;
  options: any;
  finall: any;

  constructor(private contactService: ContactService, private http: Http, public snackBar: MdSnackBar,public dialog: MdDialog) { }

  ngOnInit() {
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.tDate = new Date();
    var fd = new Date();
    fd.setHours(0, 0, 0, 0);
    this.fDate = fd;
    // this.getDevices();
  
    this.testTable();
    var tt= this;
    setTimeout(()=>{
      tt.testTable_grouped();
     
    },5000)
  
  }

  deviceArr = [];
  tab: any;

  exportExcel() {
    console.log('Inside detailed');
    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);
  }
  exportExcel_grouped() {
   
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    var table = $('#deviceTable_grouped').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);
  }


  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,
        deferRender: true,
        scrollY:    '55vh',
        scrollX : true,
        scrollCollapse: true,
     
        "sScrollX": "100%",
        scroller:       true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        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 = "";
          // https://www.oneqlik.in/trackRouteMap/getTripReport?userid=59cbbdbe508f164aa2fef3d8
          suburl += "/trackRouteMap/getTripReport?userid=" + that.useridd +'&from='+from_date.toISOString()+ '&to='+ to_date.toISOString();
          if (that.deviceArr.length != 0) {
            suburl += '&device=' + that.deviceArr;
          }

          console.log('that.deviceArr',that.deviceArr);
       
            that.contactService.get(suburl).subscribe(resp => {
              console.log('resp=>',resp); 
              // var tripData = [];
              // tripData = resp ; 

              // that.reportArr = [];
              // that.reportArr= resp ; 
              that.Load = false; 
            
              callback({ data: resp });
       
            }, err => {
              that.Load = false;
              var errCode = err.status;
              if(errCode == 500){
                callback({ data: [] });
              }
              console.log("error", err);
            });
        },
        "rowCallback": function(row: Node, data: any | Object, index: number){  
          $('#playTrip', row).bind('click', () => {  
            console.log(data);
           console.log(data.reportingDateTime);
           console.log(data.exitDateTime);
            var fd = new Date(data.loadingPoint.reportingDateTime).toISOString();
            var td = new Date(data.destination.exitDateTime).toISOString();
              var replayObj= {
                fromdate:fd,
                todate : td,
                user : that.useridd,
                device:{imei: data.deviceId,_id: data.device_id,iconType:'car'},
                geofences:[data.Source, data.Destination]  ,
                distance: (typeof data.distanceTravelled === 'number')?(parseFloat(data.distanceTravelled).toFixed(2)):0    
              }

              let dialogRef = that.dialog.open(PlayTripComponent, {    
                data: replayObj
              });
            
              dialogRef.afterClosed().subscribe(result => {
                console.log(result);
                if(result == 'cancelled'){
                
                }
              })  
             
              
            }); 
             
        }
      ,
         

        "columns": [
          // {
          //   "data": "_id",
          //   "defaultContent": "",
          //   "visible" : false,
          //   "render": function (data, type, row) {       
           
          //     return data ? data : "";   
          //   }
          // },
          
          {
            "data": "vrn",
            "defaultContent": "",
            "render": function (data, type, row) {       
           
              return data ? data : "";   
            }
          },
          {
            "data": "Source",
            "defaultContent": "",
            "render": function (data, type, row) {       
           
              return data ? data.geoname : "";   
            }
          },
          {
            "data": "Destination",
            "defaultContent": "",
            render: function (data, type, row) {
              return data ? data.geoname : '';
            }
          },
          {
            "data": "loadingPoint",
            "defaultContent": "",
            render: function (data, type, row) {    
            return data ? moment(data.reportingDateTime).format('llll') : "--";
            }
          },
          {
            "data": "destination",
            "defaultContent": "",
            render: function (data, type, row) {   
              return data ? moment(data.exitDateTime).format('llll') : '--';
            }
          },
          {
            "data": "distanceTravelled",
            "defaultContent": "",
            render: function (data, type, row) {
              return data ? parseFloat(data).toFixed(2) : 0.0;
            }
          },
          {
            "data": "tripTime",
            "defaultContent": "",
            render: function (data, type, row) {
              return data ? that.secondsToHms(data.total) : "0:0";
            }
          },
          {
            "data": "tripTime",
            "defaultContent": "",
            render: function (data, type, row) {
              that.secondsToHms(data.running);
              return data ? that.secondsToHms(data.running) : '0:0';
            }
          },
          {
            "data": "tripTime",
            "defaultContent": "",
            render: function (data, type, row) {
              return data ? that.secondsToHms(data.stoppage) :'0:0';
            }
          },
          {
            "data": "tripTime",
            "defaultContent": "",
            render: function (data, type, row) {
              return  '--';
            }
          }
          ,
          {
            "data": "status",
            "defaultContent": "",
            render: function (data, type, row) {
              return  data;
            }
          }
          ,
          {
            "data": "null",
            "defaultContent": "",
            render: function(data, type, row) {    
              if(row.status  == 'COMPLETED'){
                return '<i id="playTrip" style="color:green;cursor:pointer" class="fas fa-play"></i>';
              }else{
                return '<i class="fas fa-times"></i>';
              }
          
            }
        }    
        ]
        // "columnDefs": [
        //   { className: "dt-body-left", "targets": [0, 1, 2, 3,4,5,6,7] },
        //   {
        //     "targets": '_all',
        //     "createdCell": function (td, cellData, rowData, row, col) {
        //       $(td).css('padding', '18px')
        //     }
        //   },
        //   { "width": "10px", "targets": 0 },
        //   { "width": "40px", "targets": 1 },
        //   { "width": "100px", "targets": 2 },
        //   { "width": "70px", "targets": 3 },

        // ]
      });

    });

  }

  testTable_grouped() {

    const that = this;
    console.log("inside function grouped");
    $(document).ready(function () {
      that.tabelObj_grouped = $('#deviceTable_grouped').DataTable({
      
        "processing": true,
        "searching": true,
        pagingType: 'full_numbers',
        pageLength: 25,
        serverSide: false,
        "scrollX": true,
        "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;


          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 = "";
        
          suburl += "/trackRouteMap/getTripCountReport?userid=" +that.useridd +'&from='+from_date.toISOString()+ '&to='+ to_date.toISOString();
          if (that.deviceArr.length != 0) {
            suburl += '&device=' + that.deviceArr;
          }
          console.log('B4 grouped data called');
            that.contactService.get(suburl).subscribe(resp => {    
              // console.log('response for grouped Data',resp);
            callback({ data: resp });
            }, err => {
              // that.Load = false;
              console.log('Error Detected in load unload grouped');
              callback({ data: [] });
              // var errCode = err.status;
              // if(errCode == 500){
               
              // }
            });
        },
        "rowCallback": function( row, data, index ) {
          // console.log(data);
         
          // var colorChk = data.utilization?parseFloat(data.utilization).toFixed(2):null;
          // console.log(row);
          if (data.utilization >= 60 )
          {
              $('td', row).css({'background-color': '#3ded1d','border-bottom' :'1px solid white'});
          }
          else if(data.utilization<60)
          {
              $('td', row).css({'background-color': '#FF0800' ,'border-bottom' :'1px solid white'});
          }else{
            $('td', row).css({'background-color': 'grey','border-bottom' :'1px solid white'});
          }
      },
 
        "columns": [
       
          
          {
            "data": "Vehicle Name",
            "defaultContent": "",
            "render": function (data, type, row) {       
           
              return data ? data : "";   
            }
          },
          {
            "data": "Source",
            "defaultContent": "",
            "render": function (data, type, row) {       
              // console.log('datadatadatadatadatadatadatadata',data.source)
              return data ? data.geoname : "--";   
            }
          },
          {
            "data": "Destination",
            "defaultContent": "",
            render: function (data, type, row) {
              // console.log('datadatadatadatadatadatadatadata',data)
              return data ? data.geoname : '--';
            }
          },
          {
            "data": "distanceTravelled",
            "defaultContent": "",
            render: function (data, type, row) {    
            return data ? data.toFixed(2):0;
            }
          },
          {
            "data": "running",
            "defaultContent": "",
            render: function (data, type, row) {    
            return  data ? that.secondsToHms(data) : "0:0";
            }
          },
          {
            "data": "stoppage",
            "defaultContent": "",
            render: function (data, type, row) {    
            return  data ? that.secondsToHms(data) : "0:0";
            }
          },
          {
            "data": "idle",
            "defaultContent": "",
            render: function (data, type, row) {    
            return  data ? that.secondsToHms(data) : "0:0";
            }
          },
          {
            "data": "utilization",
            "defaultContent": "",
            render: function (data, type, row) {    
            var  d = data?parseFloat(data).toFixed(2):'0'
            return  d;
            }
          },
          {
            "data": "efficiency",
            "defaultContent": "",
            render: function (data, type, row) {    
              var  e = data?parseFloat(data).toFixed(2):'0'
            return  e;
            }
          },
          {
            "data": "tripCount",
            "defaultContent": "",
            render: function (data, type, row) {   
              return data ?data:0;
            }
          }
      
        ],
        "columnDefs": [
          // { className: "dt-body-left", "targets": [0, 1, 2, 3,4] },
        ]
      });

    });

  }

  identifier: any = 'loadunloadTrip';
  getReport(event) {
    console.log("inside function");
    if (event == 'getExcel') {
      if(this.detector === 'group'){
        this.exportExcel_grouped();
        
      }
      if(this.detector === 'detail'){
        this.exportExcel();
        
      }
     
    } 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();
     var pt = this;
     var tmp =  setTimeout(()=>{
        pt.tabelObj_grouped.ajax.reload();
        clearTimeout(tmp);
      },2000)
     
    }

  }


   secondsToHms(d) {
    d = Number(d);
    var h = Math.floor(d / 3600);
    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);

    var hDisplay = h > 0 ? h : "0";
    var mDisplay = m > 0 ? m : "0";
    var sDisplay = s > 0 ? s  : "0";
    return hDisplay + ":" +mDisplay; 
}

detector='group';
changeDetector(iden){
 
  
  if(iden === 'detail'){
    this.detector = 'detail';
  }
  if(iden === 'group'){
    this.detector = 'group';


  }
}




}
