import { Component, OnInit, ViewChild } from '@angular/core';
import { Contact } from '../contact';
import { ContactService } from '../contact.service';
import {MdSnackBar} from '@angular/material';
// import {Md5} from 'ts-md5/dist/md5';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { MdDialog, MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { FlashMessagesService } from 'angular2-flash-messages';
import { AddCustComponent } from '../add-cust/add-cust.component';

import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/debounceTime';
import { EditCostumerComponent } from '../edit-costumer/edit-costumer.component';
import { ReportService } from '../report/report.service';

declare var swal: any;
@Component({
  selector: 'app-kyc-approval',
  templateUrl: './kyc-approval.component.html',
  styleUrls: ['./kyc-approval.component.scss']
})
export class KycApprovalComponent implements OnInit {
 modelChanged: Subject<string> = new Subject<string>();
  status
  isCustomerKYC:Boolean=false;
  kycStatus=[{Name:'Approved',value:'Approved'},{Name:'Reject',value:'Reject'},{Name:'Pending',value:'Pending'}]
  dealerChk: boolean = false;
  ev: any;
  show1: boolean = false;
  show2: boolean = true;
  show3: boolean = false;
  first_name: any;
  logoutbut: boolean;
  last_name: any;
  passwordd: any;
  org_name: any;
  allUser:boolean=false;
  emaill: any;
  phone: any;
  executed: any;
  $event2: any;
  dealer: any;
  contacts: Contact[] = [];
  contact: Contact;
  login1: any;
  mess2: any;
  mess: any;
  otp: any;
  switchVal: any;
  str: boolean = false;
  password2: any;
  cust_load: any;
  errmsg: boolean =true;
  serviceResponse: string;
  errorMsg: boolean;
  showNav: boolean =false;
  url: any;
  dealer_Permission: any;
  adbtn: string;
  myInput: string;
  report() {
    this.cond = false
    this.router.navigateByUrl("device-report");

  }
  clear() {
    this.first_name = ' '
    this.last_name = ' '
    this.emaill = null
    this.phone = null
  }
  before: any;
  emmnerr: any;
  Load: any
  $event: any;
  openDialog() {
  
        let dialogRef = this.dialog.open(AddCustComponent, {
          width: '800px',
        //  height: '600px', 
    
        });
    
        dialogRef.afterClosed().subscribe(result => {
          // console.log(result);
          if (result == "succ") {
            this.tost1("succ");
            this.ngOnInit();
    
          }
        });
  }



  constructor(private contactService: ContactService, public snackBar: MdSnackBar, private router: Router, private _flashMessagesService: FlashMessagesService, public dialog: MdDialog,private reportService:ReportService) {
    this.modelChanged
      .debounceTime(1000) // wait 300ms after the last event before emitting last event
      .distinctUntilChanged() // only emit if value is different from previous value
      .subscribe(myInput => {
        this.myInput = myInput;
        // console.log('debounce')
        // this.dealerDetail();
       
        this.ngOnInit();
      });

      var script = document.createElement("script");
      script.setAttribute("type", "text/javascript");
      script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
      document.getElementsByTagName("head")[0].appendChild(script);
  }

  data_descip: any;
  table1ch() {

    myFunction();
    function myFunction() {
      var input, filter, table, tr, td, i, td1;
      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      table = document.getElementById("myTable");
      tr = table.getElementsByTagName("tr");
      for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[1];
        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);
    // this.myInput;
    // console.log(this.myInput);
    // this.sidebarData()

  }
  tost1(divid) {
    if (divid == "EmM") {
      this.data_descip = this.emmnerr.split(":")[1]
      launch_toast();
    }
    else if (divid == "succ") {
      this.data_descip = "Custumer Successfully Added"
      launch_toast();
    }else if(divid == "reportPref"){
      this.data_descip = "Report Preference updated !!!"
      launch_toast();
    }else if(divid == "password_changed"){
      this.data_descip = "Password updated !!!";
      launch_toast();
    }else if(divid == "alertset"){
      this.data_descip = "Alert preference updated !!!";
      launch_toast();
    }else if(divid=="kyc"){
       this.data_descip = "KYC Status updated !!!";
      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", ""); }, 4500);
    }
  }

  changeStatus(ev){
    console.log(ev);
    this.getCustomer()

  }

  valclear() {
    this._flashMessagesService.show("Cleared", { cssClass: 'alert-warning', timeout: 2000 });

  }

