adduser.component.ts 10.3 KB
import { Component, OnInit, AfterViewInit, ViewChild, ElementRef, HostListener } from '@angular/core';
import { UserService } from '../userentity/user.service';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { User,License } from '../userentity/datamodel';
import { Http, Response } from '@angular/http';
import { GlobalService } from '../../shared/global';
import { LicenseService } from '../licenseentity/license.service';
//import { DBOperation } from 'S';
import { Observable } from 'rxjs/Observable';
import { ConfirmService } from '../../shared/confirm/confirm.service';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/filter';
import { LoadingService } from '../../shared/loading.service';

@Component({
  templateUrl: './adduser.component.html' // '../../../../../wwwroot/html/UpdateProfile/updateuserprofile.component.html'
})

export class AddUser implements OnInit, AfterViewInit {
  user: User;
  baseUrl: string = "User";
  adduserFrm: FormGroup;
  useFname: string;
  error;
  status: boolean;
  alerts: string;
  emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";
  public UserTypeList: any;
  public AccountNumberList: any;
  tempLstAccountNumbers: any;
  public ProductEditionList: any;
  modalTitle: string;
  accountDropDownText: string;
  loopIdx1: number;
  loopIdx2: number;
  lastScrollPos: number;
  license: License;
  LicenseTypeId:number=0;
  //@ViewChild("profileModal")
  //profileModal: ModalComponent;
  //errorMessage: any;
  @ViewChild('accountNo') accountNodiv: ElementRef;
  isDropup = false;

  constructor(private _loadingService: LoadingService, private userservice: UserService, private router: Router, private fb: FormBuilder, private http: Http,
    private _confirmService: ConfirmService, public commonService: GlobalService,private licenseService: LicenseService,
  ) { }

  ngOnInit(): void {

    this.user = new User();
    this.alerts = '';
    this.accountDropDownText = 'Select';
    this.loopIdx1 = 0;
    this.loopIdx2 = 0;
    this.lastScrollPos = 0
    //this.userservice.GetUserById(this.UserId);
    this.adduserFrm = this.fb.group({
      id: [''],
      UserName: ['', [Validators.required, Validators.minLength(8)]],
      Password: ['', [Validators.required, Validators.minLength(8)]],
      ConfirmPassword: ['', Validators.required],
      FirstName: ['', Validators.required],
      LastName: ['', Validators.required],
      EmailId: ['', Validators.required],
      AccountNumberId: ['', Validators.required],
      UserTypeId: ['', Validators.required],
      ProductEditionId: ['', Validators.required]
    });
    debugger
    this._loadingService.ShowLoading("global-loading");
    this.bindUsers();
    this.GetAccountNumber();
    this.GetUserTypeByLicenseId();
    this._loadingService.HideLoading("global-loading");
  }
  ngAfterViewInit() {
    this.CheckDropDownOrUp(this.accountNodiv.nativeElement);
  }
  redirect() {
    this.router.navigate(['/']);
  }
  GetUserTypeByLicenseId() {
    debugger;
    var Accountnumber = this.adduserFrm.controls['AccountNumberId'].value;
    if (Accountnumber == "") { Accountnumber = 0 }
    this.userservice.GetUserTypeByLicenseType({
      AccountNumberId: Accountnumber
    }).subscribe(x => { this.UserTypeList = x; }, error => this.error = <any>error);
  }
  GetAccountNumber() {
    this.userservice.GetAccountNumber()
      .subscribe(x => {
        this.AccountNumberList = x;
        this.tempLstAccountNumbers = [];
        this.loopIdx1 = 0;
        this.loopIdx2 = 0;
        this.lastScrollPos = 0;
        this.tempLstAccountNumbers = [];
        if (this.commonService.UserType > 2) {
          this.accountDropDownText = this.commonService.AccountNumber;
          this.tempLstAccountNumbers.push(this.accountDropDownText);
          this.AccountNumberChanged(this.commonService.AccLicId, this.accountDropDownText);
        }
        else {
          for (var i = 0; i < 50; i++) {
            this.tempLstAccountNumbers.push(this.AccountNumberList[this.loopIdx2++]);
          }
        }
      },
      error => this.error = <any>error);
  }

  GetProductEdition() {
    this.userservice.GetProductEdition({
      AccountNumberId: this.adduserFrm.controls['AccountNumberId'].value
    })
      .subscribe(x => { console.log(x); this.ProductEditionList = x }, error => this.error = <any>error);
  }
  //BindUserTypeAndProductEdition(deviceValue) {
  //this.GetUserTypeByLicenseId();
  //this.GetProductEdition();
  //}
  AccountNumberChanged(LicenseId: number, SelectText: string) {

    this.accountDropDownText = SelectText;
    this.adduserFrm.controls['AccountNumberId'].setValue(LicenseId);
    this.GetUserTypeByLicenseId();
    this.GetProductEdition();   
      
      this.licenseService.GetLicenseById(LicenseId)
        .subscribe(st => {        
          this.license = st;
          this.LicenseTypeId=this.license.LicenseTypeId;
         
        },
        error => this.error = <any>error);
    
    return false;
  }

  onScroll($event) {
    if (this.lastScrollPos > $event.target.scrollTop) {
      for (var i = 0; i < 1000; i++) {
        if (this.loopIdx1 > 0)
          this.tempLstAccountNumbers.unshift(this.AccountNumberList[this.loopIdx1--]);
      }
    }
    else {
      for (var i = 0; i < 1000; i++) {
        if (this.loopIdx2 < this.AccountNumberList.length)
          this.tempLstAccountNumbers.push(this.AccountNumberList[this.loopIdx2++]);
      }
    }
    this.lastScrollPos = $event.target.scrollTop;
  }

