import { Component, OnInit , Inject, OnDestroy} from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import {DialogContentExampleDialogComponent} from '../dialog-content-example-dialog/dialog-content-example-dialog.component';


import {Device} from '../device';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/debounceTime';
import { Observable } from 'rxjs/Observable';
import * as io from 'socket.io-client';
/* import { DeviceReportComponent } from '../device-report/device-report.component';
 */
import { DeviceEditComponent } from '../dashboard/device-edit/device-edit.component';
import {MdSnackBar} from '@angular/material';
import { DeviceShareComponent } from '../dashboard/device-share/device-share.component';
import { ShareUserComponent } from '../dashboard/share-user/share-user.component';
import { Params,Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import {ContactService} from '../contact.service';
import { checkNoChangesNode } from '@angular/core/src/view/view';
import { SpeednotifyComponent } from '../dashboard/speednotify/speednotify.component';
import { SidebarComponent } from '../sidebar/sidebar.component';
import { MyaccountComponent } from '../myaccount/myaccount.component';
import {DatainjectionService} from '../datainjection.service'
import { isUndefined } from 'util';
import { GeneralSettingsComponent } from './general-settings/general-settings.component';
import { environment } from '../../environments/environment';
import * as XLSX from 'xlsx';
import * as fileSaver from 'file-saver';
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
declare var $: any;
import * as moment from 'moment';

import { BsDatepickerConfig } from 'ngx-bootstrap';
import { RenewalHistoryComponent } from './renewal-history/renewal-history.component';
import { EChalanComponent } from './e-chalan/e-chalan.component';
import { DeviceDocComponent } from '../kyc-approval/device-doc/device-doc.component';
import { CertOptionComponent } from '../device/cert-option/cert-option.component';
import { EditDeviceMasterComponent } from '../device/edit-device-master/edit-device-master.component';
import { NormalCertComponent } from '../device/normal-cert/normal-cert.component';
import { ViewCertificateComponent } from './view-certificate/view-certificate.component';
import { DownloadCertificateComponent } from './download-certificate/download-certificate.component';
declare var google: any;
declare var swal: any;
declare var DataTable: any;

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss'],
  // providers: [ContactService,SidebarComponent]
})


export class DashboardComponent implements OnInit {
  skip:number=0;
  limit:number=25;
  adbtn: string;
  chkAddBtn: string;
  Status_name = [];
  liecenceStatus="new"
  distributerValue
  liecenceTypeArray=[
    {name:"New",value:"new"},
    {name:"Renewal",value:"renewal"}
  ]
  statusArray = [
    {name:"RUNNING",status:false,value:"RUNNING"},
    {name:"IDLING",status:false,value:"IDLING"},
    {name:"STOPPED",status:false,value:"STOPPED"},
    {name :"Expired",status : false,value:"Expired"},
    {name:"OUT OF REACH",status:false,value:"OUT OF REACH"},
    {name : "NO GPS FIX",status : false,value:"NO GPS FIX"},
    {name : "NO GPS FIX",status : false,value:"NO GPS FIX"},
    {name:"NO DATA",status:false,value:"NO DATA"}
  ];
 //private url = 'http://localhost:3000/api/graph';  
  private socket;
  Load:boolean=false
 messages = [];
 connection;
 graphs:any;
 message;
  numberOfOnlineUsers: number;
devices: Device[];
device: Device;
Device_ID: string;
from_date: Date;
to_date: Date;
bsConfig: Partial<BsDatepickerConfig>;
Serial_Num: string;
Manf: string;
Model: string;
del:boolean = false;
colorTheme = 'theme-dark-blue';
Des: string;
Hardware_Ver: string;
Loca: string;
login:any;  
visibility:any;
/* tabs: Tab[] = []; */
calculateResult=[];
value:any;
a:any;
homeVis:any;
visibility0:any;
j:any;
id:any;
dev:any;
checked:any
MdSlideToggleChange :any;
e: Event;
d:any;
expiredVeh:any;
fs :any;
ls :any;
or :any;
/* e =[];
 */token :any;
emailid :any;
devicess :any;
devicesss :any;
userID:any;
final:any;
lat:any;
lng:any;
latLongArr:any
convertedToString :String;
useridd:any;
notifi = [];
g:any;
tableFlag:boolean=true;
status : any;
groupId : any;
statuss : any;
modelChanged: Subject<string> = new Subject<string>();
  supAdm: any;
  DealerID: any;
  url: string;
  showNav: boolean = false;
  count: number =0;
  customDatafilter: boolean =false;
  customlimit: any = null;
  dateId: any;
  dealer_Permission: any;
  panelInfo: any;
  disDataFIlter=[]
  distributers: any;
  constructor(
    public dialog: MdDialog,
    private injectData: DatainjectionService,
    public snackBar: MdSnackBar,
    private router: Router,
    private contactService: ContactService,
    private activatedRoute: ActivatedRoute) {
      this.modelChanged
      .debounceTime(2000) // wait 300ms after the last event before emitting last eventpublic sidebar: SidebarComponent,
      .distinctUntilChanged() // only emit if value is different from previous value
      .subscribe(myInput => {
        this.myInput = myInput;
        this.tabelObj;
        this.getdev();
  
      });
      
     }
bussinessType;
showButton:Boolean=false
  ngOnInit() {
    // this.updateFieldswithvalue() 
    
    this.showDemoVideo();
    this.socket_Ing = this.injectData.getSocket_gps();

    // this.from_date = new Date();
    // this.from_date.setDate(1);
    // this.to_date = new Date();
    this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYY, h:mm:ss a' }, { containerClass: this.colorTheme });
    //io.connect('https://www.oneqlik.in/gps', { secure: true, rejectUnauthorized: false, transports: ["polling"], upgrade: false });

    this.socket_Ing.on('connect', function (this) {
      // console.log('Ignition IO Connected');
    })
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.adbtn = localStorage.getItem("dlrchk");
    this.bussinessType=JSON.parse(window.atob(window.localStorage.token.split(".")[1])).bussinessType
    console.log(this.bussinessType);
    
     this.getSuperAdminList()
    this.logo = window.localStorage['logo'];
    this.text = window.localStorage['text'];
    window.localStorage['DataUpdate'] = 'True'
    if (window.localStorage.FinalAddDevice == 'True') {
      this.tost1("new_Device");
    }
    // this.sidebar.sidebarData();
    this.notify();
    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.dealer_Permission = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).device_add_permission;
    // console.log('this.dealer_Permission',this.dealer_Permission);
    // console.log("getuserObjectid",this.useridd);
    this.mb = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    this.dealerTocust = localStorage.getItem('Custumer');
    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.panelInfo  = localStorage.getItem('supAdminAcessToCust');
    // this.dealer_Permission = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).device_add_permission;
    if(window.localStorage.Dealer_token){
      // console.log("DEALER TOKEN IS PRESENT");
      if(JSON.parse(window.atob(window.localStorage.Dealer_token.split(".")[1])).isDealer){
        // console.log("IS DEALER");
        
        this.dealer_Permission = JSON.parse(window.atob(window.localStorage.Dealer_token.split('.')[1])).device_add_permission;
        // console.log(this.dealer_Permission);
        
      }else{
        // console.log("!  IS DEALER");
       this.dealer_Permission = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).device_add_permission; 
        console.log(this.dealer_Permission);
      }
      
    }else{
      // console.log("!  OTHER");
      //  console.log(this.dealer_Permission);
    }
    var dealerToken= window.localStorage.Dealer_token?JSON.parse(window.atob(window.localStorage.Dealer_token.split(".")[1])):''
    // console.log("IUKIDJKDJKJ",dealerToken,JSON.parse(window.atob(window.localStorage.token.split(".")[1])))
    
    // console.log(
    //   {"Dealer" :this.custtype,"Admin": this.superAdmin,"panelInfo" :window.localStorage['Custumer']}
    // )
    
    if (this.custtype == true) {
      this.cust = true;
    }
    let foods = [];
    console.log("TESTSTSTSTSTT==>",this.custtype,this.dealer_Permission,this.superAdmin,this.bussinessType);
    
    if (this.mb.charAt(0) == "n") {
      this.mb = ' '
    }
    if (window.localStorage['Custumer'] == 'ON') {
      this.logoutbut = false
      this.dealer = true
    }
    else {
      this.logoutbut = true
    }

    if(this.superAdmin){
      this.supAdm = this.useridd;
    }
    if(this.custtype){
      this.DealerID = this.useridd

    }
    // console.log(this.superAdmin,this.custtype);
    if(this.custtype && this.dealer_Permission){
      this.showButton=true;
    }else if(this.superAdmin){
      this.showButton=true;
    }
    // ((custtype && ((dealer_Permission == true)||(dealer_Permission === undefined)))||superAdmin) && (bussinessType!=0 || bussinessType==undefined)

    // this.activatedRoute.params.subscribe((params: Params) => {
    //   let id = params['id'];
     
    //   this.groupId = id;
     
    // });
    this.emailid = this.emailid ? this.emailid : "";
    this.useridd = this.useridd ? this.useridd : "";
    this.status = this.status ? this.status : "";
    this.groupId = this.groupId ? this.groupId : "";
    this.statuss = this.statuss ? this.statuss : "";
    var dateObj = {};
    this.contactService.getDeviceByFilter(this.emailid, this.useridd, this.groupId, this.status, this.statuss, this.skip, this.limit,this.myInput,this.supAdm,this.DealerID,dateObj,this.liecenceStatus).subscribe(
      data => {
        this.devicess = data
      // console.log("IN NGONINIT",this.devicess);
        if(this.devicess.devices.length==0){
          this.firstcall=true;
          this.lastcall=false;
        }
    
        this.final = this.devicess.devices;
        for (let i = 0; i < this.devicess.devices.length; i++) {
          if (this.devicess.devices[i].type_of_device == "Tracker") {
            let a = {
              value: this.devicess.devices[i].Device_Name,
              viewValue: this.devicess.devices[i].Device_Name
            }
            foods.push(a);
          }
        }
        this.abc(this.final);

      });


 
}


