import { Component, OnInit } from '@angular/core';
import { ContactService } from '../contact.service';
declare var $: any;
declare var moment:any;
@Component({
  selector: 'app-device-list',
  templateUrl: './device-list.component.html',
  styleUrls: ['./device-list.component.scss']
})
export class DeviceListComponent implements OnInit {
  identifier='deviceList'
  licenceStatus
  supAdm
  superAdm=JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id
   fromdate
  todate;
  tabelObj: any ;
  Load: boolean;
  fs: any;
  ls: any;
  emailid: any;
  or: any;
  useridd: any;
  custtype: any;
  devicess: any;
  total_vech=0;
  idle_vech=0;
  off_vech=0;
  maintanance=0;
  expiredDevices=0;
  OutOfReach=0;
  no_data=0;
  expire_status=0;
  Running=0;
  from: any;
  to: any;
  groupId: any;
  DealerID: any;
  data
    setTimeOut = {
    value: 20,
    viewValue: "20 Seconds"
  };
  timout = [{
    value: 10,
    viewValue: "10 Seconds"
  },
  {
    value: 20,
    viewValue: "20 Seconds"
  },
  {
    value: 30,
    viewValue: "30 Seconds"
  }]

  interval:any;
  it: number;
  constructor(private contactService:ContactService) { }

