import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { DialogCloseResult, DialogRef, DialogService } from '@progress/kendo-angular-dialog';
import { EMPTY, Observable, throwError } from 'rxjs';
import { catchError, map, switchMap, take, tap } from 'rxjs/operators';
import { Customer } from 'src/app/models/customer.model';
import { ResultApi } from 'src/app/models/result-api.model';
import { CustomerService } from 'src/app/services/customer.service';
import { MessageService } from 'src/app/services/messages.service';
import { ConsultaCepService } from 'src/app/shared/services/consulta-cep.service';

@Component({
  selector: 'app-create-customer',
  templateUrl: './create-customer.component.html',
  styleUrls: ['./create-customer.component.scss']
})
export class CreateCustomerComponent implements OnInit {

  public phoneNumberValue = '';
  public phoneNumberMask = '(99) 00000-0000';
  public cpfMask = '000.000.000-00';
  public cnpjMask = '00.000.000/0000-00';
  public customer: Customer;
  public isloading = false;
  public errorObject: any;
  public result;
  loaderVisible = false;
  inSalveCustomer = false;
  @ViewChild('formCustomer') formCustomer: ElementRef;
  @ViewChild('inputCpf') inputCpf: ElementRef;

  public form: FormGroup;

  public customerData: any = {
    company: false,
    cpfCnpj: '',
    name: '',
    numberState: '',
    cellPhone: '',
    whatsapp: false,
    email: '',
    address: '',
    addressNumber: '',
    complement: '',
    neighborhood: '',
    city: '',
    state: '',
    zipCode: '',
    notifications: true,
    typeAddress: 'N'
  };

  constructor(private readonly customerService: CustomerService,
              private dialogService: DialogService,
              private dialogsService: MessageService,
              private cepService: ConsultaCepService) {
    this.form = new FormGroup({
      company: new FormControl(this.customerData.company, [
        Validators.required,
      ]),
      cpfCnpj: new FormControl(this.customerData.cpfCnpj, [
        Validators.required,
      ]),
      name: new FormControl(this.customerData.name, [
        Validators.required,
      ]),
      whatsapp: new FormControl(this.customerData.whatsapp, [
        Validators.required,
      ]),
      numberState: new FormControl(this.customerData.numberState, []),
      cellPhone: new FormControl(this.customerData.cellPhone, [
        Validators.required,
      ]),
      email: new FormControl(this.customerData.email, [Validators.required]),
      address: new FormControl(this.customerData.address, [Validators.required]),
      addressNumber: new FormControl(this.customerData.addressNumber, [Validators.required]),
      neighborhood: new FormControl(this.customerData.neighborhood),
      complement: new FormControl(this.customerData.complement),
      city: new FormControl(this.customerData.city),
      state: new FormControl(this.customerData.state),
      zipCode: new FormControl(this.customerData.zipCode),
      notifications: new FormControl(this.customerData.notifications),
      comments: new FormControl(this.customerData.comments),
      typeAddress: new FormControl(this.customerData.typeAddress)
    });
  }

  public showConfirmation(mensage: string) {
    if (this.inSalveCustomer) {
      return;
    }
    console.log(this.form.value);
    const result$ = this.dialogsService.confirmResult;
    this.inSalveCustomer = true;
    result$.asObservable()
      .pipe(
        take(1),
        switchMap(result => result ? this.customerService.createCustomer(this.form.value) : EMPTY)
      ).subscribe(
        successCreate => {
          this.inSalveCustomer = false;
          return successCreate;
        }, err => {
          this.inSalveCustomer = false;
          err;
        }
      );
    this.dialogsService.showConfirmation('Confirmação', mensage);
  }

  ngOnInit(): void {
  }

  cpfCadastrado(data: Customer) {
    const result$ = this.dialogsService.confirmResult;
    result$.asObservable()
      .pipe(
        take(1),
        map(result => result ? this.populateCustomer(data) : this.setFocus('inputCpf')),
        // switchMap(result => result ? console.log(result) : EMPTY)
      ).subscribe(
        successCreate => {
          return successCreate;
        }, err => err
      );
    this.dialogsService.showConfirmation('Confirmação', 'Cliente já cadastrado, deseja alterar seu cadastro?');
  }

  populateCustomer(data: Customer) {
    this.form.patchValue({
      name: data.name,
      cellPhone: data.cellPhone,
      email: data.email,
      zipCode: data.zipCode,
      address: data.address,
      addressNumber: data.addressNumber,
      complement: data.complement,
      neighborhood: data.neighborhood,
      city: data.city,
      state: data.state,
      mensage: data.allowMessage,
      typeAddress: data.addressType
    });

  }

  searchCustomerByDocument() {
    const fieldCpf = 'cpfCnpj';
    const cpf = this.form.value[fieldCpf];
    this.isloading = true;
    this.errorObject = null;
    this.customerService.getCustomerbyCpf(cpf).pipe(
      map(result => {
        if ( result.data != null) {
          this.customer = result.data;
          console.log(result);
          this.cpfCadastrado(result.data);
        }
      }),
      tap(() => {
        this.isloading = false;
      }),
      catchError(err => {
        this.isloading = false;
        this.errorObject = err;
        console.log(err);
        return throwError(err);
      })).subscribe();
  }

  setFocus(name) {
    this.inputCpf.nativeElement.setFocus();
    console.log(name);
/*    const ele =
    if (ele) {
      ele.focus();
    }*/
  }

  createCustomer() {
    console.log(this.form.value);
    const result$ = this.customerService.createCustomer(this.form.value);
    result$.pipe(
      map(c => console.log('cliente cadastrado')),
    ).subscribe();
  }

  consultaCep() {
    const cep = this.form.get('zipCode').value;
    if (cep != null && cep !== '') {
      this.cepService.consultaCep(cep)
        .subscribe(
          dados => {
            this.populateAddress(dados);
          });
    }
  }

  populateAddress(dadosCep: any) {
    console.log(dadosCep);
    this.form.patchValue({
      address: dadosCep.logradouro,
      complement: dadosCep.complemento,
      neighborhood: dadosCep.bairro,
      city: dadosCep.localidade,
      state: dadosCep.uf
    });
  }

}