table1ch(){
  myFunction();
      function myFunction() {
        var input,filter, table, tr, td, i,td1;
        input = document.getElementById("myInput");
       
        filter = input.value.toUpperCase();
        // console.log(filter);
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        for (i = 0; i < tr.length; i++) {
          td = tr[i].getElementsByTagName("td")[2];
          td1= tr[i].getElementsByTagName("td")[0];
         
          if (td) {
            if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
              tr[i].style.display = "";
              
            } 
            else if(td1.innerHTML.toUpperCase().indexOf(filter) > -1){
              tr[i].style.display = "";
            
            }
            else {
              tr[i].style.display = "none";
            }
          }       
        }
      }
    }

    

    searchFilter(text: string) {
      this.modelChanged.next(text);
     
  
    }
  



cond:Boolean = false;
point : any = 0;
 aa(){
  // console.log(this.point);
   if(this.point == 0){
    this.cond = true;
    this.point ++;
   }
 else if(this.point % 2 == 0){
  this.cond = true;
  this.point ++;
 }
 else{
   this.cond = false
   this.point ++;
 }

  
}

BB:Boolean = false;
dataa:Boolean = false;


onChange2(q,dname,did,speed){
  var status2;
  //console.log(t.rowIndex);

  if(!q.checked){
  status2 = false;
  //this.BB = false;

  this.contactService.speedlimit2(did,"false").subscribe(
      
    data => {
      this.dataa = data ;
      var dateObj = {};
      this.contactService.getDeviceByFilter(this.emailid,this.useridd,this.groupId,this.status,this.statuss,this.skip,this.limit,this.myInput,this.supAdm,this.DealerID,dateObj,this.liecenceStatus).subscribe(
        (data)=> {
        // console.log("11111111111111111122")
           this.devicess = data 
           this.final = this.devicess.devices
          //  console.log(this.final);
           window.localStorage['DataUpdate'] = 'True';
          //  this.sidebar.sidebarData();
       
        }
      )


    }, (err: any) => {; 
      // console.log(err);
    if(err.status !=   200)
    {
      this.tost1("NotSucc");
    }})

  }
    else{
      status2 = true
     // this.BB = true;
     this.openDialog5(dname,status2,did,speed)

  }


}

  onChange(e,d) {
  var status;
    if(!e.checked){
              status = false;
    }
    else{
      status = true
    }

    this.contactService.getDeviceStatus(d,status).subscribe(
  
      data => {
        this.devicess = data 
   
      });

    }
    devi(){
      this.router.navigateByUrl("dashboard?_i="+window.localStorage.token);
  
    }
    geo(){
      this.router.navigateByUrl("geofencing");
      
    }

    driverPerformance(){
      this.cond = false
      this.router.navigateByUrl("device-report/Driver-performance");
    }
    openNav() {

    this.router.navigateByUrl("location");

  }
  closeNav() {
    document.getElementById("myNav").style.width = "0%";
}
   
    devv:any;
    deleteshare(did){
      this.Load = true
   //   console.log(did);
      this.contactService.deldevshr(did,this.useridd)
      .subscribe(
      
         data => {

          this.devv = data 
          var dateObj = {};
          this.contactService.getDeviceByFilter(this.emailid,this.useridd,this.groupId,this.status,this.statuss,this.skip,this.limit,this.myInput,this.supAdm,this.DealerID,dateObj,this.liecenceStatus).subscribe(
  
            data => {
             this.devicess = data 
//  console.log("1111111111111111333311")

             this.final = this.devicess.devices;
             this.Load =false
             this.tost1("deleteshareDevice");
             window.localStorage['DataUpdate'] = 'True'
            //  this.sidebar.sidebarData();
            }, (err: any) => {; 
           
            if(err.status !=   200)
            {
              this.Load =false
            }});

        });
    
    }


// delete(did){
//   swal({
//     title: 'Are you sure?',
//     text: "You won't be able to revert this!",
//     type: 'warning',
//     showCancelButton: true,
//     confirmButtonColor: '#3085d6',
//     cancelButtonColor: '#d33',
//     confirmButtonText: 'Yes, delete it!'
//   }).then((result: { value: boolean; }) => {
//     if (result) {
//       this.Load =true;
//       this.contactService.deldev(did)
//       .subscribe(
//         data => {
                     
//           swal(
//             'Deleted',
//             'Device Deleted',
//             'success'
//           )
//           this.dev  = data 
//           this.contactService.getDeviceByFilter(this.emailid,this.useridd,this.groupId,this.status,this.statuss,this.skip,this.limit,this.myInput,this.supAdm,this.DealerID).subscribe(
        
//             data => {
//               this.devicess = data    
//               this.final = (this.devicess.devices);
//               this.Load =false
//               this.tost1("delete");
//               window.localStorage['DataUpdate'] = 'True';
//               this.sidebar.sidebarData();     
//             }, (err: any) => { 
//               // console.log(err);

//             if(err.status !=200)
//             {
//                this.Load =false
//             }
//             this.Load =true;
//           });  
//         },err=>{
//           swal(
//             'Error',
//             'Internal Server Error, Please try after sometime !!!',
//             'success'
//           )
//         })    
//     }
//   })




