Skip to content

Instantly share code, notes, and snippets.

@BenevidesLecontes
Created April 27, 2017 19:02
Show Gist options
  • Save BenevidesLecontes/63aa3ee1785606ba7dd53d5006bf91e2 to your computer and use it in GitHub Desktop.
Save BenevidesLecontes/63aa3ee1785606ba7dd53d5006bf91e2 to your computer and use it in GitHub Desktop.
/**
* Created by benevideschissanga on 13/04/17.
*/
import {
AfterViewInit,
Component,
ElementRef,
HostListener,
Inject,
OnDestroy,
OnInit,
QueryList,
Renderer,
ViewChild,
ViewChildren
} from '@angular/core';
import {FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms';
import {CapitalizeNameNg2, FirstNamePipe} from '../../../pipes/pipes';
import {Http} from '@angular/http';
import {UIRouter} from 'ui-router-ng2';
import {isNumeric} from 'rxjs/util/isNumeric';
import {ValidationService} from '../../../ui-kit.components/ui-kit.message/validation.service';
import {wiAuthenticationService} from 'wiseit';
import {ClientesService} from '../services/clientes.services';
import {Subscription} from 'rxjs/Subscription';
import {PopoverDirective} from 'ngx-bootstrap';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/last';
import 'rxjs/add/observable/throw';
@Component({
selector: 'app-novo-client',
templateUrl: 'atendimento/clientes/cliente-novo/cliente-novo.html'
})
export class NovoClienteComponent implements OnInit, OnDestroy, AfterViewInit {
public selectedClient = {
'emails': [{}],
'enderecos': [{}],
'sexo': 'M',
'telefones': [{}],
'codigo': undefined,
'nome': undefined,
'apelido': undefined,
'cpf': undefined,
'nascimento': undefined,
'emailPreferencial': 0,
'telefonePreferencial': 0,
'enderecoPreferencial': 0
};
@ViewChildren('telEl') childChildren: QueryList<ElementRef>;
optionsTipoTel = [];
optionsTipoEndereco = [];
configTipo: any = {
searchField: ['nome'],
create: false,
plugins: ['dropdown_direction', 'no_results'],
dropdownDirection: 'auto',
valueField: 'codigo',
labelField: 'nome',
};
formAddCE: FormGroup;
cpf: number;
nascimento: Date;
nome: string;
sexo: string;
apelido: string;
datepickerOpts = {
autoclose: true,
endDate: new Date(),
icon: 'glyphicon glyphicon-calendar',
language: 'pt-BR',
placeholder: 'Insira uma data',
orientation: 'auto bottom',
container: '.content'
};
@ViewChild('cpfEl') cpfEl: ElementRef;
@ViewChildren('pop') popQueryList: QueryList<PopoverDirective>;
cpfElForValidation: ElementRef;
private _subscription: Subscription;
private dddIndex: number;
private telElForValidation: ElementRef[];
counter = 0;
constructor(private formBuilder: FormBuilder,
private http: Http, private render: Renderer,
@Inject('uiMessageService') private uiMessageService: any,
private router: UIRouter,
@Inject('uiModalService') private uiModalService: any,
@Inject('$rootScope') private $rootScope: any,
@Inject('wiAuthenticationService') private wiAuthenticationService: wiAuthenticationService,
private clienteService: ClientesService) {
}
ngOnInit(): void {
if (this.wiAuthenticationService.isLoggedIn()) {
this.clienteService.getClassificacaoContato();
this._subscription = this.clienteService.classificaoChange.subscribe((value) => {
if (value && value['TELEFONE']) {
value['TELEFONE'].map(item => {
item.nome = new CapitalizeNameNg2().transform(item.nome);
});
this.optionsTipoTel = value['TELEFONE'];
}
if (value && value['ENDERECO']) {
value['ENDERECO'].map(item => {
item.nome = new CapitalizeNameNg2().transform(item.nome);
});
this.optionsTipoEndereco = value['ENDERECO'];
}
});
}
this.formAddCE = this.formBuilder.group({
cpf: ['', null, ValidationService.asyncCpfValidator],
nome: ['', Validators.required],
nascimento: [''],
apelido: [''],
sexo: ['', Validators.required],
emails: this.formBuilder.array([this.initEmails()]),
telefones: this.formBuilder.array([this.initTelefones()]),
enderecos: this.formBuilder.array([this.initEnderecos()])
});
this.cpfElForValidation = this.cpfEl;
}
ngAfterViewInit(): void {
this.telElForValidation = this.childChildren.toArray();
ValidationService.telEl = this.childChildren.toArray();
}
initEmails() {
return this.formBuilder.group({
email: ['']
});
}
addEmail() {
const control = < FormArray > this.formAddCE.controls['emails'];
control.push(this.initEmails());
}
removeEmail(i: number) {
const control = < FormArray > this.formAddCE.controls['emails'];
control.removeAt(i);
if (control.length === 0) {
this.selectedClient.emailPreferencial = 0;
}
}
initTelefones() {
if (this.childChildren) {
this.childChildren.changes.subscribe(children => {
this.telElForValidation = children.toArray();
ValidationService.telEl = children.toArray();
});
}
return this.formBuilder.group({
telefone: [''],
ddd: [''],
tipo: ['']
});
}
addTelefone() {
const control = < FormArray > this.formAddCE.controls['telefones'];
control.push(this.initTelefones());
}
removeTelefone(i: number) {
const control = < FormArray > this.formAddCE.controls['telefones'];
control.removeAt(i);
if (control.length === 0) {
this.selectedClient.telefonePreferencial = 0;
}
}
initEnderecos() {
return this.formBuilder.group({
complemento: [''],
numero: [''],
tipo: ['1'],
logradouro: [''],
bairro: [''],
uf: [''],
cep: [''],
cidade: [''],
tipoLogradouro: ['']
});
}
addEndereco() {
const control = < FormArray > this.formAddCE.controls['enderecos'];
control.push(this.initEnderecos());
}
removeEndereco(i: number) {
const control = < FormArray > this.formAddCE.controls['enderecos'];
control.removeAt(i);
if (control.length === 0) {
this.selectedClient.enderecoPreferencial = 0;
}
}
isRequiredTel(item): any {
const condition = (item.telefone && item.telefone.value && item.telefone.value !== '') ||
item.ddd && item.ddd.value && item.ddd.value !== '' && isNumeric(item.ddd.value);
return condition ? condition : false;
};
requiredAdress(form): boolean {
return form.controls.complemento.value ||
form.controls.numero.value ||
form.controls.tipo.value ||
form.controls.logradouro.value ||
form.controls.bairro.value ||
form.controls.uf.value ||
form.controls.cep.value ||
form.controls.cidade.value;
}
makeNick(nome: string) {
if (nome && !this.selectedClient.apelido || nome && this.selectedClient.apelido === '') {
this.selectedClient.apelido = new FirstNamePipe().transform(nome);
}
};
addCE(form) {
console.log(form);
}
@HostListener('click', ['$event']) onClick(event) {
this.popQueryList.forEach((item) => {
if (event.srcElement.className !== `icon icon-info-dots` && item && item.isOpen) {
item.hide();
}
});
}
dddKeyUp(event: Event | any, to: string, value: string, index: number) {
const key = event.which || event.keyCode;
this.dddIndex = index;
if ((value && value.length === 2) && ((key >= 48 && key <= 57) || (key >= 96 && key <= 105))) {
this.onFocus(to);
}
};
onFocus(to: string) {
const elementToFocus = (<HTMLInputElement>document.getElementById(to));
elementToFocus.focus();
}
autoCelClass(numero) {
let typeTel;
const firstNum = (numero && numero.length > 0) ? parseInt(numero.substring(0, 1), 10) : 0;
const isCel = (firstNum === 9 || firstNum === 8 || firstNum === 7);
if (numero && ((!typeTel && numero.length > 0) || numero.length === 1)) {
if (isCel) {
typeTel = this.optionsTipoTel.find((item) => {
if (item.nome.toUpperCase() === 'CELULAR') {
return item.codigo;
}
});
} else {
typeTel = this.optionsTipoTel.find((item) => {
if (item.nome.toUpperCase() === 'RESIDENCIAL') {
return item.codigo;
}
});
}
}
return typeTel ? typeTel.codigo : null;
};
updateTelefoneValidity() {
// this.formAddCE.controls['telefones'].controls.forEach((item) => {
// item.controls.telefone.patchValue(item.controls.telefone.value);
// });
}
ngOnDestroy() {
if (this._subscription) {
this._subscription.unsubscribe();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment