editlicensebasicsettings.component.ts 10.3 KB
import { Component, OnInit, AfterViewInit, Input, Output, EventEmitter, Pipe, PipeTransform, TemplateRef } from '@angular/core';
import { LicenseService } from './license.service';
import { GlobalService } from '../../shared/global';
import { Router, ActivatedRoute } from '@angular/router';
import { FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { License } from '../userentity/datamodel';
import { BsDatepickerModule } from 'ngx-bootstrap';
import { Http, Response } from '@angular/http';
import { DatePipe } from '@angular/common';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
import { ContenteditableModelDirective } from '../../shared/contenteditabledirective'
import { ConfirmService } from '../../shared/confirm/confirm.service';
import { LoadingService } from '../../shared/loading.service';
declare var $:JQueryStatic;
@Component({
  templateUrl: './editlicensebasicsettings.component.html'
})

export class EditLicenseBasicSettings implements OnInit {

  tempLstAccountNumbers: any;
  lstCountry: any;
  lstState: any;
  license: License;
  updateLicenseBasicSettingsFrm: FormGroup;
  error: any;
  alerts: string;
  modalAlerts: string;
  modalRef: BsModalRef;
  ConvertedPhoneno: string;
  MinusCharater: number;
  LicenseId:number=0;
  AccountNumber:string='';
  IsUniteState:Boolean=false;

  constructor(private _loadingService: LoadingService,private licenseService: LicenseService,
    public globalService: GlobalService, private router: Router,
    private activeRoute: ActivatedRoute, private fb: FormBuilder,
    private modalService: BsModalService, private _confirmService: ConfirmService) { }

  ngOnInit(): void {
    this._loadingService.ShowLoading("global-loading");
    $('#accountSelect').chosen({allow_single_deselect:true,width:'300px',placeholder_text_single:'Select Account',search_contains:true});
 
    this.license = new License();
    this.alerts = '';
    this.updateLicenseBasicSettingsFrm = this.fb.group({
      licenseId: [0],
      accountNumber: ['', [Validators.required,this.noWhitespaceValidator]],
      licenseeFirstName: ['', [Validators.required,this.noWhitespaceValidator]],
      licenseeLastName: ['', [Validators.required,this.noWhitespaceValidator]],
      institutionName: ['', [Validators.required,this.noWhitespaceValidator]],
      address1: ['', [Validators.required,this.noWhitespaceValidator]],
      address2: [''],
      city: ['', [Validators.required,this.noWhitespaceValidator]],
      stateId: [0, [Validators.min(1)]],
      countryId: [0],
      zip: ['', [Validators.required]],
      emailId: ['', [Validators.required]],
      //phone: ['', [Validators.required, Validators.pattern('^([0-9]{3})-([0-9]{3})-([0-9]{4})$')]],
      phone: ['', [Validators.required]]
    });
    this.GetCountry();
    this.GetState();

    if (this.globalService.UserType > 2) {
      this.tempLstAccountNumbers=[];
      this.tempLstAccountNumbers.push({m_Item1:this.globalService.AccLicId,m_Item2:this.globalService.AccountNumber});
      this.AccountNumberChanged(this.globalService.AccLicId,this.globalService.AccountNumber);
     
      setTimeout(function(){         
        $('#accountSelect').prop('disabled', true).trigger("chosen:updated");
        $('#accountSelect').trigger('chosen:updated'); 
      
     }, 500);
     this._loadingService.HideLoading("global-loading");
    }
    else
    {    
      this.GetLicenseAccounts();
    }
    $('#accountSelect')
      .on('change', (e, args) => {
        var selectedValue = Number(args.selected);
        var selectedText= $(".chosen-single span" ).text();
        this.AccountNumberChanged(selectedValue,selectedText);
      });  


  }
  public noWhitespaceValidator(control: FormControl) {
    // new validation for intial whaite space
    //****Birendra *****/
     var isValid=false;
     if(control.value!=null)
     {
      var controlLen=control.value.length;
      if(controlLen==undefined)//undefined for integer value
      {
       isValid=true;
      }
     else if(controlLen!=0)
      {
        const isWhitespace = (control.value || '').trim().length === 0;
         isValid = !isWhitespace;
        if(!isValid)
        {
          control.setValue('');
          
        }
      }
     }  
     // can use also on page of input control
     //
     return isValid ? null: { 'whitespace': true };
     
 }

 onKeyUp(event: any) {
  var mobno = event.target.value;
  var countryName =$("#Country option:selected").text().trim();
  if(mobno!="" && event.key!="Backspace")
  {
    if(countryName=="United States")
    {  
        this.USFormatPhoneNumber(mobno);
    }
    else
    {
      this.OtherFormatPhoneNumber(mobno);
    }
}
    
};

OtherFormatPhoneNumber(mobno:any)
{
  //var regex = /\d+/g;
  //var matches = mobno.match(regex); //extract digit only
  //var currentNum= matches==null?"" :matches.join('');
  this.updateLicenseBasicSettingsFrm.controls['phone'].setValue(mobno);
}

USFormatPhoneNumber(mobno:any)
{
  var newformat="";
  if(mobno!="" && mobno!=null)
  {
    var regex = /\d+/g;
    var matches = mobno.match(regex); //extract digit only
    var currentNum= matches==null?"" :matches.join('');

    for(var ind=0;ind<currentNum.length;ind++)
    {
      if(newformat.length==3)
      {
        newformat=newformat+"-";
      }
      else if(newformat.length==7)
      {
        newformat=newformat+"-";
      }   
      newformat=newformat+currentNum[ind];
    }

   }
   this.updateLicenseBasicSettingsFrm.controls['phone'].setValue(newformat);
}

//get Property
get PhoneNumber() {
  return this.updateLicenseBasicSettingsFrm.get('phone');
} 
onCountryChange(event: any) {
  //let contryName = event.target.options[event.target.options.selectedIndex].text;
  this.UpdatePhoneValidation()
};

UpdatePhoneValidation()
{
  var phoneno=this.PhoneNumber.value==null?"":this.PhoneNumber.value;
 
  var countryName =$("#Country option:selected").text().trim();
  if(countryName=="United States")
    {
      // validate first phone number
      this.IsUniteState=true;
      this.PhoneNumber.setValidators([Validators.required, Validators.pattern('^([0-9]{3})-([0-9]{3})-([0-9]{4})$')]);
      this.PhoneNumber.updateValueAndValidity();
      this.USFormatPhoneNumber(phoneno);
    }
    else
    {
      this.IsUniteState=false;
     // this.PhoneNumber.setValidators([Validators.required, Validators.pattern('^[0-9]*$')]);
      this.PhoneNumber.setValidators([Validators.required]);
      this.PhoneNumber.updateValueAndValidity(); 
      this.OtherFormatPhoneNumber(phoneno);
    }
  
}

  openModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template);
  }

  GetCountry() {
    this.licenseService.GetCountry()
      .subscribe(y => {
         this.lstCountry = y;
         }, error => this.error = <any>error);
  }

  GetState() {
    this.licenseService.GetState()
      .subscribe(st => { this.lstState = st; }, error => this.error = <any>error);
  }

  GetLicenseAccounts() {
    this.tempLstAccountNumbers=[];
    this.licenseService.GetLicenseAccounts(0)
      .subscribe(st => {   
       var newOption = $('<option value=""></option>');
       $('#accountSelect').append(newOption);
        this.tempLstAccountNumbers=st;       
        setTimeout(function(){             
          $('#accountSelect').trigger('chosen:updated');  
       }, 500);
       this._loadingService.HideLoading("global-loading");

      }, error => this.error = <any>error);
  }

  GetLicenseById() {
    if (this.LicenseId != 0) {
      this.licenseService.GetLicenseById(this.LicenseId)
        .subscribe(st => {
          this.license = st;

          this.updateLicenseBasicSettingsFrm.controls['licenseId'].setValue(this.license.LicenseId);
          this.updateLicenseBasicSettingsFrm.controls['accountNumber'].setValue(this.license.AccountNumber);
          this.updateLicenseBasicSettingsFrm.controls['licenseeFirstName'].setValue(this.license.LicenseeFirstName);
          this.updateLicenseBasicSettingsFrm.controls['licenseeLastName'].setValue(this.license.LicenseeLastName);
          this.updateLicenseBasicSettingsFrm.controls['institutionName'].setValue(this.license.InstitutionName);
          this.updateLicenseBasicSettingsFrm.controls['address1'].setValue(this.license.Address1);
          this.updateLicenseBasicSettingsFrm.controls['address2'].setValue(this.license.Address2);
          this.updateLicenseBasicSettingsFrm.controls['city'].setValue(this.license.City);
          this.updateLicenseBasicSettingsFrm.controls['stateId'].setValue(this.license.StateId);
          this.updateLicenseBasicSettingsFrm.controls['countryId'].setValue(this.license.CountryId);
          this.updateLicenseBasicSettingsFrm.controls['zip'].setValue(this.license.Zip);
          this.updateLicenseBasicSettingsFrm.controls['emailId'].setValue(this.license.EmailId);
          this.updateLicenseBasicSettingsFrm.controls['phone'].setValue(this.license.Phone);
          this._loadingService.HideLoading("global-loading");

          this.UpdatePhoneValidation();
        },
        error => this.error = <any>error);
    }
  }

  AccountNumberChanged(LicenseId: number,AccountNumber:string) {
    if (LicenseId == 0) {
      this.updateLicenseBasicSettingsFrm.reset();
      this.updateLicenseBasicSettingsFrm.controls['licenseId'].setValue(0);
      this.updateLicenseBasicSettingsFrm.controls['countryId'].setValue(0);
      this.updateLicenseBasicSettingsFrm.controls['stateId'].setValue(0);
      return;
    }
    this._loadingService.ShowLoading("global-loading");
    this.LicenseId=LicenseId;
    this.AccountNumber=AccountNumber;
    this.GetLicenseById();
    return false;
  }

  AfterUpdateData(data, template) {
    if (data.Status == "false") {
      this.alerts = "<span>License profile update unsuccessfull.</span>";
    } else {
      this._confirmService.activate("License profile updated successfully.", "alertMsg");
    }
    this._loadingService.HideLoading("global-loading");
  }

  UpdateLicenseBasicSettings(template: TemplateRef<any>) {
    this.alerts = '';
    if (this.alerts == '') {
      this._loadingService.ShowLoading("global-loading");
      var obj = this.updateLicenseBasicSettingsFrm.value;
      return this.licenseService.UpdateLicenseBasicSettings(obj)
        .subscribe(
        n => (this.AfterUpdateData(n, template)),
        error => this.error = <any>error);
    }

  }

}