// }
 adddev(){
  // this.router.navigateByUrl("add-device");
  // this.panelInfo
  var distId = this.useridd; 

  if(this.panelInfo==='true'){
    distId = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).supAdmin;
  }

  var distPoint = '1';
  this.contactService.getAvialblePoints(distId,distPoint).subscribe(res=>{
    if(res.available_points<=0){
      // console.log("Inside toast");
      this.data_descip = 'Insufficient Points';
      launch_toast()

    }else{
      this.router.navigateByUrl("add-device");
    }

    function launch_toast() {
      // console.log(divid);
      var x = document.getElementById("toast")
      //console.log(x);
      x.className = "show";
      setTimeout(function () { x.className = x.className.replace("show", ""); }, 4500);
    }

})


 
}
vewdev(id,name,type,expDate){

  let currDate = new Date().getTime();
  let chkDate = new Date(expDate).getTime();

  // console.log("Inside adddiv");
 // console.log(id + name);
 var dataStatus = {
  vehicleId:id,
  vehicleName:name,
  vehicleType:type
}

if(currDate>chkDate){
  // console.log("Service expired !!!")
  this.tost1("experr");

}

 else if(type=="Tracker"){

    this.router.navigateByUrl("location?_dname="+name+"_id="+id);
    window.localStorage['devDetail']= JSON.stringify(dataStatus);
    
    
  }
  else{
  this.router.navigateByUrl("account?_did="+id+"."+name); 
  }
}

  selectedIndex:number=0;
  clickMe(value){
    this.selectedIndex=this.value;
    if(!this.visibility0)
    this.visibility0=!this.visibility0; 
  }

  onLinkClick($event: any) {
    // console.log($event);
  
  }

  cancle(a){
    // console.log(a);   
    this.visibility0=!this.visibility0;  
  }
  
 
sha :any;
// openDialog4(a,b,c){

//   let dialogRef = this.dialog.open(ShareUserComponent, {
//     width: '528px',
//     data: { name: a, dname:b, did:c}
//   });

//   dialogRef.afterClosed().subscribe(result => {
    
//     // console.log(result);
//     if(result == "OKK"){
//       this.tost1("removeuser");
//       window.localStorage['DataUpdate'] = 'True';
//       this.sidebar.sidebarData(); 
//     }
//     else if(result == "No_Dev"){
//       this.tost1("No_Dev");

//     }
//   });

// }
// openDialog3(a,b){
//   let dialogRef = this.dialog.open(DeviceShareComponent, {
//     width: '528px',
//     data: { name: a , did:b}
//   });

//   dialogRef.afterClosed().subscribe(result => {
//     // console.log(result);
//     if(result == "OK"){
//       this.tost1("share");
//       window.localStorage['DataUpdate'] = 'True';
//       this.sidebar.sidebarData(); 
//     }
//   });
// }

openDialog5(dname,status,did,speed){
  let dialogRef = this.dialog.open(SpeednotifyComponent, {
    width: '528px',
    data: { dname: dname , did:did, status:status, speed:speed}
  });

  dialogRef.afterClosed().subscribe(result => {
   // console.log(result);

    let  foods = [];
    var dateObj = {}
    this.contactService.getDeviceByFilter(this.emailid,this.useridd,this.groupId,this.status,this.statuss,this.skip,this.limit,this.myInput,this.supAdm,this.DealerID,dateObj,this.liecenceStatus).subscribe(
      
      data => {
     
        this.devicess = data 
        //  console.log("111111111111144444111")

       /*  this.final = this.devicess.devices[0]; */
       this.final = (this.devicess.devices);
    
      //  console.log(this.final);
      
       for(let i=0;i<this.devicess.devices.length;i++){
       
         if(this.devicess.devices[i].type_of_device =="Tracker"){
           let a ={
            value : this.devicess.devices[i].Device_Name,
            viewValue:this.devicess.devices[i].Device_Name
           }
           foods.push(a);
         }
      
       }
  
      });

      if(result == "device_alert"){
        this.tost1("device_alert");
      }
      else if(result == null){
       this.ngOnInit();
      }
  });



}


alert_report(){
  this.cond = false
  this.router.navigateByUrl("device-report/alert_report");
  
}

myInput:any;
data_descip :any;
before:any;
// TOAST


tost1(divid){
if(divid == "share"){
  this.data_descip = "Device Succesfully Shared";
  launch_toast();
}else if(divid == "experr"){
  this.data_descip = "Access denied, Service expired";
  launch_toast();
}
else if(divid == "delete"){
  this.data_descip = "Device Deleted Succesfully";
  launch_toast();
}
else if(divid == "update"){
  this.data_descip = "Device Succesfully Updated";
  launch_toast();
}
else if(divid == "blankemail"){
  this.data_descip = "Blank Email ID or Mobile Number";
  launch_toast();
}
else if(divid == "deleteshareDevice"){
  this.data_descip = "Share Device Succesfully Removed";
  
  launch_toast();
}
else if(divid == "removeuser"){
  this.data_descip = "Share Device User Succesfully Removed";
  
  launch_toast();
}



else if(divid == "No_Dev"){
  this.data_descip = "No Shared Users for this Device";
  
  launch_toast();
}
else if(divid == "device_alert"){
  this.data_descip = "Speed Alert Sucessfully Added";
  launch_toast();
}
else if(divid == "NotSucc"){
  this.data_descip = "Speed Alert Removed";
  launch_toast();
}
else if(divid == "new_Device"){
  window.localStorage['FinalAddDevice'] = 'False'
  this.data_descip = "New Device Added";
  launch_toast();
}
  function launch_toast() {
   // console.log(divid);
    var x = document.getElementById("toast")
    //console.log(x);
    x.className = "show";
    setTimeout(function(){ x.className = x.className.replace("show", ""); }, 1500);
}
 }
  openDialog2(a,b,c,d,e,f,g,h,i,j,k,user,vehType,dev_IMEI,simProvider,totalODO,inteId,sim2,simprovider2,device,sellsPerson,installer): void {
    var internalThat  = this;
    let dialogRef = this.dialog.open(DeviceEditComponent, {
      width: '950px',
      // height: '1160px',   
      data: { _id: a, des: b, sim:c, dname:d, speed:e,iconType:f,drname:g,dcontact:h,expdate:i,model:j,mainmodel:k,assigned_to:user,vehicleType:vehType,devIMEI:dev_IMEI,S_provider:simProvider,tot_ODO:totalODO,itiId:inteId,simNUM2:sim2,simProvider2:simprovider2,devObj:device,sellsPerson:sellsPerson,installer:installer}
      
    });

    dialogRef.afterClosed().subscribe(result => {
      // console.log("result",result);
      this.ngOnInit();
     
        if(result=="done"){
          // console.log("resultdone",result)
          this.tost1("update");
          window.localStorage['DataUpdate'] = 'True';
          // this.sidebar.sidebarData();       
        }
    });
  }

  // editDeviceInformation(deviceforedit: Object) {
  //   var that = this;
  //   deviceforedit['actionFlag'] = 'edit';
  //   console.log('DeviceObject=>', deviceforedit);
  //   localStorage.setItem('deviceforedit',JSON.stringify(deviceforedit))
  //   this.router.navigateByUrl("add-device");
   

  // }
  

  shareOwner:any;
  ss:any;
  y:any;
  test3(a,b){
    if(b){
      let u = b.split(",");
      for(let p=0 ; p<u.length; p++){
        if(this.useridd == u[p]){
          this.y=a;
          return true;
        } 
      }
    }
   else{
     return false;
   }
    
    
  }

//   updateFieldswithvalue(){
//     this.contactService.tempDevicedata.subscribe(res=>{
//     console.log("tempdeviceobject=fhlkdsjksaldjasd>",res);  
//   });
// }
  group(){
    this.cond = false
    this.router.navigateByUrl("group_view");
  }
  


  test1(a,b){
    if(b){
      let u = b.split(",");
      for(let p=0 ; p<u.length; p++){
        if(this.useridd == u[p]){
          return true;
        } 
      }
    }
   else{
     return false;
   }
    
  }

  test(a,b){
  
    if(b){
      return !(b.split(",").indexOf(a)+1); 
    }
   else{
     return true;
   }
  }


