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


@Component({
  selector: 'app-add-distributers',
  templateUrl: './add-distributers.component.html',
  styleUrls: ['./add-distributers.component.scss']
})
export class AddDistributersComponent implements OnInit {
  fs:any;
  service2
  service1
  support1
  support2;
  support3
  ls:any;
  DeviceSetting={Add:true,Edit:true,Delete:false}
  UserSetting={Add:true,Edit:true,Delete:false}
  selectedlanguage='en';
  DeviceOptions=[{name:"Add",value:true},{name:"Edit",value:true},{name:"Delete",value:false}];
  UserOptions=[{name:"Add",value:true},{name:"Edit",value:true},{name:"Delete",value:false}]
  available_languages = [{
      view : "English",
      id : "en"
  },{
      view : "Spanish",
      id : "sp"
  },{
    view : "Persian",
    id : "fa"
},{
  view : "Arabic",
  id : "ar"
},{
  view : "Portuguese",
  id : "pr"
},
{
  view : "Albanian",
  id : "newLan2"
},
{
  view : "French",
  id : "fr"
},
{
  view : "Indonesian",
  id : "bhasa_web"
}];
  emailid:any;
  or:any;
  useridd:any;
  custtype:any;
  timezoneArray=[];
  cust:boolean=false;
  mb:any;
  logo:any;
  plan
  text:any;
  superAdmin: any;
  dealerName: any;
  currencyType:any="INR";
  sup_admin: any;
  Load : boolean = false;
  show1:boolean = false;
  show2:boolean = true;
  show3:boolean = false;
  first_name:any=null;
  last_name:any=null;
  passwordd:any=null;
  org_name:any;
  emaill:any=null;
  welcome_messages_status:any;
  phone:any=null;
  executed:any;
  $event2:any;
  dealer:any;
  contacts: Contact[]=[];
  contact: Contact;
  login1:any;
  mess2:any;
  mess:any;
  otp:any;
  userID:any;
  address:any;
  str:boolean = false;
  password2:any=null;
  billingMail:any;
  dealerSelect: any=[];
  imageuploadObject = [];
  emmnerr: any;
  data_descip: any;
  editVal : boolean = true;
  heading = "ADD DISTRIBUTER";
  distStaus:any;
  organisation_name: any;
  androidAppLink:any;
  iosAppLink:any;
  
  countrySelected: { countryCode: any; dialcode: any; };
  billingTypeArr =['Monthly','Yearly'];
  billingType:any;
  billingContactDetail:any;
  timezone:any = 'Asia/Kolkata';
  billingRate:any;
  billingPhone: { countryCode: any; dialcode: any; };
  billingId: any;
  outOfReach=3;
  speedLimit=60;
  kyc_verification_mail:boolean=false;
  inventoryManagement:boolean=false;
  bussinessType:boolean=false;
  constructor(private contactService: ContactService,private router: Router,private _flashMessagesService: FlashMessagesService,public dialogRef: MdDialogRef<AddDistributersComponent>,
    @Inject(MD_DIALOG_DATA) public data: any) { 

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


      this.welcome_messages_status= true;
      if(this.data != undefined){
        console.log('this.data=>',this.data);
        if(this.data.userInfo.edit == true){
          this.heading = "EDIT DISTRIBUTER";
          console.log(this.data);
          this.kyc_verification_mail= this.data.userInfo.kyc_verification_mail? this.data.userInfo.kyc_verification_mail:false;
          this.bussinessType=this.data.userInfo.bussinessType?this.data.userInfo.bussinessType=="1"?true:false:false
          this.inventoryManagement= this.data.userInfo.inventoryManagement? this.data.userInfo.inventoryManagement:false;
          if( this.data.userInfo.Plan)this.plan= this.data.userInfo.Plan;
          if( this.data.userInfo.SpeedLimit)this.speedLimit= this.data.userInfo.SpeedLimit;
         
          if( this.data.userInfo.outOfReach)this.outOfReach= this.data.userInfo.outOfReach;
          if( this.data.userInfo.support1)this.support1= this.data.userInfo.support1
          if( this.data.userInfo.support2)this.support2= this.data.userInfo.support2
          if( this.data.userInfo.support3)this.support3= this.data.userInfo.support3
          if( this.data.userInfo.service1)this.service1= this.data.userInfo.service1
          if( this.data.userInfo.service2)this.service2= this.data.userInfo.service2
         this.distStaus = this.data.userInfo.status;
          this.editVal = false;
          this.userID =  this.data.userInfo ? this.data.userInfo.user_id  :'';
          this.passwordd=this.data.userInfo ? this.data.userInfo.pass  :''
          this.first_name = this.data.userInfo ? this.data.userInfo.first_name  :'';
          this.last_name = this.data.userInfo ? this.data.userInfo.last_name  :'';
          this.emaill = this.data.userInfo ? this.data.userInfo.email  :'';
          this.phone = this.data.userInfo ? this.data.userInfo.phone  :'';
          this.address = this.data.userInfo ? this.data.userInfo.address  :'';
          this.organisation_name = this.data.userInfo ? this.data.userInfo.organisation_name:'';
          this.androidAppLink = this.data.userInfo ? this.data.userInfo.androidAppLink : '';
          this.iosAppLink = this.data.userInfo ? this.data.userInfo.iosAppLink : '';
          if(this.data.userInfo.billing_id){
            this.billingId = this.data.userInfo.billing_id._id;
            if(this.data.userInfo.billing_id.BillingType){
                this.billingType = this.data.userInfo.billing_id.BillingType ; 
            }
            if(this.data.userInfo.billing_id.billing_contact){
              this.billingContactDetail = this.data.userInfo.billing_id.billing_contact ; 
            }
            if(this.data.userInfo.billing_id.billing_rate){
              this.billingRate = this.data.userInfo.billing_id.billing_rate;
            }
            if(this.data.userInfo.billing_id.email){
              this.billingMail = this.data.userInfo.billing_id.email ; 
            }

          }
           if( this.data.userInfo.devicePermission){
             this.DeviceSetting= this.data.userInfo.devicePermission;
              for(let i=0;i<this.DeviceOptions.length;i++){
                // if(this.DeviceOptions[i].name==this.data.userInfo.DevicePermission[this.DeviceOptions[i].name]){
                  this.DeviceOptions[i].value=this.data.userInfo.devicePermission[this.DeviceOptions[i].name]
                // }
              }
            }
          if( this.data.userInfo.userPermission){
            this.UserSetting= this.data.userInfo.userPermission;
             for(let i=0;i<this.UserOptions.length;i++){
                // if(this.UserOptions[i].name==this.data.userInfo.DevicePermission[this.UserOptions[i].name]){
                  this.UserOptions[i].value=this.data.userInfo.userPermission[this.UserOptions[i].name]
                // }
              }
          }
        
          if(this.data.userInfo){
            if(this.data.userInfo.welcome_msg != undefined){
              this.welcome_messages_status =this.data.userInfo.welcome_msg ; 
            }else{
              this.welcome_messages_status = true; 
            }
          }
          
        }
      }
   


      var  initialObj = {
        doctype:'',
        image:'',
        phone:''
      }
      this.imageuploadObject.push(initialObj);
      
    }

  ngOnInit() {


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

    setTimeout(() => {
      $("#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
      }
      });

      setTimeout(() => {
        $("#telephoneBill").intlTelInput({
          allowDropdown:true,
          autoPlaceholder:"Enter Mobile Number",
          initialCountry:"in",
          preferredCountries: ["in","us" ],
          separateDialCode:true,
          }); 
      }, 300);
    
  
      var Phoneinput_bill = document.getElementById('telephoneBill');
      var that = this;
      Phoneinput_bill.addEventListener("countrychange",function(p) {
        console.log("Inside Function");
        var countryDataBill = $('#telephoneBill').intlTelInput("getSelectedCountryData");
        console.log(countryDataBill); 
        that.billingPhone = {
          countryCode : countryDataBill.iso2,
          dialcode: countryDataBill.dialCode
        }
        console.log(that.billingPhone);
        });


    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    // console.log(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;
    if(!this.superAdmin){
      this.dealerName = this.fs
    }
    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.mb =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;

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

    this.sup_admin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).supAdmin;
    console.log("superAdmin=>",this.sup_admin);

