import { Component, OnInit, Inject } from '@angular/core';
import { ContactService } from '../../contact.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { MdDialog, MD_DIALOG_DATA, MdDialogRef } from '@angular/material';
import { Subject } from 'rxjs';
declare var $:any;
declare var swal: any;
declare var google :any;
import * as moment from 'moment-timezone';

@Component({
  selector: 'app-addsubadmin',
  templateUrl: './addsubadmin.component.html',
  styleUrls: ['./addsubadmin.component.scss']
})
export class AddsubadminComponent implements OnInit {
  modelChanged: Subject<string> = new Subject<string>();
  myInput: string;
  superAdmin: any;
  emailid: any;
  useridd: any;
  sup_admin: any;
  custtype: any;
  timezoneArray: any[];
  countrySelected: { countryCode: any; dialcode: any; };
  first_name: any;


  show1:boolean = false;
  show2:boolean = true;
  passwordtype : any = 'password';
  passwordtype_1 :any = 'password';
  show3:boolean = false;
 
  imageuploadObject = [];
  timezone:any = 'Asia/Kolkata';
  last_name:any=null;
  passwordd:any=null;
  org_name:any=null;
  emaill:any=null;
  phone:any=null;
  executed:any;
  $event2:any;
  dealer:any;

  login1:any;
  mess2:any;
  mess:any;
  otp:any;
  str:boolean = false;
  password2:any=null;
  before:any;
  emmnerr:any;
  Load:any
  $event:any;
  fs:any;
  ls:any;
  selectedRole="subadmin"

  cust:boolean=false;
  mb:any;
  logo:any;
  text:any;
  userID:any;
  role=[{name:'SubAdmin',value:'subadmin'},{name:"CC",value:'cc'}]
  role1=[{name:'SubAdmin',value:'subadmin'},{name:"KYC Approval",value:'kycApproval'},{name:"CC",value:'cc'}]
  documentDetail:any;
  imageURL:any;
  address: any;
  contacts=[];
  isOrganisation
  telCountryCode: any;
  showError :boolean = false;
  updateBtn:boolean=false;
  headTitle = 'ADD SUBADMIN';
  errorMsg: string;
  organisation: any;
  constructor(private contactService: ContactService,private router: Router,private _flashMessagesService: FlashMessagesService,public dialogRef: MdDialogRef<AddsubadminComponent>,
    @Inject(MD_DIALOG_DATA) public data: any) {
      console.log(this.data);
      if((this.data != undefined)&&(this.data.edit === true)){
          this.updateBtn = true;
          this.headTitle = 'EDIT SUBADMIN';
          this.userID = this.data.user_id?this.data.user_id:'';
          this.first_name = this.data.first_name?this.data.first_name:'';
          this.last_name = this.data.last_name?this.data.last_name:'';
          this.emaill = this.data.email?this.data.email:'';
          this.phone = this.data.phone?this.data.phone:'';
          this.address =this.data.address?this.data.address:'';
          this.selectedRole=this.data.customer_role?this.data.customer_role:'subadmin';
          // this.expDate = this.data.expire_date?this.data.expire_date:'';
          if(this.data.std_code != undefined){
            var cc = this.data.std_code.countryCode?this.data.std_code.countryCode:'in'
            $('#telephone').intlTelInput("setCountry",cc);
          }
      

      }
  }

  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.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
  
    this.sup_admin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).supAdmin;
    var that = this;
    this.isOrganisation=JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isOrganisation;
    if(this.superAdmin){
      this.sup_admin = this.useridd;
    }
    this.organisation=JSON.parse(window.atob(window.localStorage.token.split(".")[1])).organisation;
    console.log("this.isOrganisation",this.isOrganisation);
    
    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
  //  this.getdev();

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

  var that = this;
    setTimeout(() => {
     that.telCountryCode =  $("#telephone").intlTelInput({
        allowDropdown:true,
        autoPlaceholder:"Enter Mobile Number",
        initialCountry:"in",
        preferredCountries: ["in","us" ],
        separateDialCode:true,
        }); 
    }, 300);

    var Phoneinput = document.getElementById('telephone');
    var that = this;
    Phoneinput.addEventListener("countrychange",function(p) {
      console.log("Inside Function");
      var countryData = $('#telephone').intlTelInput("getSelectedCountryData");
      console.log(countryData); 
      that.countrySelected = {
        countryCode : countryData.iso2,
        dialcode: countryData.dialCode
      }
      });



  var timeZn = moment.tz.guess(); 
  if(timeZn != 'Asia/Calcutta'){
    this.timezone = timeZn;
  }
  console.log(this.timezone);