notify(){
  
let a ={
  "NoteDate":"Notification1"
}
this.notifi.push(a);
let b ={
  "NoteDate":"Notification2"
}
this.notifi.push(b);
// console.log(this.notifi);
this.g= this.notifi;
}


custtype:any;
cust:boolean=false;

mydealer(){
  window.localStorage['token'] =  window.localStorage['Dealer_token'];
  localStorage.removeItem('devices');
  window.localStorage['DataUpdate'] = 'True';
  if(window.localStorage['DataLoaded'] = 'True'){
    window.localStorage['Custumer'] = 'OFF'
    this.router.navigateByUrl("add")
   // this.router.navigateByUrl("const?_status="+"OK");
  }
}
getdev(){
  // console.log("Inside Anonym function")
  let foods = [];

  // console.log("statusName = > ", this.Status_name);
  if(this.Status_name != null){
    // console.log();
    this.statuss = this.Status_name;
  }

  var dateObj = {};
 
  if((this.dateId == 'todate')||(this.to_date != undefined)){
      dateObj['to_date'] = this.to_date.toISOString();

  }
  if((this.dateId == 'fdate')||(this.from_date != undefined)){
    dateObj['from_date'] = this.from_date.toISOString();
  }
 
  this.dateId='';
  this.contactService.getDeviceByFilter(this.emailid,this.useridd,this.groupId,this.status,this.statuss,this.skip,this.limit,this.myInput,this.supAdm,this.DealerID,dateObj,this.liecenceStatus).subscribe(
      
    data => {
    
      this.devicess = data 
      this.final = this.devicess.devices
      // console.log("IN GET DEV",this.final);

      
     for(let i=0;i<this.devicess.devices.length;i++){
     
       if(this.devicess.devices[i].type_of_device =="Tracker"){
         let a ={
          value : this.devicess.devices[i].Device_Name,
          viewValue:this.devicess.devices[i].Device_Name
         }
         foods.push(a);
       }
    
     }
     this.abc(this.final);
    });
  

}

ign(){
  this.router.navigateByUrl("device-report/ign-report");

}
mb:any;
logoutbut:boolean;
dealer:boolean;
logo:any;
text:any;
data_to_view=[];
Durations:any;
superAdmin:Boolean = false;
socket_Ing:any;
dealerTocust:any;
 

  
/*   this.socket = io.connect('https://13.126.36.205:5000');
  this.socket.on('connect', function(){
    console.log("IO Connected");
  
  }); */
  deviceData=[];
  arrival_time:any;
  baba=[]
  status_toShow:any;
  address_show:any;
  lattitude:any;
  longitude:any;


  

  abc(div){
  // console.log("deviceObj=>",div)
  var that = this;
   this.baba=[];
   this.deviceData=div;
   var outerThis = this;
   var start_add:any;
  //  console.log("Initial Value",this.deviceData);

    for(var j=0;j<this.deviceData.length;j++){
     
      if(this.deviceData[j].status_updated_at==undefined){
       let  dev_status_1= this.deviceData[j].status?this.deviceData[j].status:"Not available";
       this.deviceData[j].status  =  dev_status_1 ;
      //  console.log("Not Available !!!");
      }else{
         
          // this.arrival_time = new Date(this.deviceData[j].status_updated_at)

          let  dev_status= this.deviceData[j]?this.deviceData[j].status:"NA";
           
        
            // var curr_time= new Date();
            // var fd = new Date(this.arrival_time).getTime();
            // var td = curr_time.getTime();
            // var timedev_status_difference = td-fd;
            // var total_min = timedev_status_difference/60000;
            // var hours = total_min/60
            // var rhours = Math.floor(hours);
            // var minutes = (hours - rhours) * 60;
            // var rminutes = Math.round(minutes);
          
            // this.Durations = rhours + " "+'hrs'+ " " +  rminutes + " " + 'min';      
            // // console.log("vehicle=>",this.Durations)

            
        // new conversion logic
        var curr_time:any = new Date();
        this.arrival_time = new Date(this.deviceData[j].status_updated_at);
        var fd:any = new Date(this.arrival_time);
        // console.log('curr_time',curr_time,this.arrival_time);
        var diffInMilliSeconds= Math.abs(curr_time - fd) / 1000;

        // calculate days
        const days = Math.floor(diffInMilliSeconds / 86400);
        diffInMilliSeconds -= days * 86400;
        // console.log('calculated days', days);
    
        // calculate hours
        const hours = Math.floor(diffInMilliSeconds / 3600) % 24;
        diffInMilliSeconds -= hours * 3600;
        // console.log('calculated hours', hours);
    
        // calculate minutes
        const minutes = Math.floor(diffInMilliSeconds / 60) % 60;
        diffInMilliSeconds -= minutes * 60;
        // console.log('minutes', minutes);
    
        let difference = '';
        if (days > 0) {
          difference += (days === 1) ? `${days} day, ` : `${days} days, `;
        }
    
        difference += (hours === 0 || hours === 1) ? `${hours} hour, ` : `${hours} hours, `;
    
        difference += (minutes === 0 || hours === 1) ? `${minutes} minutes` : `${minutes} minutes`; 
    
   // new conversion logic
          this.Durations = difference ; 
            if(dev_status==undefined){
              
              this.status_toShow = "NA";
    
            }else{
              this.status_toShow = dev_status + " " + "Since" +" "+ this.Durations;
            }
    
            this.deviceData[j].status  =  this.status_toShow ;
      }
   
    }
      // datatable will be called from here
     
      if(this.tableFlag === true){
        this.testTable(); 
    
      }else{
       
         this.tabelObj.clear();
         this.tabelObj.rows.add(this.deviceData); 
         this.tabelObj.draw();      
       
      }
      this.tableFlag = false;

 }



  // getExpvehData(expiredVeh,$event){
  //   // console.log(expiredVeh,$event)
  //   var status = expiredVeh;
  //   var Expstatus = 0;
  //   this.Load =true;
  //   this.contactService.getExpVehDetails(this.useridd,this.emailid,status,Expstatus,this.limit,this.myInput,this.supAdm,this.DealerID)
  //     .subscribe(res=>{
  //       this.Load = false;
  //       // console.log(res);
  //       this.final = res.devices;
  //       this.abc(this.final)

  //     },err=>{
  //       this.Load =false;
  //       swal(
  //         'Error',
  //         'Internal Server error, Please try aftersometime !!!',
  //         'error'
  //       )

  //     })
  // }


  firstcall:boolean=false;
  lastcall:boolean=true;
  next() {
    this.deviceData =[];
    this.lastcall=false;
    this.skip += 1; 
    // this.sidebarData();
    this.ngOnInit();
  }
  pre() {
    this.deviceData=[]
    // console.log(this.skip)
    if(this.skip>0){
      this.skip -= 1;   
      this.lastcall=false;
      // this.sidebarData();
      this.ngOnInit();
    }else{
      this.lastcall=true;
      this.firstcall=false;
    }
   
  }

  licenceStatus(ev){
    // console.log(this.liecenceStatus,ev);
    this.getdev();
    
  }

  selectedStatus(ev,ind){
    // this.statusArray[ind].status = !this.statusArray[ind].status;
    this.Status_name = ev.value;
    // console.log('indindindindindindindindindindindindind',this.Status_name);
   
      this.getdev();
    
    // if(this.statusArray[ind].status){
    //   this.Status_name.push(this.statusArray[ind].value);
    //   this.getdev();

    // }
    // else{
    //   this.Status_name.splice(this.Status_name.indexOf(this.statusArray[ind].value),1);
    //   this.getdev();
    // }

    // console.log('this.Status_name',this.Status_name);
  }

  // deviceSetting(deviceObj){
  //   console.log("clicked",deviceObj);
  //   let dialogRef = this.dialog.open(GeneralSettingsComponent, {
    
  //     data: { device :deviceObj}
  //   });
  
  //   dialogRef.afterClosed().subscribe(result => {
  //     console.log(result);
  //     if(result == 'cancelled'){
  //       this.ngOnInit();
  //     }
  //   })
  // }

  showMenu = environment.showLandingpageMenu;
  showDemoVideo(){
    let split1 = document.URL.split('//')[1];
    // console.log(split1,document);
    let split2 = split1.split('/')[0];
    let splitForStyle = split1.split('/')[1];
    this.url =  split2;
    // console.log("split2",this.url);
      for(var i = 0; i <this.showMenu.length;i++){
        if (this.url == 'www.oneqlik.in') {
          this.showNav = true;
            return;
        } else {
          this.showNav = false;
        }
      }
  
  }


  // datatable work starts here
  devStatus:any;
  tabelObj
  // tabelObj=$('#deviceTable1').DataTable(); 
  callfunction(): void {
    // console.log(this.deviceData);
    this.tabelObj.draw();
}