  onOpenChange(data: boolean): void {
    if (!data) {
      this.loopIdx1 = 0;
      this.loopIdx2 = 0;
      this.tempLstAccountNumbers = [];
      for (var i = 0; i < 50; i++) {
        this.tempLstAccountNumbers.push(this.AccountNumberList[this.loopIdx2++]);
      }
    }
  }

  onKeyPress($event) {
    let FindItem = this.AccountNumberList.find(C => (C.AccountNumber.toLowerCase().indexOf($event.key) == 0));
    let prevIdx = 0;
    if (FindItem != null) {
      for (var i = 0; i < this.AccountNumberList.length; i++) {
        if (FindItem.Id == this.AccountNumberList[i].Id) {
          prevIdx = i;
          break;
        }
      }
      this.tempLstAccountNumbers = [];
      this.loopIdx1 = prevIdx;
      this.loopIdx2 = prevIdx;
      for (var i = 0; i < 50; i++) {
        if (this.loopIdx2 < this.AccountNumberList.length)
          this.tempLstAccountNumbers.push(this.AccountNumberList[this.loopIdx2++]);
      }
      this.lastScrollPos = 0;
      $event.target.nextElementSibling.scrollTop = 0;
    }
  }

  public AddUser() {

    this.alerts = '';
    
    if (this.adduserFrm.value.UserName == '') {
      this.alerts += '<span>User Name of minimum 8 characters is required.</span>';
    }
    if (this.adduserFrm.value.Password == '') {
      this.alerts += '</br><span>Password of minimum 8 characters is required.</span>';
    }
   
    if (this.adduserFrm.value.ConfirmPassword == '') {
      this.alerts += '</br><span>Confirm Password is required.</span>';
    }
    if (this.adduserFrm.value.EmailId == '') {
      this.alerts += '</br><span>Email Id is required.</span>';
    }
    //if(this.LicenseTypeId!=1)
    //{        
    if (this.adduserFrm.value.FirstName == '') {
    this.alerts += '</br><span>First Name is required.</span>';
    }
    if (this.adduserFrm.value.LastName == '') {
    this.alerts += '</br><span>Last Name is required.</span>';
     }
     // }
    if (this.adduserFrm.value.Password != this.adduserFrm.value.ConfirmPassword) {
      this.alerts += '</br><span>Password and confirm password must be same</span>';
    }
    if (this.adduserFrm.value.AccountNumberId == '0') {
      this.alerts += '</br><span>Please select account number</span>';
    }
    if (this.adduserFrm.value.UserTypeId == '0') {
      this.alerts += '</br><span>Please select user type</span>';
    }
    if (this.adduserFrm.value.ProductEditionId == '0') {
      this.alerts += '</br><span>Please select product edition</span>';
    }
    if (this.alerts == '') {
      var AddUserEntity = this.adduserFrm.value;
      return this.userservice.InsertUser(AddUserEntity)
        .subscribe(
        n => (this.AfterInsertData(n)),
        error => {
          this.error = <any>error;
          this.alerts = "<span>" + this.error + "</span>";
        });
    }

  }
  AfterInsertData(data) {
    //debugger;
    if (data == "User added successfully") {
      this.alerts = '';
      this._confirmService.activate("User added successfully.", "alertMsg");
    }

  }
  ResetForm() {
    this._buildForm();
  }
  _buildForm() {
    this.adduserFrm = this.fb.group({
      id: [''],
      UserName: [""],
      Password: [""],
      ConfirmPassword: [""],
      FirstName: [""],
      LastName: [""],
      EmailId: [""],
      AccountNumberId: ["0"],
      UserTypeId: ["0"],
      ProductEditionId: ["0"]

    });
  }
  CheckDropDownOrUp(elm: any) {
    var dropDownTop = elm.children[0].offsetTop;
    var dropDownBottom = elm.children[0].offsetTop + elm.children[0].offsetHeight + 330;
    var screenBottom = (window.innerHeight) + window.pageYOffset;
    if (dropDownTop <= screenBottom && screenBottom <= dropDownBottom) {
      this.isDropup = true;
    }
    else {
      this.isDropup = false;
    }
  }
  @HostListener('window:scroll', ['$event'])
  onWindowScroll(event) {
    // console.debug("Scroll Event", document.body.scrollTop);
    // see András Szepesházi's comment below
    //console.debug("Scroll Event", window.pageYOffset );
    this.CheckDropDownOrUp(this.accountNodiv.nativeElement);
  }

  @HostListener('window:resize', ['$event'])
  onWindowResize(event) {
    this.CheckDropDownOrUp(this.accountNodiv.nativeElement);
  }
  bindUsers() {

    //console.log(data);
    //alert(JSON.stringify(data));
    //this.user = data[0];


    this.adduserFrm.controls['id'].setValue(0)
    this.adduserFrm.controls['FirstName'].setValue('')
    this.adduserFrm.controls['LastName'].setValue('')
    this.adduserFrm.controls['EmailId'].setValue('')
    this.adduserFrm.controls['UserName'].setValue('')
    this.adduserFrm.controls['Password'].setValue('')
    this.adduserFrm.controls['ConfirmPassword'].setValue('')
    this.adduserFrm.controls['AccountNumberId'].setValue(0)
    this.adduserFrm.controls['UserTypeId'].setValue(0)
    this.adduserFrm.controls['ProductEditionId'].setValue(0)

  }
}