var timeZones = moment.tz.names();
console.log(timeZones);
this.timezoneArray=[];
for (var i in timeZones) {
  this.timezoneArray.push({ viewValue: "(GMT" + moment.tz(timeZones[i]).format('Z') + ")" + timeZones[i], value: timeZones[i] });
}


setTimeout(() => {
  $('#dbselect').multipleSelect({
    width: 300,
    placeholder: 'Select Timezone',
    filter: true,
    single: true,
    selectAll: false
  })   
}, 100);

  }

  check(){
    if(this.updateBtn === true){
      this.editDealer();
    }else{
      this.addContact2();
    }
  }

  addContact2(){
    var tzone = $('#dbselect').multipleSelect('getSelects','value'); 
    console.log(tzone);
   var expDate = new Date()
   expDate.setFullYear(expDate.getFullYear()+1); 
   var countryData = $('#telephone').intlTelInput("getSelectedCountryData");
   console.log(countryData); 
   this.countrySelected = {
     countryCode : countryData.iso2,
     dialcode: countryData.dialCode
   }
   console.log('expDate=>',expDate);
    if(this.first_name==null || this.last_name==null || this.passwordd==null)
      {
     return  this._flashMessagesService.show('Please fill all Requied fields', { cssClass: 'alert-danger', timeout: 3000 });
       
      }  
      else if((this.userID == undefined)||(this.userID.trim() == '')){
      return  this._flashMessagesService.show('User ID is mandatory', { cssClass: 'alert-danger', timeout: 3000 });
      }   
      // else if((this.emaill == undefined)||(this.emaill.trim() == '')){
      //  return this._flashMessagesService.show('Email is mandatory', { cssClass: 'alert-danger', timeout: 3000 });

      // }
      else if(this.password2 != this.passwordd){
       // this._flashMessagesService.show('Password and Confirm Password do not match', { cssClass: 'alert-danger', timeout: 3000 });
        this.tost1("psdnmtch")
       }
      else if (this.emaill && this.phone){
        this.Load=true
   //  if (!this.executed) {
       
    //   this.executed = true;
       const newContact2 ={
       first_name: this.first_name,
       last_name: this.last_name,
       email: this.emaill,
       password: this.passwordd,
       phone: this.phone,
       isDealer: true,
       custumer:false,
       sysadmin:this.superAdmin,
       expdate : new Date(expDate),
       supAdmin:this.sup_admin,
       user_id:this.userID,
       address:this.address,
       customer_role: this.selectedRole?this.selectedRole:'subadmin'

   }

   if(this.countrySelected != undefined){
    newContact2['std_code']=this.countrySelected;
   }
   if(this.isOrganisation){
  newContact2['organisation']=this.useridd
}
   
      if (tzone != undefined) {
        newContact2['timezone'] = tzone[0];
      }

  

   if(this.imageuploadObject.length > 0){  
     
    for(var d = 0 ;d <this.imageuploadObject.length;d++){
     
      if((this.imageuploadObject[d].doctype == "")&&(this.imageuploadObject[d].image == "")&&(this.imageuploadObject[d].phone == "")){   
            this.imageuploadObject.splice(d,1);
           
      }

    }
  } 
  console.log("Final DOC ARRAY",this.imageuploadObject);
    newContact2['imageDoc'] = this.imageuploadObject;
    console.log(newContact2);
    console.log(newContact2);
    
   this.contactService.addContact(newContact2)
   .subscribe(contact => {
    console.log(contact);
    //  USER_ID already exists   
    if(contact.message == "USER_ID already exists"){
      return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }if(contact.message == "USER_ID already exists"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else if(contact.message == "User Duplicate"){
          return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else if(contact.message == "Email ID already exists"){
          return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else if(contact.message == "Mobile Number already exists"){
          return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else{
    
      this.Load=false
      this.onNoClick("succ");
      // this.contacts.push(contact);
    }
  
   }, (err: any) => { 
    //  console.log(err.status); 
    // console.log(err);
  if(err.status ==  500)
  {
  //  console.log(err._body);
    this.Load=false
    this.emmnerr=JSON.parse(err._body);
    this.data_descip = this.emmnerr.split(':')[1];
    console.log(this.data_descip);
    swal(
      'Error',
      this.data_descip,
      'error'
    )

    this.tost1("EmM")
  }
  else{
    this.Load=false
    swal(
      'Error',
      'Internal Server error , Please try after sometime !!!',
      'error'
    )

  }
  });
/*    this._flashMessagesService.show('OTP Sent Sucessfully', { cssClass: 'alert-success', timeout: 3000 }); */

 }
      else if((this.phone)||(this.userID)){
        this.Load=true

    //   if (!this.executed) {
    //     this.executed = true;
         const newContact2 ={
         first_name: this.first_name,
         last_name: this.last_name,
         password: this.passwordd,
        //  phone: this.phone,
         isDealer: true,
         custumer:false,
         sysadmin:this.superAdmin,
         expdate : new Date(expDate).toISOString(),
         supAdmin:this.sup_admin,
        //  user_id:this.userID,
         address:this.address,
         customer_role: this.selectedRole?this.selectedRole:'subadmin'
     }

     if(this.phone){
      newContact2['phone'] = this.phone  ;
    }

    if(this.countrySelected != undefined){
      newContact2['std_code']=this.countrySelected;
     }
     if(this.isOrganisation != undefined){
      newContact2['organisation']=this.useridd;
     }
    
     
   if(tzone != undefined){
    newContact2['timezone'] = tzone[0];
}
  
    if(this.userID){
      newContact2['user_id'] = this.userID  ;

    }

     if(this.imageuploadObject.length > 0){  

      for(var d = 0 ;d <this.imageuploadObject.length;d++){   
        if((this.imageuploadObject[d].doctype == "")&&(this.imageuploadObject[d].image == "")&&(this.imageuploadObject[d].phone == "")){   
              this.imageuploadObject.splice(d,1);        
        }
      }
    }
    newContact2['imageDoc'] = this.imageuploadObject;
    console.log(newContact2);
    
     this.contactService.addContact(newContact2)
     .subscribe(contact => {
   
      if(contact.message == "USER_ID already exists"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }if(contact.message == "USER_ID already exists"){
          return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
          }else if(contact.message == "User Duplicate"){
            return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
          }else if(contact.message == "Email ID already exists"){
            return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
          }else if(contact.message == "Mobile Number already exists"){
            return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
          }else{
        
      this.clear();
      this.Load=false;
      this.onNoClick("succ");
       this.contacts.push(contact);

      }
  
     }, (err: any) => {
    if(err.status ==  500)
    {
    //  console.log(err._body);
      this.Load=false
      this.emmnerr=JSON.parse(err._body);
      this.data_descip = this.emmnerr.split(':')[1];
      console.log(this.data_descip);
      swal(
        'Error',
        this.data_descip,
        'error'
      )
  

      this.tost1("EmM")
    }
    else{
      this.Load=false
      // console.log("dadsa");
      swal(
        'Error',
        'Internal Server error , Please try after sometime !!!',
        'error'
      )
    }})
  }
 else if(this.emaill){
 // if (!this.executed) {
  //  this.executed = true;
    const newContact2 ={
    first_name: this.first_name,
    last_name: this.last_name,
    password: this.passwordd,
    org_name: this.org_name,
    email: this.emaill,
    isDealer: true,
    custumer:false,  
    sysadmin:this.superAdmin,
    expdate : new Date(expDate).toISOString(),
    supAdmin:this.sup_admin,
    user_id:this.userID,
    address:this.address,
    customer_role: this.selectedRole?this.selectedRole:'subadmin'

}

if(this.countrySelected != undefined){
  newContact2['std_code']=this.countrySelected;
 }

 
 if(tzone != undefined){
  newContact2['timezone'] = tzone[0];
}
if(this.isOrganisation){
  newContact2['organisation']=this.useridd
}



if(this.imageuploadObject.length > 0){  

  for(var d = 0 ;d <this.imageuploadObject.length;d++){
    if((this.imageuploadObject[d].doctype == "")&&(this.imageuploadObject[d].image == "")&&(this.imageuploadObject[d].phone == "")){   
          this.imageuploadObject.splice(d,1);   
    }
  }
}
newContact2['imageDoc'] = this.imageuploadObject;
console.log(newContact2);

this.contactService.addContact(newContact2)
.subscribe(contact => {
  console.log(contact);
  //  USER_ID already exists

  //this.tost1("succ")
  if(contact.message == "USER_ID already exists"){
    return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
    }if(contact.message == "USER_ID already exists"){
      return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else if(contact.message == "User Duplicate"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else if(contact.message == "Email ID already exists"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else if(contact.message == "Mobile Number already exists"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else{
    this.clear();
    this.Load=false
    this.onNoClick("succ");
    this.contacts.push(contact);
  }

}, (err: any) => {
  if(err.status ==  500)
  {
  //  console.log(err._body);
    this.Load=false
    this.emmnerr=JSON.parse(err._body);
    this.data_descip = this.emmnerr.split(':')[1];
    console.log(this.data_descip);
    swal(
      'Error',
      this.data_descip,
      'error'
    )
    // console.log(this.emmnerr)
    this.tost1("EmM")
  }
  else{
    this.Load=false
    swal(
      'Error',
      'Internal Server error , Please try after sometime !!!',
      'error'
    )
 
  }});


 }
 
 }

 data_descip:any;
 onNoClick(a): void {
  this.dialogRef.close(a);
 }
 tost1(divid){
  if(divid == "EmM"){
     this.data_descip =  this.emmnerr.split(":")[1]
     this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-danger', timeout: 3000 });
   }
   else if(divid == "succ"){
     this.data_descip =  "Dealer Successfully Added"
     this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-success', timeout: 3000 });
   }
   else if(divid == "psdnmtch"){
    this.data_descip =  "Error: Password and confirm password do not match"
    this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-danger', timeout: 3000 });
   }
  //    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);
  //  }
    }

    clear(){
      this.first_name=' '
      this.last_name=' '
      this.emaill = null
      this.phone = null
    }

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


     latLongDetail(){
      var that =this;
      console.log("Inside Latlong Function");
      if (navigator.geolocation) {  
     
        if(location.protocol != 'https:'){
          this.contactService.getlatLong().subscribe(res=>{
            console.log(res); 
              let t_latlng = new google.maps.LatLng(res.lat, res.lon);
              let request = {
                latLng: t_latlng
              };
    
            this.getAddress(request);
          })
        }else{
          navigator.geolocation.getCurrentPosition(function(position) {
            var d_lat= position.coords.latitude;
            var d_lng=position.coords.longitude;
            let t_latlng = new google.maps.LatLng(d_lat, d_lng);
            let request = {
              latLng: t_latlng
            };
    
            that.getAddress(request);
          })
          
        }}            
    }
    
    getAddress(request){ 
      let geocoder = new google.maps.Geocoder();  
      geocoder.geocode(request, function (data, status) {
        console.log("Inside geocoder function");  
        var userCountry;
        if (status == google.maps.GeocoderStatus.OK) {
          if (data[0] != null) {
            var address_show = data[0];
            console.log('var=>' ,address_show);
            for (var ac = 0; ac < data[0].address_components.length; ac++) {
              var component = data[0].address_components[ac];
              switch(component.types[0]) {     
                  case 'country':
                      userCountry  = component.short_name;
                      console.log(userCountry);
                      break;      
              }
          };
           
              var aaa = $('#telephone').intlTelInput("setCountry",userCountry);
          } else {
            userCountry = 'in';  
          }
        }
        else {
          console.log("Inside Error function");  
          userCountry = 'in';
        }
      })  
    }
    

    closebox(){
      this.dialogRef.close('close');
    }

    stren(){}
    editDealer(){   
      // this.emaill = this.data.email?this.data.email:'';
      // this.phone = this.data.phone?this.data.phone:'';
      // this.address =this.data.address?this.data.address:'';
      var editDealerPayload = {
        first_name : this.first_name,
        last_name:this.last_name,
        address:this.address,
        user_id:this.userID,  
        contactid:this.data._id,    
        phone :  this.phone,
        email : this.emaill, 
        customer_role: this.selectedRole?this.selectedRole:'subadmin' 
      }
   
     
      this.contactService.editDealer(editDealerPayload)
        .subscribe(res=>{
        
          // console.log(res);
          if(res){
            // console.log(res);
            this.dialogRef.close("success");
        }  
        },err=>{
          var that = this;
          console.log(JSON.parse(err._body).message);
          var errorM = (JSON.parse(err._body).message).split(":");
          var mainErr =errorM[2];
          if(mainErr == " phone_1 dup key"){
            this.errorMsg = "Phone number already exists";
          }else if(mainErr == " email_1 dup key"){
            this.errorMsg = "Email id already exists";
          }else{
            this.errorMsg = "Internal server error";
          }
  
          this.showError  = true;
        
          var error =  setTimeout(function(){
            clearInterval(error);
            that.showError = false; 
          },5000)
  
        })
  
    }
  
  
}
