import { Component, OnInit } from '@angular/core';
import * as moment from 'moment';
import { ContactService } from '../../contact.service';
import { Router } from '@angular/router';
import { MdDialog } from '@angular/material';

declare var $:any;
@Component({
  selector: 'app-maintanance',
  templateUrl: './maintanance.component.html',
  styleUrls: ['./maintanance.component.scss']
})
export class MaintananceComponent implements OnInit {
  identifier : String = "maintanance_report";
  superAdmin: any;
  useridd: any;
  custtype: any;
  optionVal:any;
  deviceArr: any=[];
  tabelObj: any;
  Fromdate: Date;
  todate: Date;
  Load: boolean;
  constructor(private contactService: ContactService,private router: Router,public dialog: MdDialog) { }

  ngOnInit() {
    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.testTable();
  }

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

getReport(event){
  
  console.log("inside function");
  if(event == 'getExcel'){
    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();  
    // this.tabelObj.draw();  
    // this.tabelObj.draw();
    // if(this.ajaxCount != 0){
 
    // }
    // this.ajaxCount = 1 ; 
  }
 
}



testTable() {
  const that = this;
  console.log("inside function");
  $(document).ready(function() {
    that.tabelObj = $('#deviceTable').DataTable({
      dom: 'lBftip',
      buttons: [
        'copy',
        'print',
        'excel'
      ],       
        "processing": true,
        "searching": false,
        pagingType: 'full_numbers',
        pageLength: 25,
        serverSide: true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        ajax: (dataTablesParameters: any, callback) => {
          
            dataTablesParameters.op = {};
            dataTablesParameters.select = [];
            dataTablesParameters.find = {};

            dataTablesParameters.find['$and'] = [];
            var userFilter = {};
            userFilter['$or'] =[ {user : that.useridd}, {created_by :that.useridd} ]
            dataTablesParameters.find['$and'].push(userFilter);

            // dataTablesParameters.find['$or'] = [currUser,admin]  

            dataTablesParameters.columns = [
          
          {data:"_id"},
          {data:'user.first_name'},
          {data:'user.last_name'},
          {data:'device.Device_Name'},
          {data:'device.Device_ID'},
          {data:'reminder_date'},    
          {data:'notification_type.SMS'},
          {data:'notification_type.EMAIL'},
          {data:'notification_type.PUSH_NOTIFICATION'},
          {data : 'reminder_type'},
          {data :'date_of_service'},
          {data : 'performed_by'},
          {data : 'prior_reminder'},
          {data : 'odo'},
          {data:'note'},
          {data:'status'},
            ]            
           
          
            var reminder_date={};
        
       
            // dataTablesParameters.find.user = that.useridd;
            if(that.deviceArr.length != 0){
              console.log('that.deviceArr',that.deviceArr);
              var dev_in = {device : {'$in': that.deviceArr}};
            
                dataTablesParameters.find['$and'].push(dev_in);
                }
                 if (that.Fromdate) {
                  var fdate = new Date(that.Fromdate).toISOString()                      
                   reminder_date['$gte']=fdate  
                

              };
              if (that.todate) {
                var tdate = new Date(that.todate).toISOString()        
                 reminder_date['$lte'] =  tdate     ;
                
            };
            var r_d ={};
            r_d['reminder_date'] = reminder_date ; 
            dataTablesParameters.find['$and'].push(r_d);
       
          
              var r_t = {};
              r_t['status'] = 'Completed' ;
              dataTablesParameters.find['$and'].push(r_t);               
            
            // dataTablesParameters.find.user = that.useridd ;       

            
           console.log('dataTablesParameters.find=>',dataTablesParameters.find);
            if(that.deviceArr.length != 0 && that.Fromdate && that.todate){
            // that.minIdleTime =      
            var suburl = "";
            suburl += "/reminder/reminderdatatable";
            that.contactService.post(suburl, dataTablesParameters).subscribe(resp => {     
                console.log("Response from datatable=>",resp);     
                that.Load= false;         
                callback(resp);
            }, err => {                
              that.Load= false;    
         
            });
          }else{
              that.Load= false; 
               callback({data : []});
          }
            // }else{
            //   that.Load= false;    
            //   let message1="Please Select Device";
            //   let action:any;
            //   that.snackBar.open(message1, action, {
            //     duration: 5000,
                
            //   });  
            //   return;
            // }
           
                                      
     
        },  
 

        "columns": [
            {
                "data": "date_of_service",
                "visible" :true,
                "render": function(data, type, row) {
              
                 return data?moment(data).format('llll'):'NA';
                    
                }
            },
            {
                "data": "device.Device_Name",
                "visible" :true,
                render: function(data, type, row) {
                    
                    return data?data:'';           
                }
            },
            {
                "data": "device.Device_ID",
                "visible" :true,
                render: function(data, type, row) {
                  console.log('data',data);                                      
                    return data?data:'';
                }
            }, 
            {
              "data": "odo",
              "visible" : true,
              render: function(data, type, row) {  
                
                  return data?data:"NA";
              }
          },    
            
            {
              "data": "reminder_type",
              "visible" :true,
              render: function(data, type, row) {             
                  return data?data:'--';
              }
          },         
          { 
            "data": "performed_by",
            "visible" :true,
            render: function(data, type, row) {
          return data?data:''
            }
        }, 
        { 
          "data": "note",
          "visible" :true,
          render: function(data, type, row) {
           return data?data:''
          }
      }, 
  
                
        ],   
    });

  });

}


}