testTable() {
  const that = this;
  $(document).ready(function() { 
    // console.log("called on every click");
      that.tabelObj = $('#deviceTable1').DataTable({   
          "serverSide": false,
          "processing": false,
          "paging" :false,
          "searching": false,
          'deferRender':true,
          "autoWidth": true,
          "bInfo" : false,
          "scrollX": true,
          "scrollY":540,      
          "order": [[0, "desc"]],
          "scrollCollapse": true,
          'responsive':true,
          // "fixedColumns": {
          //   leftColumns: 2,
          // },    
          lengthMenu: [[10, 25, 50, 100,200,500], [10, 25, 50, 100,200,500]],
          "pageLength": 25,
          "data" : that.deviceData,      
          "rowCallback": function(row: Node, data: any | Object, index: number){     
            $('#deviceSetting', row).bind('click', () => {  
          
              let dialogRef = that.dialog.open(GeneralSettingsComponent, {    
                data: { device :data}
              });
            
              dialogRef.afterClosed().subscribe(result => {
                // console.log(result);
                if(result == 'cancelled'){
                  that.ngOnInit();
                }
              })  
             
              
            }); 
            $('#speedAlert', row).bind('click', () => {    
            
              
            }); 
            $('#shareDevice', row).bind('click', () => {    
              // openDialog3(a,b){
                // console.log(data);
                var dname = data.Device_Name;
                var devid= data._id;
                let dialogRef = that.dialog.open(DeviceShareComponent, {
                 
                  width: '528px',
                  data: { name: dname , did:devid}
                });
              
                dialogRef.afterClosed().subscribe(result => {
                  // console.log(result);
                  if(result == "OK"){
                    that.tost1("share");
                    window.localStorage['DataUpdate'] = 'True';
                    // that.sidebar.sidebarData(); 
                  }
                });
              // }
             
              
            }); 
            $('#shareUser', row).bind('click', () => {   
              var vehid = data._id;
              var dname = data.Device_Name;
              var vehID = data.Device_ID; 
              let dialogRef = that.dialog.open(ShareUserComponent, {
                width: '528px',
                data: { name: vehid, dname:dname, did:vehID}
              });      
              dialogRef.afterClosed().subscribe(result => {
                
                // console.log(result);
                if(result == "OKK"){
                  that.tost1("removeuser");
                  window.localStorage['DataUpdate'] = 'True';
                  // that.sidebar.sidebarData(); 
                }
                else if(result == "No_Dev"){
                  that.tost1("No_Dev");
            
                }
              });
             
             
            }); 

            $('#edit', row).bind('click', () => {   
              var internalThat  = that;
              // console.log('rowrowrowrow=>',row);
              // console.log('datadatadatadata',data);

              if(that.bussinessType=='1'){
                localStorage.setItem('deviceData',JSON.stringify(data))
                that.router.navigate(['/editDevice']);
              }else{
                let dialogRef = that.dialog.open(DeviceEditComponent, {
                  width: '950px',
                  // height: '1160px',   
                  data: { _id: data._id, des: data.Device_Des, sim:data.sim_number, dname:data.Device_Name, speed:data.SpeedLimit,iconType:data.iconType,
                    drname:data.driver_name,dcontact:data.contact_number,expdate:data.expiration_date,model:data.maxSpeed,mainmodel:data.device_model,
                    assigned_to:data.user,vehicleType:data.vehicleType,devIMEI:data.Device_ID,S_provider:data.sim_provider,tot_ODO:data.total_odo,
                    itiId:data.integrationId,simNUM2:data.sim_number2,simProvider2:data.sim_provider2,devObj:data,
                    distanceVariation:data.distanceVariation?data.distanceVariation:null,sellsPerson:data.sellsPerson?data.sellsPerson:null,
                  installer:data.installer?data.installer:null}
                  
                });
            
                dialogRef.afterClosed().subscribe(result => {
                  // console.log("result",result);
                  that.ngOnInit();
               
                    if(result=="done"){
                      // console.log("resultdone",result)
                      that.tost1("update");
                      window.localStorage['DataUpdate'] = 'True';
                      // that.sidebar.sidebarData();       
                    }
                });              

              }
          
            }); 
            $('#renewalHistory',row).bind('click',()=>{
              // console.log(data);
              let dialogRef = that.dialog.open(RenewalHistoryComponent, {
                width: '950px',
                // height: '1160px',   
                data: { _id: data._id, des: data.Device_Des, sim:data.sim_number, dname:data.Device_Name, speed:data.SpeedLimit,iconType:data.iconType,drname:data.driver_name,dcontact:data.contact_number,expdate:data.expiration_date,model:data.maxSpeed,mainmodel:data.device_model,assigned_to:data.user,vehicleType:data.vehicleType,devIMEI:data.Device_ID,S_provider:data.sim_provider,tot_ODO:data.total_odo,itiId:data.integrationId,simNUM2:data.sim_number2,simProvider2:data.sim_provider2,devObj:data,distanceVariation:data.distanceVariation?data.distanceVariation:null}
                
              });

              dialogRef.afterClosed().subscribe(result => {

              })
              
            });

             $('#echalan',row).bind('click',()=>{
              // console.log(data);
              let dialogRef = that.dialog.open(EChalanComponent, {
                // width: '950px',
                // height: '1160px',   
                data: { _id: data._id, dname:data.Device_Name}
                
              });

              dialogRef.afterClosed().subscribe(result => {

              })
              
            });
            $('#certificate',row).bind('click',()=>{
              // console.log(data);
              var docs=data
              // var  that =this;
    docs.ID = 'viewDoc',
    docs.hide=true;
    // console.log(docs);
    let dialogRef = that.dialog.open(DeviceDocComponent, {
      width: '900px', 
      // height:'900px',
      data: { dealer_payload: docs }
    });

              dialogRef.afterClosed().subscribe(result => {

              })
              
            });
             $('#certificate1',row).bind('click',()=>{
              that.exportCertificate(data)
              
            });

            $('#delete', row).bind('click', () => {   
                swal({
                  title: 'Are you sure?',
                  text: "You won't be able to revert this!",
                  type: 'warning',
                  showCancelButton: true,
                  confirmButtonColor: '#3085d6',
                  cancelButtonColor: '#d33',
                  confirmButtonText: 'Yes, delete it!'
                }).then((result: { value: boolean; }) => {
                  if (result) {
                    that.Load =true;
                    var req={
                      device:data.Device_ID,
                      userId:that.useridd
                    }
                    that.contactService.deldev(req)
                    .subscribe(
                      data => {
                                   
                        swal(
                          'Deleted',
                          'Device Deleted',
                          'success'
                        )
                        that.dev  = data 
                        var dateObj = {}
                        that.contactService.getDeviceByFilter(that.emailid,that.useridd,that.groupId,that.status,that.statuss,that.skip,that.limit,that.myInput,that.supAdm,that.DealerID,dateObj,that.liecenceStatus).subscribe(
                      
                          data => {
                            that.devicess = data    
                            // console.log("1111111111111111111")
                            that.final = (that.devicess.devices);
                            that.Load =false
                            that.tost1("delete");
                            window.localStorage['DataUpdate'] = 'True';
                            // that.sidebar.sidebarData();     
                          }, (err: any) => { 
                            // console.log(err);
              
                          if(err.status !=200)
                          {
                             that.Load =false
                          }
                          that.Load =true;
                        });  
                      },err=>{
                        if(err.status==401){
                          swal(
                            "Access Denied !!"
                          )
                        }else{

                          swal(
                            'Error',
                            'Internal Server Error, Please try after sometime !!!',
                            'success'
                          )
                        }
                      })    
                  }
                })
            }); 

              },
          "columns": [
            {
              "data": "_id",
              "visible" :false,
              "defaultContent": "",
              "render": function(data, type, row) {
                  return data ? data : "";
              }
          },
              {
                  "data": "Device_Name",
                  "defaultContent": "",
                  "render": function(data, type, row) {
                      return data ? data : "";
                  }
              },
              {
                  "data": "vehicleGroup",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    var grp ='';
                    if(data){
                        grp = data.name ; 
                    }
                
                      return grp;
                  }
              },
              {
                  "data": "Device_ID",
                  "defaultContent": "",
                  render: function(data, type, row) {
                      return data ? data : "";
                  }
              },
              {
                  "data": "integrationId",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    var intid = '';
                    if(data){
                      intid = data;
                    }
                      return intid;
                  }
              },
              {
              "data": "sim_number",
              "defaultContent": "",
               render: function(data, type, row) {
                  return data ? data : "";
                  }
              },
              {
                  "data": "sim_provider",
                  "defaultContent": "",
                  render: function(data, type, row) {
                      return data ? data : "";
                  }
              },
              {
                  "data": "sim_number2",
                  "defaultContent": "",
                  "render": function(data, type, row) {
                      return data?data:'';
                  }
              },
              {
                  "data": "sim_provider2",
                  "defaultContent": "",
                  "render": function(data, type, row) {
                    return data?data:'';
                  }
              },
              {
                  "data": "device_model",
                  "defaultContent": "",
                  "render": function(data, type, row) {
                    return data?data.device_type:"NA"
                  }
              },
        
              {
                  "data": "vehicleType",
                  "defaultContent": "",
                  "render": function(data, type, row) {
                    // console.log('vehicleType',data);
                  return  data ? (data.brand + " " + data.model):'NA'
                   
                  }
              },
              {
                  "data": "status",
                  "defaultContent": "",
                  "render": function(data, type, row) {
                      return data ? data : "";
                  }
              },
              {
                  "data": "user",
                  "defaultContent": "",
                  "visible" :true,
                  "render": function(data, type, row) {
                 
                    var fn = data?data.first_name:'-' ; 
                    var ln = data?data.last_name:'-'
                    return fn + ' ' + ln ;
                  }
              },     
              {
                "data": "created_by",
                "defaultContent": "",
                "visible" :true,
                "render": function(data, type, row) {
             
                  var fn1 = data?data.first_name:'-' ; 
                  var ln1 = data?data.last_name:'-'
                  return fn1 + ' ' + ln1 ;
                }
            },     
            {
                "data": "Dealer",
                "defaultContent": "",
                "visible" :true,
                "render": function(data, type, row) {
             
                  var fn1 = data?data.first_name:'-' ; 
                  var ln1 = data?data.last_name:'-'
                  return fn1 + ' ' + ln1 ;
                }
            },
            {
              "data": "created_on",
              "defaultContent": "",
              "visible" :true,
              "render": function(data, type, row) {
                var createdDate = new Date(data);
                return data ? (moment(createdDate).format('LL')) : "";   
              }
          },     
            {
              "data": "expiration_date",
              "defaultContent": "",
              "visible" :true,
              "render": function(data, type, row) {         
                  var expDate = new Date(data);
                  return data ? (moment(expDate).format('LL')) : "";   
              }
          },
          {
              "data": "renew_at",
              "defaultContent": "",
              "visible" :true,
              "render": function(data, type, row) {         
                  var expDate = new Date(data);
                  return data ? (moment(expDate).format('LL')) : "";   
              }
          },
          {
              "data": "renew_by",
              "defaultContent": "",
              "visible" :true,
              "render": function(data, type, row) { 
                if(data){
                  var name =(data.first_name?data.first_name:'')+' '+(data.last_name?data.last_name:'');
                  return name ? name : "";   
                }else ''        
              }
          },     
          {
            "data": "driver_name",
            "defaultContent": "",
            "render": function(data, type, row) {
                return data ? data : "";
            }
        },
        {
            "data": "contact_number",
            "defaultContent": "",
            "render": function(data, type, row) {
                return data ? data : ""
            }
        },

        {
            "data": "sellsPerson",
            "defaultContent": "",
            "render": function(data, type, row) {
                return data ? data : ""
            }
        },
        {
            "data": "installer",
            "defaultContent": "",
            "render": function(data, type, row) {
                return data ? data.first_name+' '+data.last_name : ""
            }
        },
         {
            "data": "last_ping_on",
            "defaultContent": "",
            "render": function(data, type, row) {
                 var expDate = new Date(data);
                  return data ? (moment(expDate).format('lll')) : ""; 
            }
        },
              {
                  "data":null,
                  "defaultContent": "",
                  "render":function(data,type,row){                      
                    return '<i id="deviceSetting" style="font-size:20px" title="Share device" class="fas fa-cog"></i>'
              }
          } , 
      {
          "data":null,
          "defaultContent": "",
          "render":function(data,type,row){    
              return '<i id="shareDevice" title="Share device" style="font-size:20px" class="fas fa-share-alt"></i>'              
          }  
  },
  {                
      "data":null,
      "defaultContent": "",
      "render":function(data,type,row){
       
          return '<i id="shareUser" title="Share user" style="font-size:20px" class="fas fa-share"></i>'           
      }
  }, 
  {
    "data":null, 
    "defaultContent": "",
    "render":function(data,type,row){   
      return '<i id="renewalHistory" title="Show Renewal History" style="font-size:20px;color:green" class="fas fa-history"></i>'     
}
},
 
      {
          "data":null,
          "defaultContent": "",
          "render":function(data,type,row){   
            return '<i id="edit" title="Edit Vehicle" style="font-size:20px;color: green" class="fas fa-edit"></i>'    
      }
  } ,   
  {
    "data":null, 
    "defaultContent": "",
    "render":function(data,type,row){   
      if(row.kycStatus) {
        if(row.kycStatus=="Approved") {
          return '<i  title="Unable to delete" style="font-size:20px;color:gray;cursor: not-allowed;" class="fas fa-trash-alt"></i>'  
  
        }else{
           return '<i id="delete" title="Delete Vehicle" style="font-size:20px;color:red" class="fas fa-trash-alt"></i>'
        }
      }else{
           return '<i id="delete" title="Delete Vehicle" style="font-size:20px;color:red" class="fas fa-trash-alt"></i>'
      }
          
}
  },

   {
    "data":null, 
    "defaultContent": "",
    "render":function(data,type,row){   
      return '<i id="echalan" title="Delete Vehicle" style="font-size:20px;color:red" class="fas fa-ticket-alt"></i>'     
}
  },
  {
    "data":null, 
    "defaultContent": "",
    "render":function(data,type,row){   
      return '<i id="certificate" title="Documents" style="font-size:20px;color:red" class="fas fa-file"></i>'     
    }
    },
{
    "data":null, 
    "defaultContent": "",
    "render":function(data,type,row){ 
      if(row.kycStatus) {
        if(row.kycStatus=="Approved") {
          return '<i id="certificate1" title="Download Certificate" style="font-size:20px;color:red" class="fas fa-download"></i>'     
  
        }else{
          return '<i  title="Please approve kyc to Download certificate" style="font-size:20px;color:gray;cursor: not-allowed;" class="fas fa-download"></i>'
        }
      }else{

      }
}
  },
  {
    "data":null, 
    "defaultContent": "",
    "render":function(data,type,row){ 
      if(row.remark) {
       return row.remark
      }
  }
},
   {
    "data":null, 
    "defaultContent": "",
    "render":function(data,type,row){   
      var str
      if(row.kycStatus==undefined || row.kycStatus=='Pending'){
        str="<button class='btn btn-warning btn-sm' style='border-radius: 40px; font-size: x-small;'>Pending</button>"
      }else if(row.kycStatus=="Approved"){
        str="<button class='btn btn-success btn-sm' style='border-radius: 40px; font-size: x-small;'>Approved</button>"
      }else{
        str="<button class='btn btn-danger btn-sm' style='border-radius: 40px; font-size: x-small;'>Rejected</button>"
      }
          // <button class="btn btn-warning btn-sm"
          //   style="border-radius: 40px; font-size: x-small; background-color: orange;"
          //   *ngIf="cust_array.kycStatus=='Pending'">{{cust_array.kycStatus}}</button>
          // <button class="btn btn-success btn-sm"
          //   style="border-radius: 40px; font-size: x-small; background-color: green;"
          //   *ngIf="cust_array.kycStatus=='Approved'">{{cust_array.kycStatus}}</button>
          // <button class="btn btn-danger btn-sm" style="border-radius: 40px; font-size: x-small; background-color: red;"
          //   *ngIf="cust_array.kycStatus=='Reject'">{{cust_array.kycStatus}}</button>
      
      
      return str
      // '<i id="certificate" title="Documents" style="font-size:20px;color:red" class="fas fa-file"></i>'     
    }
    },
                 
          ],

      
            "columnDefs": [
              { className: "dt-body-left", "targets": [ 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34] },
              // { width: '20%', targets: 0 } ,
             
            ]
      
      });
    //   $('#deviceTable').on( 'length.dt', function ( e, settings, len ) {
    //     console.log( 'New page length: '+len );
    //     that.customDatafilter = true;
    //     this.skip = 0;
    //     that.limit = len;
    //     that.getdev();

      
    // });
    // that.testGround()
  
      that.colSwitch()
   
  });


}