  ngOnInit() {
   this.data= JSON.parse(localStorage.getItem('dashboardCount'))
    this.to = new Date().toISOString();
    var d = new Date();
    let a = d.setHours(0, 0, 0, 0)
    this.from = new Date(a).toISOString();

    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.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    var fuelvalue  = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).fuel_unit;
    var today = new Date();
      var startDate = new Date(today.getFullYear(), today.getMonth(), 1);
      this.fromdate=startDate;
      this.todate=new Date();
    this.testTable();
    this.getDashbord()
    // this.superAdm=JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id
    // this.timeIntervalRefresh();
  }
  timeIntervalRefresh() {
  // var that=this;
  clearInterval(this.interval);

  this.it = (1000 * this.setTimeOut.value);

  this.interval = setInterval(() => {
    this.getDashbord()
  }, this.it);


}

  getDashbord(){

   this.contactService.getDashboard(this.emailid, this.from, this.to, this.superAdm, this.groupId,this.superAdm,this.DealerID).subscribe(
      data => {
        this.devicess = data
        console.log(data);
        
        this.total_vech = this.devicess.Total_Vech;
        this.idle_vech = this.devicess["Ideal Devices"];
        this.off_vech = this.devicess["OFF Devices"];
        this.maintanance = this.devicess["Maintance Device"];
        this.expiredDevices = this.devicess["expire_status"];
        this.OutOfReach = this.devicess["OutOfReach"];
        this.no_data = this.devicess["no_data"]?this.devicess["no_data"]:0;
        this.Running = this.devicess["running_devices"];
        this.expire_status= this.devicess["expire_status"];

      })
    }
 

  getData(){
    var data={
      f:this.fromdate,
      t:this.todate,
      deviceType:''
    }
    this.contactService.getVehicleList(data).subscribe(res=>{
      console.log(res);
      
    })
  }

  getReport(data){
    console.log(data);
    if(data=="getExcel"){
      this.exportExcel()

    }else{
      this.fromdate=new Date(data.fromDate).toISOString();
      this.todate=new Date(data.toDate).toISOString();
      this.licenceStatus=data.liecenceStatus;
      if(data.distributerSelect[0]){
        this.supAdm=data.distributerSelect[0]._id;
        this.superAdm=data.distributerSelect[0]._id;
        this.getDashbord()
      }else{
        this.supAdm=undefined;
        this.superAdm=this.useridd;
        this.getDashbord()
      }
      console.log(this.fromdate,this.todate);
      this.tabelObj.ajax.reload();

    }

    
  }

  testTable(){
  const that = this;
  console.log("inside function");
  // that.Load = true;

   $(document).ready(function() {
     that.tabelObj = $('#deviceTable').DataTable({
       "processing": false,
          "searching": true, 
          pagingType: 'full_numbers',
          pageLength: 25,
          serverSide: false,
          responsive: true,
          "scrollY":'60vh',  
          "scrollCollapse": true, 
          
          // "deferLoading": 25 ,  
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
            // "rowCallback": function(row: Node, data: any | Object, index: number){
          ajax: (mainData,callback) => {

  var data={
      f:that.fromdate,
      t:that.todate,
      deviceType:'',
      licenceType:that.licenceStatus,
      supAdm:that.supAdm
    }

    if(that.fromdate !=undefined && that.todate!=undefined){
      that.contactService.getVehicleList(data).subscribe(res=>{
        console.log(res);
        that.Load = false;
        if(res.length!=0){
          callback({ data: res[0].data });

        }else{
           callback({ data: [] });
        }
        
      })

    }else{
      callback({ data: [] });
      that.Load = false;
    }
  },
   "columns": [
              {
                  "data": "Device_Name",
                  "render": function(data, type, row) {                   
                    return data?data : '';                  
                  }
              },
              {
                  "data": "Device_ID",
                  "render": function(data, type, row) {                   
                    return data?data : '';                  
                  }
              },
              {
                  "data": "User",
                  "render": function(data, type, row) {                   
                    return data?(data.first_name+' '+data.last_name) : '';                  
                  }
              },
              {
                  "data": "Distributer",
                  "render": function(data, type, row) {                   
                    return data?(data.first_name+' '+data.last_name) : '';                  
                  }
              },
               {
                  "data": "Distributer",
                  "render": function(data, type, row) {                   
                    return data?(data.phone) : '';                  
                  }
              },
               {
                  "data": "created_on",
                  "render": function(data, type, row) {                   
                    return data?(data) : '';                  
                  }
              },
               {
                  "data": "expiration_date",
                  "render": function(data, type, row) {                   
                    return data?data : '';              
                  }
              },
              {
                  "data": "renew_at",
                  "render": function(data, type, row) {                   
                    return data?(data) : '';                  
                  }
              }
              ,{
                  "data": "Dealer",
                  "render": function(data, type, row) {                   
                    return data?(data.first_name+' '+data.last_name) : '';              
                  }
              },
              // "accountSuspended":1,"device_delete_on":1,"integrationId":1
              {
                  "data": "accountSuspended",
                  "render": function(data, type, row) {                   
                    return data;              
                  }
              },
              {
                  "data": "deletedDevice",
                  "render": function(data, type, row) {                   
                    return data?'true':'false';              
                  }
              },
               {
                  "data": "device_delete_on",
                  "render": function(data, type, row) {                   
                    return data?data : '';              
                  }
              },
              {
                  "data": "integrationId",
                  "render": function(data, type, row) {                   
                    return data?data : '';              
                  }
              },
             
              
//               [5:57 PM, 7/5/2021] Job 1: creation date
// [5:57 PM, 7/5/2021] Job 1: dealer name
// [5:59 PM, 7/5/2021] Job 1: Organization name
   
          ],  
          "columnDefs": [
            { className: "dt-body-left", "targets": [ 0,1,2,3,4,5,6,7,8,9,10,11] },  
          //   {
          //     "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 },
          //  { "width": "70px", "targets": 4 },
          //   { "width": "70px", "targets": 5 },
          //    { "width": "70px", "targets": 6 },  
          //    { "width": "70px", "targets": 7 },
          //    { "width": "70px", "targets": 8 },
          //    { "width": "70px", "targets": 9 },
          //           { "width": "10px", "targets": 10 },
          //            { "width": "10px", "targets": 11 },   
 
    //       {
    //     targets: -1, //-1 es la ultima columna y 0 la primera
    //     data: null,
    //     defaultContent: '<div class="btn-group"> <button (click)="show()">view</button></div>'
    // },
          ] , order: [[ 3, 'desc' ], [ 0, 'asc' ]]
      });

  });

}



tab:any;
  exportExcel()
	{
   console.log("Export");
   

	    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];
    console.log(this.tab);
    
  
	    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, ""); 

	    var ua = window.navigator.userAgent;
	    var msie = ua.indexOf("MSIE "); 

	    var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

	    return (sa);
  }

}



 