    if(this.superAdmin){
      this.sup_admin = this.useridd;
    }

  //  this.getdev();
  if(this.mb.charAt(0)=="n"){
    this.mb = ' '
  }
  if(this.custtype == true){
    this.cust = true;
  }
  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);



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



  checkkeyandupdate(){
    console.log('inside function');
    var tzone = $('#dbselect').multipleSelect('getSelects','value'); 
    console.log(tzone);

    if((this.emaill == undefined)||(this.emaill.trim() == '')){
      this._flashMessagesService.show('Email is mandatory', { cssClass: 'alert-danger', timeout: 3000 });
      return;
      
    }

    if(this.editVal === true){
      this.addContact2();
    }else{
      this.editDistributers();
    }
  }

  documentDetail:any;
  imageURL:any;

  documentList = [
    {
      "docId": "Adhar",
      "docName": "Adhar Card"
    },
    {
      "docId": "voterCard",
      "docName": "Voter Id"
    },
    {
      "docId": "PAN",
      "docName": "Pan Card"
    },
    {
      "docId": "DL",
      "docName": "Driving License"
    }
    
  ];



  onChange(ev) {
    let dealer_status = ev.checked;
  }

  stren(){
    this.str =false;
  }

  documentType(docType){
    console.log("doctypeObject=>",docType);
  }
  selectedFile: File;
  onFileChanged(event) { 
    this.selectedFile = <File>event.target.files[0];
    console.log(this.selectedFile); 
  }
 
  onUpload(imgIndex) {
    console.log(imgIndex);
    console.log(this.imageuploadObject);
    const fd = new FormData();
    console.log("selected file name =>",this.selectedFile.name);
    if(this.selectedFile.name == " "){
      swal(
        'Upload Error',
        'Please select document type before upload !!!',
        'error'
      )
    }else{
      fd.append('photo',this.selectedFile,this.selectedFile.name)
      console.log("imgURL=>",fd) ;
      this.contactService.imageupload(fd)
      .subscribe(res=>{
        console.log(res);
        var resImage ='';
        resImage = res['_body'];
        console.log(res['_body']);
        this.imageuploadObject[imgIndex].image = resImage;
         console.log(this.imageuploadObject);
        // console.log(res);
      },err=>{
        swal(
          'Server Error',
          'Internal Server Error , plaese try after sometime !!!',
          'error'
        )
      })
    }
   }

   docRow:boolean=false;;
  AddDocumentsField(addedRow){
      if(addedRow){
        this.docRow = true;
      }
       var obj={doctype:'',image:'',phone:''};
       this.imageuploadObject.push(obj);
       console.log(this.imageuploadObject);
      // console.log("ImageuploadObject=>",this.imageuploadObject);
  }

  DeleteDocumentsField(index){
    console.log(this.imageuploadObject.length);
    if(this.imageuploadObject.length == 1){
      this.docRow = false;
    }
    this.imageuploadObject.splice(index, 1);

  }
  passwordtype:any= 'password';
  passwordtype_1:any= 'password';
  passwordIcon:any='visibility_off';
  passwordIcon_1:any='visibility_off';

  showpassword(p:any){
    console.log('inside function');
   
    if((p == 'p1')&&(this.passwordtype == "password")){
      this.passwordtype = 'text';
      this.passwordIcon = 'visibility';
      return
 
    }
 
    if((p == 'p1')&&(this.passwordtype == "text")){
      this.passwordtype = 'password';
      this.passwordIcon = 'visibility_off';
      return;
    }
 
    if((p == 'p2')&&(this.passwordtype_1 == "password")){
     this.passwordtype_1 = 'text';
     this.passwordIcon_1 = 'visibility';
     return;
 
   }
 
   if((p == 'p2')&&(this.passwordtype_1 == "text")){
     this.passwordtype_1 = 'password';
     this.passwordIcon_1 = 'visibility_off';
     return;
   }
 
  }


  
  addContact2(){

    var countryData = $('#telephone').intlTelInput("getSelectedCountryData");
    var tzone = $('#dbselect').multipleSelect('getSelects','value'); 
    console.log(tzone);
    console.log(countryData); 
    this.countrySelected = {
      countryCode : countryData.iso2,
      dialcode: countryData.dialCode
    }
  
    if(this.first_name==null || this.last_name==null || this.passwordd==null)
      {
       this._flashMessagesService.show('Please fill all Requied fields', { 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;
        // console.log(this.dealerName._id);

     
       //console.log(this.imageuploadObject);
       const newContact2 ={
       first_name: this.first_name,
       last_name: this.last_name,
       email: this.emaill,
       password: this.passwordd,
       phone: this.phone,
       isSuperAdmin : true,
       isDealer: false,
       organisation : this.useridd,
       welcome_msg : this.welcome_messages_status,
      //  custumer:true,
       user_id:this.userID,
       address:this.address,
       organisation_name: this.organisation_name,
       
   }

   if(this.countrySelected != undefined){
    newContact2['std_code']=this.countrySelected;
   }
   if(this.plan!=undefined){
     newContact2['plan']=this.plan;
   }
    if(this.kyc_verification_mail!=undefined){
     newContact2['kyc_verification_mail']=this.kyc_verification_mail;
   }
   if(this.bussinessType!=undefined){
     newContact2['bussinessType']=this.bussinessType?"1":"0";
   }
   if(this.inventoryManagement!=undefined){
     newContact2['inventoryManagement']=this.inventoryManagement;
   }

   if(this.selectedlanguage != undefined){
    newContact2['language_code']=this.selectedlanguage;
   }

   if(this.speedLimit != undefined){
    newContact2['SpeedLimit']=this.speedLimit;
   }

   if(this.UserSetting != undefined){
    newContact2['userPermission']=this.UserSetting;
   }

    if(this.DeviceSetting != undefined){
    newContact2['devicePermission']=this.DeviceSetting;
   }

  //  if(this.speedLimit != undefined){
  //   newContact2['SpeedLimit']=this.speedLimit;
  //  }

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



   if(this.support1 != undefined){
    newContact2['support1'] = this.support1;
}
 if(this.support2 != undefined){
    newContact2['support2'] = this.support2;
}
 if(this.support3 != undefined){
    newContact2['support3'] = this.support3;
}
 if(this.service1 != undefined){
    newContact2['service1'] = this.service1
}
 if(this.service2 != undefined){
    newContact2['service2'] = this.service2
}
 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);         
       }

     }
   }

   if(this.androidAppLink != undefined){
    newContact2['androidAppLink'] = this.androidAppLink ; 
   }
   if(this.iosAppLink != undefined){
     newContact2['this.iosAppLink'] = this.iosAppLink ; 
   }

    console.log("Final DOC ARRAY",this.imageuploadObject);
    newContact2['imageDoc'] = this.imageuploadObject;
    console.log(newContact2);
   this.contactService.addContact(newContact2)
   .subscribe(contact => {
    this.Load=false
    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{   
          console.log(contact);
          if((this.billingContactDetail != undefined)||(this.billingRate != undefined)||(this.billingType != undefined)||(this.billingMail != undefined)){
            this.addBillingDetail(contact);   
          }else{
            this.dialogRef.close('success');       
            this.contacts.push(contact);
          }
       
        }
   
   

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

  }
  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.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,          
         isSuperAdmin : true,
         isDealer: false,
         organisation : this.useridd,
         welcome_msg : this.welcome_messages_status,
         user_id:this.userID,
         address:this.address,
         organisation_name: this.organisation_name,
     }

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

   if(this.UserSetting != undefined){
    newContact2['userPermission']=this.UserSetting;
   }

    if(this.DeviceSetting != undefined){
    newContact2['devicePermission']=this.DeviceSetting;
   }

  //  if(this.speedLimit != undefined){
  //   newContact2['SpeedLimit']=this.speedLimit;
  //  }

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



   if(this.support1 != undefined){
    newContact2['support1'] = this.support1;
}
 if(this.support2 != undefined){
    newContact2['support2'] = this.support2;
}
 if(this.support3 != undefined){
    newContact2['support3'] = this.support3;
}
 if(this.service1 != undefined){
    newContact2['service1'] = this.service1
}
 if(this.service2 != undefined){
    newContact2['service2'] = this.service2
}
    

     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;
     this.contactService.addContact(newContact2)
     .subscribe(contact => {
      // this.clear();
      this.Load=false;
      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.dialogRef.close('success');    
            this.contacts.push(contact);
          }
     
       
     }, (err: any) => {
    if(err.status ==  500)
    {
    //  console.log(err._body);
      this.Load=false
      this.emmnerr=JSON.parse(err._body);
        console.log(this.emmnerr);
       this.data_descip = this.emmnerr.split(':')[1];
        console.log(this.data_descip);
    swal(
      'Error',
      this.data_descip,
      'error'
    )
    }
    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,
    organisation_name: this.organisation_name,
    email: this.emaill, 
    isSuperAdmin : true,
    isDealer: false,
    organisation :this.useridd,
    user_id:this.userID,
    welcome_msg : this.welcome_messages_status,
    address:this.address,
}

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

   if(this.UserSetting != undefined){
    newContact2['userPermission']=this.UserSetting;
   }

    if(this.DeviceSetting != undefined){
    newContact2['devicePermission']=this.DeviceSetting;
   }

  //  if(this.speedLimit != undefined){
  //   newContact2['SpeedLimit']=this.speedLimit;
  //  }

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



   if(this.support1 != undefined){
    newContact2['support1'] = this.support1;
}
 if(this.support2 != undefined){
    newContact2['support2'] = this.support2;
}
 if(this.support3 != undefined){
    newContact2['support3'] = this.support3;
}
 if(this.service1 != undefined){
    newContact2['service1'] = this.service1
}
 if(this.service2 != undefined){
    newContact2['service2'] = this.service2
}

 
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;

