import { Component, OnInit, ViewChild } from '@angular/core';
import { Contact } from '../../contact';

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 { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/debounceTime';
import { ContactService } from '../../contact.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { DeviceDocComponent } from '../device-doc/device-doc.component';
import { ReportService } from '../../report/report.service';
import { NormalCertComponent } from '../../device/normal-cert/normal-cert.component';
import { CertOptionComponent } from '../../device/cert-option/cert-option.component';
import { EditDeviceMasterComponent } from '../../device/edit-device-master/edit-device-master.component';
declare var swal: any;
import * as moment from 'moment';

@Component({
  selector: 'app-device-kyc',
  templateUrl: './device-kyc.component.html',
  styleUrls: ['./device-kyc.component.scss']
})
export class DeviceKYCComponent implements OnInit {
modelChanged: Subject<string> = new Subject<string>();
  status
  pageLengthArr=[10,25,50,100,200,500,"All"];
  state
  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;

  before: any;
  emmnerr: any;
  Load: any
  $event: any;
   Indianstate = [ "Andhra Pradesh",
                "Arunachal Pradesh",
                "Assam",
                "Bihar",
                "Chhattisgarh",
                "Goa",
                "Gujarat",
                "Haryana",
                "Himachal Pradesh",
                "Jammu and Kashmir",
                "Jharkhand",
                "Karnataka",
                "Kerala",
                "Madhya Pradesh",
                "Maharashtra",
                "Manipur",
                "Meghalaya",
                "Mizoram",
                "Nagaland",
                "Odisha",
                "Punjab",
                "Rajasthan",
                "Sikkim",
                "Tamil Nadu",
                "Telangana",
                "Tripura",
                "Uttarakhand",
                "Uttar Pradesh",
                "West Bengal",
                "Andaman and Nicobar Islands",
                "Chandigarh",
                "Dadra and Nagar Haveli",
                "Daman and Diu",
                "Delhi",
                "Lakshadweep",
                "Puducherry"]
  organisation: any;
  constructor(private contactService: ContactService, public snackBar: MdSnackBar, private router: Router, private _flashMessagesService: FlashMessagesService, public dialog: MdDialog,private reportService:ReportService) {
    this.reportService.deviceExcel.subscribe(value=>{
        if(value){
          this.downloadExcel()
        }
    })
    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('myInput')
        // 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;
    this.organisation = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).organisation;
    // 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.getSupAdmin();
  }

  getSupAdmin(){
    this.contactService.get('/users/shareProfileImage?uid='+this.useridd).subscribe((res:any)=>{
      this.emailid=res.email;
      this. getCustomer();
      this.getDeviceCount()
    })
  }

 callDataTable(){
    this.skip = 0;
    // that.limit = len;
    this.getCustomer();
  }
  editDevice(data) {
    localStorage.setItem('deviceData', JSON.stringify(data))
    localStorage.setItem('KycApprovalRedirect','true');
    this.router.navigate(['/editDevice']);
  }
  getCustomer(){
     this.Load = true;  
     var url="/devices/getAllVehi?id="+this.organisation+"&skip="+this.skip+'&limit='+this.limit
     if(this.myInput){
       url=url+'&search='+this.myInput
       console.log(this.myInput,url);
     }
    if(this.status){
        url=url+'&status='+this.status
    }
    // else{
    //    url="/devices/getAllVehi?id="+this.organisation+"&skip="+this.skip+'&limit='+this.limit

    //  }
     if(this.state){
       url=url+'&state='+this.state
     }
     var group,statuss,dateObj,DealerID,status1
    //  this.contactService.getAllVehi()
    this.contactService.get(url)
    .subscribe(  
      (data:any) => {
        this.Load = false;
        this.custumer=[];
         if(data.length==0){
          this.nextButton=true;
          this.previewButton=false;
        }
        this.custumer = data;
        
        console.log("custDetail=>", this.custumer);
      }, err => {
        // console.log("errlog");
         this.Load = false;
        this.custumer=[];
        this.nextButton = true;
        this.previewButton = false;
      });
  }

  


 

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

  }
  

  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() {

      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<this.custumer.length;i++){
          this.custumer[i].DocName = '-';
          this.custumer[i].device_Type_csv = this.custumer[i].device_model && this.custumer[i].device_model.device_type ? this.custumer[i].device_model.device_type :''
          this.custumer[i].adharNumber = '-';
          if (this.custumer[i].imageDoc && this.custumer[i].imageDoc.length) {
            let findData = this.custumer[i].imageDoc.find(dImageDoc => dImageDoc.doctype == 'Adhar card1 *');
            if (findData) {
              this.custumer[i].DocName = 'Aadhar Card';
              this.custumer[i].adharNumber = findData.phone ? findData.phone.replaceAll('-','') : '-' ;
            }
          }
          let lastName = this.custumer[i].user && this.custumer[i].user.last_name ? this.custumer[i].user.last_name : '';
          console.log(lastName);
          this.custumer[i].Dphone ='-';
          this.custumer[i].kycApprovalDateOnly = moment(this.custumer[i].kycApprovalDate).format("DD/MM/YYYY");
          this.custumer[i].fuelType = '-';
          this.custumer[i].stateServer = '-';
          this.custumer[i].email = this.custumer[i].user && this.custumer[i].user.email ? this.custumer[i].user.email : ''
          this.custumer[i].Dealer_full_name = (this.custumer[i] && this.custumer[i].Dealer && this.custumer[i].Dealer.first_name ? this.custumer[i].Dealer.first_name : '') + ' ' + (this.custumer[i] && this.custumer[i].Dealer &&this.custumer[i].Dealer.last_name ? this.custumer[i].Dealer.last_name : '')
          //this.custumer[i].Dealer_full_name = (this.custumer[i].Dealer.first_name ? this.custumer[i].Dealer.first_name : '') + ' ' +(this.custumer[i].Dealer.last_name ? this.custumer[i].Dealer.last_name : '');
          // this.custumer[i].email=this.custumer[i].user.email?this.custumer[i].user.email:''
          this.custumer[i].user_id = this.custumer[i].user &&  this.custumer[i].user.user_id?this.custumer[i].user.user_id:''
          this.custumer[i].phone = this.custumer[i].user && this.custumer[i].user.phone?this.custumer[i].user.phone:'';
          this.custumer[i].address = this.custumer[i].user &&  this.custumer[i].user.address ? this.custumer[i].user.address : ''
          this.custumer[i].fullName = (this.custumer[i].user && this.custumer[i].user.first_name ? this.custumer[i].user.first_name : '') + " " + (lastName ? lastName :'');
          console.log(this.custumer[i].fullName);
          if(i==(this.custumer.length-1)){

            this.downloadFile(this.custumer);
          }
          }
      //   console.log("custDetail=>", custumer);
      // }, err => {
        // console.log("errlog");
         this.Load = false;
        // custumer=[];
        // this.nextButton = true;
        // this.previewButton = false;
      // });


  //  for(var i=0;i<this.custumer.length;i++){
  //   // this.custumer[i].user.fullName=this.custumer[i].first_name?this.custumer[i].first_name:''+" "+this.custumer[i].last_name?this.custumer[i].last_name:'';
  //  }

    
  }

  downloadFile(data) {
    let arrHeader = ["Device_ID", "kycApprovalDateOnly", "vahanID", "device_Type_csv", "IccidNo", "sim_number", "sim_number2", 'sim_provider', 'License', 'Dealer_full_name', 'phone', 'DocName', 'adharNumber', "fullName", "ConcernPersonName", 'phone', 'manufacturingCompany', 'Model', 'ChassisNo', 'engineNo', 'fuelType', 'Device_Name', 'transportOfficeCity', 'transportOfficeState', 'pin', "transportOfficeState", 'rto', "stateServer", 'state_certifcate_date', 'DocName', 'adharNumber', 'address'];
    let arrHeaderOld = ["fullName", "email", "phone", "user_id","kycStatus","Device_Name","Device_ID","esim_validity","remark","RtoState","RtoCity"];
    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 = ['IMEI NO.', 'KYC Approve Date', 'DEVICE ID', 'Device Model', 'ICCID NO.', 'SIM 1', 'SIM 2', 'Profile', 'Plan', 'Dealership- Distributor Name', 'D. Mobile', 'ID Proof Document', 'ID NO', 'Customer Name', 'Concern Person Name', 'Mobile No', 'MAKE BY', 'Model', 'Chassis No', 'Engine No', 'Fuel Type', 'Vehicle No.', 'CITY', 'State', 'PIN', 'RTO STATE', 'RTO NAME', 'STATE SERVER', 'State certificate Generation Date', 'Address Proof Document', 'Address ProofDocument No.', 'ADDRESS'];
    let newHeadersOld =["Name", "Email", "Phone", "User id","KYC Status","Device Name","IMEI","E Sim Validity","Remark","RTO State","RTO City"];

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

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

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

      if (result == "no") {
     
      }
      if(result == 'imageupdated'){
        swal(
          'Updated',
          'Documents has been Updated.',
          'success'
        ) 
          this.ngOnInit();
      }
    });
  }
  inventoryCount=[{_id: "Pending", TotalDev: 0},{_id: "Approved", TotalDev: 0},{_id: "Reject", TotalDev: 0}]
getDeviceCount(){
  this.contactService.get("/devices/getStatusCount?id="+this.organisation).subscribe((res:any)=>{
   for(var i=0;i<res.length;i++){
     for(var j=0;j<this.inventoryCount.length;j++){
       if(res[i]._id==null){
         this.inventoryCount[0].TotalDev=res[i].TotalDev
       }
       if(this.inventoryCount[j]._id==res[i]._id){
        this.inventoryCount[j].TotalDev=res[i].TotalDev
       }
     }
   }
    // this.inventoryCount=res;
   
  })
}

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 = this.dialog.open(CertOptionComponent, {
                            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 }
                                });
                            }
                        })
}

}