  click1(event) {
    this.show2 = false;
    this.show3 = true;
    if ((event.keyCode >= 48 && event.keyCode <= 57) || event.keyCode == 9 || event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39) {
    }
    /* if(event.keyCode===13){
    this.otp_window();
    } */

    else
      event.preventDefault();
  }
  click2(event2) {
    this.show2 = true;
    this.show3 = false;

  }
  call(e) {
    {
      if (e.keyCode == 32) {
        e.preventDefault();
      }
    }
  }
  geo() {
    this.router.navigateByUrl("geofencing");

  }
  devicess: any;
  final: any;
 
   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++;
    }


  }
  run() {

  }

  devicesss: any;
  subscription: any;
  timer: any;
  messageSuccess: any = true;
  selectedlanguage :any; 



  fs: any;
  ls: any;
  emailid: any;
  or: any;
  useridd: any;
  custtype: any;
  custumer: any=[];
  mb: any;
  cust: boolean = false;
  logo: any;
  text: any;
  superAdmin: Boolean = false;
  ngOnInit() {

    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
      console.log('whatishere=>',this.superAdmin);
    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])).supAdmin;
    this.mb = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    let test = JSON.parse(window.atob(window.localStorage.token.split('.')[1]));
    this.dealer_Permission = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).cust_add_permission;

    // console.log(test);
    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.adbtn = localStorage.getItem("dlrchk");
    localStorage.setItem("dlrchk", this.custtype);
    //  this.getdev();
    if (this.custtype == true) {
      this.cust = true;
    }
    if (this.mb.charAt(0) == "n") {
      this.mb = ' '
    }
    if (window.localStorage['Custumer'] == 'ON') {
      this.logoutbut = false
      this.dealer = true
    }
    else {
      this.logoutbut = true
    }

    this.logo = window.localStorage['logo'];
    this.text = window.localStorage['text'];

 
    history.pushState(null, null, document.URL);
    window.addEventListener('popstate', function () {
      history.pushState(null, null, document.URL);
    });

    this.logo = window.localStorage['logo'];
    this.text = window.localStorage['text'];
    this.getCustomer();
  }


  getCustomer(){
     this.Load = true;  
    this.contactService.getCustumer1(this.useridd, this.skip, this.limit,this.myInput,this.allUser,this.status).subscribe(  
      data => {
        this.Load = false;
        this.custumer=[];
        this.custumer = data;
        for(var i=0;i<this.custumer.length;i++){
          if(this.custumer[i].adminAlert == undefined){
            this.custumer[i]['adminAlert'] = false;
          }
          if(this.custumer[i].dealerAlert == undefined){
            this.custumer[i]['dealerAlert'] = false;
          }
        }
        console.log("custDetail=>", this.custumer);
      }, err => {
        // console.log("errlog");
         this.Load = false;
        this.custumer=[];
        this.firstcall = true;
        this.lastcall = false;
      });
  }

  


 

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

  }
  

   viewDocuments(docs){
    console.log("Documents=>", docs);
    var  that =this;
    docs.ID = 'viewDoc';
    console.log(docs);
    let dialogRef = this.dialog.open(EditCostumerComponent, {
      width: '900px', 
      data: { dealer_payload: docs }
    });

    
    dialogRef.afterClosed().subscribe(result => {
      if (result == "yes") {
        this.getCustomer()
      }

      if (result == "no") {
     
      }
      if(result == 'imageupdated'){
        swal(
          'Updated',
          'Documents has been Updated.',
          'success'
        ) 
          this.ngOnInit();
      }
    });
  }

  custPhone(dlr){
  var dphn = '';
  if(dlr.std_code != undefined){
     dphn = '+' + dlr.std_code.dialcode + ' ' + dlr.phone ; 
     return dphn ; 
  }else{
     dphn = dlr.phone ; 
    return dphn ; 
  }
}

allUserFunction(ev){
  console.log('event=>',ev);
  this.allUser = ev.checked ;
   
    this.skip = 1;
    this.getCustomer(); 
}



changeKYC(data,event){
  console.log(event);
  var req={
    user:data._id,
    status:event
  }
  this.contactService.changeKycStatus(req).subscribe(res=>{
    console.log(res);
     this.tost1('kyc');
  })
  
}


tab:any;
  
  downloadExcel() {

    if(this.isCustomerKYC){
      this.Load = true;  
    this.contactService.get('/users/getCustomer?uid='+this.useridd).subscribe(  
      (data:any) => {
        this.Load = false;
       var custumer=[];
        custumer = data;
        for(var i=0;i<custumer.length;i++){
         
           custumer[i].fullName=custumer[i].first_name?custumer[i].first_name:''+" "+custumer[i].last_name?custumer[i].last_name:'';
          if(i==(custumer.length-1)){
  
            this.downloadFile(custumer);
          }
          }
        console.log("custDetail=>", custumer);
      }, err => {
        // console.log("errlog");
         this.Load = false;
        // custumer=[];
        // this.firstcall = true;
        // this.lastcall = false;
      });

    }else{
      this.reportService.downloadDeviceExcel(true);
    }


    
  }

  downloadFile(data) {
   
    let arrHeader = ["fullName", "email", "phone", "user_id","kycStatus","total_vehicle"];
    let csvData = this.ConvertToCSV(data, arrHeader);
    let blob = new Blob(['\ufeff' + csvData], { type: 'text/csv;charset=utf-8;' });
    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", "Customer List.csv");
    dwldLink.style.visibility = "hidden";
    document.body.appendChild(dwldLink);
    dwldLink.click();
    document.body.removeChild(dwldLink);
     this.Load = false;
  }
  ConvertToCSV(objArray, headerList) {
    let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    // console.log(array,"<===");Distance	126.94
// Running	2:1
// Idle	1:56
// Stop
    
    let str = 'Customer List \r\n';
    let row = 'S.No,';
// name,emial,phone,id,password and status no of vehicles
    let newHeaders =["Name", "Email", "Phone", "User id","Status","Number of Vehicle"];

    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;
    }
  }

 

logout() {
    window.localStorage.clear();
    this.router.navigateByUrl("login");
  }

  changeTab(type){
    if(type=="deviceKYC"){
      this.isCustomerKYC=false
    }else{
       this.isCustomerKYC=true
    }

  }

}
