import { Component, OnInit } from '@angular/core';
import { AddsubadminComponent } from './addsubadmin/addsubadmin.component';
import { Subject } from 'rxjs';
import { ContactService } from '../contact.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { MdDialog } from '@angular/material';
declare var $:any;
declare var PerfectScrollbar:any;
declare var swal:any;
@Component({
  selector: 'app-sub-amin',
  templateUrl: './sub-amin.component.html',
  styleUrls: ['./sub-amin.component.scss']
})
export class SubAminComponent implements OnInit {
  subadmin_info=[];
  myInput:any;
  modelChanged: Subject<string> = new Subject<string>();
  superAdmin: any;
  emailid: any;
  useridd: any;
  or: any;
  custtype: any;
  mb: any;
  cust: boolean;
  Load: boolean;
  firstcall: boolean = false;
  lastcall: boolean = true;
  constructor(private contactService: ContactService, private router: Router, private _flashMessagesService: FlashMessagesService, public dialog: MdDialog) {
   
    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;
     this.subadminDetail();
    });

    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.0/js/intlTelInput-jquery.min.js");
    document.getElementsByTagName("head")[0].appendChild(script);


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

  ngOnInit() {
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
   
    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;

    let test = JSON.parse(window.atob(window.localStorage.token.split('.')[1]));
  
    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;

 
    if (this.custtype == true) {
      this.cust = true;
    }

    this.subadminDetail();
    

    // $(document).ready(function () {
    //   $('.js-pscroll').each(function(){
    //     var ps = new PerfectScrollbar(this);
  
    //     $(window).on('resize', function(){
    //       ps.update();
    //     })
  
    //     $(this).on('ps-x-reach-start', function(){
    //       $(this).parent().find('.table100-firstcol').removeClass('shadow-table100-firstcol');
    //     });
  
    //     $(this).on('ps-scroll-x', function(){
    //       $(this).parent().find('.table100-firstcol').addClass('shadow-table100-firstcol');
    //     });
  
    //   });
    // })
  }

  addSubadmin(){
    let dialogRef = this.dialog.open(AddsubadminComponent, {
      width: '800px',
    });
    var that = this;
    dialogRef.afterClosed().subscribe(result => {     
      if (result == "succ") {  
        that.subadminDetail()   
     
      }
    });
  }

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

  subadminDetail() {
    this.Load = true;
   console.log("Inside function");
    this.contactService.dealer_Info1(this.useridd, this.skip, this.limit,this.myInput,'subadmin')
      .subscribe(res => {
        // console.log(res);
        this.Load = false ;
        this.subadmin_info = res;
        console.log('this.subadmin_info',this.subadmin_info);
        // console.log("SuccessLog");
      }, err => {
        this.Load = false;
        this.subadmin_info=[];
        this.firstcall = true;
        this.lastcall = false;
      })

  }

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

  }

 
  dealerToken: any;
  // dealer switch function
  dealerSwitch(dlr) {
    // console.log(dlr);
    localStorage.setItem("DealerObj=>", dlr._id);
    localStorage.removeItem("in1");
    this.contactService.getcustToken(dlr._id).subscribe(
      data => {
        this.dealerToken = data
        var superAdminToken = localStorage.getItem('token');
        localStorage.setItem('superAdminToken', superAdminToken);
        localStorage.setItem('token', this.dealerToken.custumer_token);

        var chkPP = localStorage.getItem('profilePic');
        if(chkPP != null){
          localStorage.removeItem('profilePic');
        }  
        localStorage.removeItem('devices');
        window.localStorage['DataUpdate'] = 'True';
        window.localStorage['Dealer'] = 'ON';
        localStorage.setItem('superadmin', "ON");


        if (window.localStorage['DataLoaded'] = 'True') {
          this.router.navigateByUrl("const?_status=" + "OK");
        }
      });
  }

  edit_DealerDetail(dealer){
    dealer['edit']=true;
    let dialogRef = this.dialog.open(AddsubadminComponent, {
      width: '800px',
      data:dealer
    });
    var that=this;
    dialogRef.afterClosed().subscribe(result => {     
      if (result == "success") {     
        that.subadminDetail();
      }
    });


  }

  delete_DealerDetail(dealer){
    var that = this;
    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) {
        var deletePayload = {
          'userId' : dealer._id,
          'deleteuser' : true
        }
        that.contactService.deleteCostumer(deletePayload).subscribe(res=>{  
          that.subadminDetail();
              swal(
                  'Deleted',
                  'Subadmin Deleted',
                  'success'
              )
          },err=>{
            swal(
              'Error',
              'Please try after sometime !!!',
              'error'
          )
          })
      }
  });
  }

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

  data_descip:any;

}