exportCertificate(data){
  
                        data.actionId = "exportPdf";

                        data.OwnerName = JSON.parse(JSON.stringify(data)).user.first_name + " " + JSON.parse(JSON.stringify(data)).user.last_name;
                        //   data.Dealer_name = JSON.parse(JSON.stringify(data))
                        var fstname = (JSON.parse(JSON.stringify(data)).Dealer != undefined) ? JSON.parse(JSON.stringify(data)).Dealer.first_name : "";
                        var lsname = (JSON.parse(JSON.stringify(data)).Dealer != undefined) ? JSON.parse(JSON.stringify(data)).Dealer.last_name : "";
                        var dlraddress = (JSON.parse(JSON.stringify(data)).Dealer != undefined) ? JSON.parse(JSON.stringify(data)).Dealer.address : "";
                        data.Dealer_name = fstname + " " + lsname;
                        data.DealerAddress = dlraddress;data.deviceImage=data.deviceImage
                        let dialogRef
                        if(this.bussinessType=="1"){
                            dialogRef = this.dialog.open(DownloadCertificateComponent, {
                              data: { "deviceInfo": data },
                              width:'950px'
                          });
                        }else{
                          dialogRef = this.dialog.open(ViewCertificateComponent, {
                              data: { "deviceInfo": data }
                          });

                        }


                        dialogRef.afterClosed().subscribe(result => {
                            // console.log(result);

                            // if (result == "advance") {
                            //     let dialogRef_1 = this.dialog.open(EditDeviceMasterComponent, {
                            //         data: { "deviceInfo": data },
                            //         width: '650px',
                            //         height: '700px',
                            //     });
                            // }

                            // if (result == "basic") {
                            //     let dialogRef_2 = this.dialog.open(NormalCertComponent, {
                            //         data: { "deviceInfo": data }
                            //     });
                            // }
                        })
}