this.contactService.addContact(newContact2)
.subscribe(contact => {
 
  this.Load=false
  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.dialogRef.close('success'); 
        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("error to display",this.emmnerr);
    // this.tost1("Error")
  }
  else{
    this.Load=false;
    swal(
      'Error',
      'Internal Server error , Please try after sometime !!!',
      'error'
    )
  }});


 }
 
 
 }

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

 click2(event2){
  this.show2=true;
  this.show3=false;
  
  }
  call(e) {
    {
      if (e.keyCode == 32) {
        e.preventDefault();
      }
    }
  }

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

  
    editDistributers(){
      console.log('this.address',this.address);
        var userObj = {
          'first_name' : this.first_name,
          'user_id' : this.userID ,
          'last_name'  : this.last_name,
          'phone' :this.phone,
          'email' : this.emaill,
          password: this.passwordd,    
          'contactid' : this.data.userInfo._id,
          'address' : this.address,
          'status' : this.distStaus,
          'organisation_name': this.organisation_name  ,
          'welcome_msg' : this.welcome_messages_status,
        }
      

        if(this.selectedlanguage != undefined){
          userObj['language_code']=this.selectedlanguage;
         }
         if(this.plan!=undefined){
           userObj['plan']=this.plan;
        }
        if(this.outOfReach!=undefined){
           userObj['outOfReach']=this.outOfReach;
        }
        if(this.speedLimit!=undefined){
           userObj['SpeedLimit']=this.speedLimit;
        }
         if(this.UserSetting != undefined){
    userObj['userPermission']=this.UserSetting;
   }

    if(this.DeviceSetting != undefined){
    userObj['devicePermission']=this.DeviceSetting;
   }

        if(this.support1 != undefined){
    userObj['support1'] = this.support1;
}
 if(this.support2 != undefined){
    userObj['support2'] = this.support2;
}
 if(this.support3 != undefined){
    userObj['support3'] = this.support3;
}
 if(this.service1 != undefined){
    userObj['service1'] = this.service1
}
 if(this.service2 != undefined){
    userObj['service2'] = this.service2
}

   if(this.kyc_verification_mail!=undefined){
     userObj['kyc_verification_mail']=this.kyc_verification_mail;
   }
    if(this.inventoryManagement!=undefined){
     userObj['inventoryManagement']=this.inventoryManagement;
   }
   if(this.bussinessType!=undefined){
     userObj['bussinessType']=this.bussinessType?"1":"0";
   }
   console.log(userObj);
   
        this.contactService.editUsermaster(userObj)
          .subscribe(res=>{
            console.log(res);
            if(res){
              if((this.billingContactDetail != undefined)||(this.billingRate != undefined)||(this.billingType != undefined)||(this.billingMail != undefined)){
                if(this.billingId === undefined){
                  var adminId = {
                        user : {_id : this.data.userInfo._id}
                  }
                  this.addBillingDetail(adminId);
                }else{
                  this.updateBillingDetail();   
                }
              
              }else{
                this.dialogRef.close('success');               
              }   
            }
          },err=>{
              console.log(err.status);
              this._flashMessagesService.show('Please try again', { cssClass: 'alert-danger', timeout: 3000 });
          })
      
    }

    stre(){
      console.log("inside function");
    }

    addBillingDetail(distID){
      console.log("Inside function",distID);
    
        var payload ={
          supAdmin: distID.user._id,
          organisation: this.useridd,
          billing_contact: this.billingContactDetail,
          billing_rate: this.billingRate,
          BillingType: this.billingType,
          std_code: this.countrySelected,
          email : this.billingMail
        };
        console.log(payload);
      
        // this.contacts.push(contact);
     
      this.contactService.addBillingDetail(payload).subscribe(res=>{
        console.log("response",res);
        this.dialogRef.close('success');     
      })

    }


    updateBillingDetail(){
      var payload ={
        billing_contact: this.billingContactDetail,
        billing_rate: this.billingRate,
        BillingType: this.billingType,
        email : this.billingMail,
        billingId: this.billingId
      };
      console.log(payload);
      this.contactService.updateBillingDetail(payload).subscribe(res=>{
        console.log(res);
        this.dialogRef.close('success');  
      },err=>{
        this.dialogRef.close('success');  
      })
    }

    changelanguage(){
      
    }


    latLongDetail(){
      var that =this;
      if (navigator.geolocation) {    
          navigator.geolocation.getCurrentPosition(function(position) {
        
            let geocoder = new google.maps.Geocoder();
           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
      };
    
      geocoder.geocode(request, function (data, status) {
        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 {
          userCountry = 'in';
        }
      })          
        });
        // } 
            }
    
    
         
    
    }

    updateCheckedOptions(value,e,type){
      console.log(value,e);
      if(type=='user'){
       for(var i=0;i<this.UserOptions.length;i++){
         if(this.UserOptions[i].name==value){
           this.UserOptions[i].value=e;
           this.UserSetting[value]=e
           console.log(this.UserOptions,this.UserSetting)
         }
       }
        
        
      }else{
         for(var i=0;i<this.DeviceOptions.length;i++){
         if(this.DeviceOptions[i].name==value){
           this.DeviceOptions[i].value=e;
           this.DeviceSetting[value]=e;
            console.log(this.DeviceOptions,this.DeviceSetting)
         }
       }
      }
      
    }
}