// testGround(){
//     var aaaaaaaa= new $.fn.datatable.FixedColumns(this.tabelObj, {
//       leftColumns: 4
//      });
  
//      console.log('aaaaaaaa',aaaaaaaa);  


 
// }




 colSwitch(){

      // this.tabelObj.column( 22 ).visible( false );
      this.tabelObj.column( 29).visible( false );
      this.tabelObj.column( 31 ).visible( false );
      this.tabelObj.column( 32 ).visible( false );
      this.tabelObj.column( 33 ).visible( false );
      this.tabelObj.column( 28 ).visible( false );
      this.tabelObj.column( 26).visible( false ); 
      this.tabelObj.column( 27).visible( false ); 
       this.tabelObj.column( 34 ).visible( false );
        if((this.superAdmin ==true)||(this.custtype ==true)||(this.dealerTocust=='ON')){
          // this.tabelObj.column( 22 ).visible( true );
          this.tabelObj.column( 28).visible( true );       
          this.tabelObj.column( 29).visible( true ); 
         
          this.tabelObj.column( 26).visible( true );
          this.tabelObj.column( 27).visible( true );
          this.tabelObj.column(15).visible( true );
          this.tabelObj.column( 13).visible( true ); 
           
          if(this.bussinessType=='1'){
            this.tabelObj.column( 31 ).visible( true );
            this.tabelObj.column( 32 ).visible( true );
            this.tabelObj.column( 33 ).visible( true );
            this.tabelObj.column( 34 ).visible( true );
          }
        }

        if((this.superAdmin ==false)&&(this.custtype ==false)){
          this.tabelObj.column( 9 ).visible( false );
                                     
        }
    }

    tab:any;

  exportExcel1() {

    var data = this.devicess.devices

    for (var i = 0; i < data.length; i++) {
      data[i].device_models = data[i].device_model ? data[i].device_model.device_type ? data[i].device_model.device_type:"N/A":"N/A"
      data[i].kycApprovalDate = data[i].kycApprovalDate ? moment(data[i].kycApprovalDate).format('LL') : "N/A"
      if (data[i].Dealer){
        var pin = data[i].user.pin ? data[i].user.pin : ""
        var address = data[i].user.address ? data[i].user.address : ""
        var name = data[i].Dealer.first_name ? data[i].Dealer.first_name : ""+" " + data[i].Dealer.last_name ? data[i].Dealer.last_name : ""
        data[i].dealerName = name;
       

      
      }
      if (data[i].user) {
        var name1 = data[i].user.first_name ? data[i].user.first_name : "" + " " + data[i].user.last_name ? data[i].user.last_name : ""
        data[i].customerName = name1;
        
        data[i].customerId = data[i].imageDoc[0] ? data[i].imageDoc[0].phone ? data[i].imageDoc[0].phone : "" :""
      }
      var pin = data[i].user.pin ? data[i].user.pin : ""
      var address = data[i].user.address ? data[i].user.address : ""
      data[i].address = address;
      data[i].pin = pin;
      if(i==data.length-1){
        this.downloadFile(this.devicess.devices);
      }
      // this.exportAsExcelFile(this.devicess.devices, 'sample');
      // const workBook = XLSX.utils.book_new(); // create a new blank book
      // const workSheet = XLSX.utils.json_to_sheet(this.devicess.devices);

      // XLSX.utils.book_append_sheet(workBook, workSheet, 'data'); // add the worksheet to the book
      // XLSX.writeFile(workBook, 'temp.xlsx'); // initiate a file download in browser

    }
  }

    exportAsExcelFile(json: any[], excelFileName: string): void {
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
    const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }
   saveAsExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], { type: EXCEL_TYPE });
    fileSaver.saveAs(data, fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
  }

    // this.downloadFile(this.devicess.devices);
  

  downloadFile(data, filename = 'Vehicle List') {
    console.log(data);
    
    let arrHeader = ["Device_ID", "kycApprovalDate", "vahanID", "device_models", "IccidNo", "sim_number", "sim_number2", "SIM and SIM to TSP",  "dealerName",
      "CID_No","customerId","customerName", "phone", "manufacturingCompany", "Model", "vehicleCategory", "ChassisNo", "engineNo", "Device_Name", "transportOfficeCity", "transportOfficeState", "pin", "rto", "spare", "spare", "address"];
    let csvData = this.ConvertToCSV(data, arrHeader);
    let blob = new Blob(['\ufeff' + csvData], { type: 'text/csv;charset=utf-8;' });
    // const file = new File([blob], 'report.xlsx',
    //   { type: 'application/vnd.ms-excel' });

    // fileSaver.saveAs(file);
    let dwldLink = document.createElement("a");
    let url = URL.createObjectURL(blob);
    let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
    if (isSafariBrowser) {  //if Safari open in new window to save file with random filename.
      dwldLink.setAttribute("target", "_blank");
    }
    dwldLink.setAttribute("href", url);
    dwldLink.setAttribute("download", "Vehicle List.csv");
    dwldLink.style.visibility = "hidden";
    document.body.appendChild(dwldLink);
    dwldLink.click();
    document.body.removeChild(dwldLink);
  }
  ConvertToCSV(objArray, headerList) {
    let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    let str = 'Vehicle List \r\n \r\n'
    let row = 'S.No,';
    let newHeaders = ["Device IMEI", "Date of KYC approval", "Vahan ID", "Device Model", "ICCID NO", "SIM1", "SIM2", "SIM and SIM to TSP", "Dealer name",
      "Follow-up number","Customer ID","Customer Name", "Mobile No", "vehicle manufacturer", "Vehicle Model", "Vehicle Category", "Chassis No", "Engine No", "Vehicle No", "CITY", "State", "PIN","RTO","spare","spare","ADDRESS"];

    for (let index in newHeaders) {
      row += newHeaders[index] + ',';
    }
    row = row.slice(0, -1);
    str += row + '\r\n';
    for (let i = 0; i < array.length; i++) {
      let line = (i + 1) + '';
      if (i < array.length) { }
      for (let index in headerList) {
        let head = headerList[index];
        line += ',' + this.strRep(array[i][head]);
      }
      str += line + '\r\n';

    }
    return str;
  }

  strRep(data) {

    if (typeof data == "string") {
      let newData = data.replace(/,/g, " ");
      return newData;
    }
    else if (typeof data == "undefined") {
      return "-";
    }
    else if (typeof data == "number") {
      return data.toString();
    }
    else {
      return data;
    }
  }

    exportExcel() {
 
 
      var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
      var textRange; var j=0;
      this.tab = document.getElementById('deviceTable1'); // id of table
   
      // console.log(this.tab.rows.length)
      var rowlength = 4; 
      if((this.superAdmin ==true)||(this.custtype ==true)||(this.dealerTocust=='ON')){
        var rowlength = 6; 
      }

  
      for(j = 0 ; j < this.tab.rows.length; j++) 
      {    
       
          tab_text=tab_text+this.tab.rows[j].innerHTML+"</tr>";
          //tab_text=tab_text+"</tr>";
      }
      $('table tr').find('td:eq(20),th:eq(20)').remove();
      $('table tr').find('td:eq(21),th:eq(21)').remove();
      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
      // tab_text= tab_text.replace(/<th>Edit</th>/gi, ""); // reomves input params
      
      // console.log(tab_text);
  
      var ua = window.navigator.userAgent;
      var msie = ua.indexOf("MSIE "); 
  
      var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  
  
      return (sa);
  }

  dateChange(id){
    // console.log(id);
    // console.log("Inside function");
    this.dateId = id;
    this.getdev();
 
  }
  pageLength:any;
  pageLengthArr=[10,25,50,100,200,500,"All"];
  callDataTable(){
    this.customDatafilter = true;
    this.skip = 0;
    // that.limit = len;
    this.getdev();
  }

  getSuperAdminList(){
    // console.log("KJDKJDKJKDJKJKDJD");
    
    this.contactService.getSuperAdminList().subscribe(res=>{
      // console.log(res);
      this.distributers=res;
       var loadinguser1 = {
              user_type: "All",
              _id: "All User"
            }
            for(var i=0;i<this.distributers.length;i++){
              loadinguser1 = {
                user_type:  this.distributers[i].first_name + " " + this.distributers[i].last_name,
                _id: this.distributers[i]._id
              }
              this.disDataFIlter.push(loadinguser1);
            }
      
    })
  }

  distributerSelect = [];
  filterStates(usr1) {
    // console.log("userObj=>",usr);
    if(usr1.length == 0){
      this.distributerSelect =[];
    }
    
    if (usr1) {
      // console.log("user=>",usr1);
      const filterdealerValue:any = usr1;
      this.distributerSelect=[];
       this.distributerSelect = this.disDataFIlter.filter(function(ppp){
      //  console.log(ppp);
       
        var t = ppp.user_type.indexOf(filterdealerValue);
      //  this.option = this.options[i];
      // console.log("India1");
        return t > -1;    
      });
        // console.log(this.distributerSelect);
        // if(this.distributerSelect.length==this.disDataFIlter.length){
        //   this.getdev()
        // }
        if(this.distributerSelect.length === 1){
          this.getSuperAdminVehicles(this.distributerSelect);

        }else{
          this.getdev()
        }
        return this.distributerSelect;
    }
  
  }


  getSuperAdminVehicles(data){

    let foods = [];

  // console.log("statusName = > ", this.Status_name);
  if(this.Status_name != null){
    // console.log();
    this.statuss = this.Status_name;
  }

  var dateObj = {};
 
  if((this.dateId == 'todate')||(this.to_date != undefined)){
      dateObj['to_date'] = this.to_date.toISOString();

  }
  if((this.dateId == 'fdate')||(this.from_date != undefined)){
    dateObj['from_date'] = this.from_date.toISOString();
  }
 
  this.dateId='';
  this.contactService.getDeviceByFilter(this.emailid,data[0]._id,this.groupId,this.status,this.statuss,this.skip,this.limit,this.myInput,data[0]._id,this.DealerID,dateObj,this.liecenceStatus).subscribe(
      
    data => {
    
      this.devicess = data 
      this.final = this.devicess.devices
      // console.log("IN GET DEV",this.final);

      
     for(let i=0;i<this.devicess.devices.length;i++){
     
       if(this.devicess.devices[i].type_of_device =="Tracker"){
         let a ={
          value : this.devicess.devices[i].Device_Name,
          viewValue:this.devicess.devices[i].Device_Name
         }
         foods.push(a);
       }
    
     }
     this.abc(this.final);
    });
  
  }

  adddevnew(){
     this.router.navigate(["/add_newDevice"]);
   
  }
}
