import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { forkJoin, Observable, of, Subscription, throwError } from 'rxjs';
import { catchError, debounceTime, map, mergeMap, tap } from 'rxjs/operators';
import { CategoryPartner } from 'src/app/models/category-partner.model';
import { Customer } from 'src/app/models/customer.model';
import { Partner } from 'src/app/models/partner.model';
import { CustomerService } from 'src/app/services/customer.service';
import { LookupService } from 'src/app/services/lookup.service';
import { PartnerService } from 'src/app/services/partner.service';
import { ConsultaCepService } from 'src/app/shared/services/consulta-cep.service';
import { Seller } from '../../../models/seller.model';

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

  formPartner: FormGroup;
  partnerData: Partner;
  isloading: boolean;
  errorObject: any;

  subscriptionSeller: Subscription;
  sellers: Seller[];
  selectedSeller: Seller;

  subscriptionCategory: Subscription;
  categoryPartners: CategoryPartner[];
  selectedCategory: CategoryPartner;

  subscriptionPartner: Subscription;

  loadingCustomer = false;
  customer$: Observable<Customer[]>;
  selectedCustomer: Customer;

  showCommission = false;

  constructor(
    private cepService: ConsultaCepService,
    private lookupService: LookupService,
    private partnerService: PartnerService,
    private activeRoute: ActivatedRoute,
    private customerService: CustomerService,
    private router: Router,
  ) {
    this.formPartner = new FormGroup({
      name: new FormControl('', [Validators.required, Validators.minLength(10)]),
      cpf: new FormControl('', [Validators.required]),
      type: new FormControl('', [Validators.required]),
      rg: new FormControl('', [Validators.required]),
      professionalNumber: new FormControl('', [Validators.required]),
      phone: new FormControl('', [Validators.required]),
      email: new FormControl('', [Validators.required, Validators.email]),
      pixKey: new FormControl('', [Validators.required]),
      buyer: new FormControl('', [Validators.required]),
      customerId: new FormControl(null),
      customer: new FormControl(null),
      seller: new FormControl(null),
      sellerId: new FormControl(null),
      bank: new FormControl('', []),
      agencia: new FormControl('', []),
      conta: new FormControl('', []),
      zipCode: new FormControl('', [Validators.required]),
      address: new FormControl('', [Validators.required]),
      number: new FormControl('', [Validators.required]),
      complement: new FormControl('', []),
      neighborhood: new FormControl('', [Validators.required]),
      city: new FormControl('', [Validators.required]),
      state: new FormControl('', [Validators.required]),
      category: new FormControl(null),
      categoryId: new FormControl('', []),
      observer1: new FormControl('', []),
      observer2: new FormControl('', []),
    });

    this.formPartner.controls.type.valueChanges.pipe(
      debounceTime(100),
    ).subscribe(() => {
      console.log('alterando tipo do parceiro');
      this.filterCategory();
    });

  }


  ngOnInit(): void {

    const cpf = this.activeRoute.snapshot.paramMap.get('cpf');

    if (cpf != null) {
      this.subscriptionPartner = this.partnerService.getPartner(cpf)
        .pipe(
          tap((data) => this.partnerData = data),
          mergeMap(result => this.lookupService.getSellers()),
          tap((dataSeller) => this.sellers = dataSeller),
          mergeMap(result => this.lookupService.getCategoryPartner()),
          tap((dataCategory) => this.categoryPartners = dataCategory),
          mergeMap(result => this.customerService.getCustomerByQuery('customerId', (this.partnerData.customerId ?? 0).toString())),
          tap((resultApi) => {
            console.log(resultApi);
            const data: Customer[] = resultApi.data;
            this.selectedCustomer = resultApi[0];
            if (this.selectedCustomer != null) {
              this.handleFilterCustomer(this.selectedCustomer.name);
            }
          }),)
        .subscribe(result => {
          this.selectedSeller = this.sellers.find(s => s.sellerId === this.partnerData.sellerId);
          this.selectedCategory = this.categoryPartners.find(c => c.id === this.partnerData.categoryId);
          this.populatePartner(this.partnerData);
          this.showCommission = this.partnerData.type == "B";
        });
    }
  }

  ngOnDestroy(): void {
    if (this.subscriptionSeller) {
      this.subscriptionSeller.unsubscribe();
    }
    if (this.subscriptionCategory) {
      this.subscriptionCategory.unsubscribe();
    }
  }

  public submitForm(): void {
    this.formPartner.markAllAsTouched();
    console.log(this.formPartner.valid);
    console.log(this.formPartner.errors);
    //    if (this.formPartner.valid) {
    const data = JSON.stringify(this.formPartner.value);
    const partner: Partner = JSON.parse(data);
    console.log(JSON.stringify(partner));
    this.partnerService.createOrReplace(this.formPartner.value).pipe(
      tap(() => {
        this.isloading = false;
        this.router.navigate(['partner/list']);
      }),
      catchError((error) => {
        this.isloading = false;
        console.log(error);
        return of(error);
      })
    ).subscribe();
    //   }
    console.log(JSON.stringify(this.formPartner.value));
  }

  public clearForm(): void {
    this.formPartner.reset();
    this.router.navigate(['partner/list']);
  }

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

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

  searchPartner() {
    const serachText = this.formPartner.get('cpf').value;
    this.partnerService.getPartner(serachText).pipe(
      map(result => {
        if (result != null) {
          this.partnerData = result;
          this.populatePartner(this.partnerData);
        }
      }),
      tap(() => {
        this.isloading = false;
      }),
      catchError(err => {
        this.isloading = false;
        this.errorObject = err;
        return throwError(err);
      })).subscribe();
  }

  populatePartner(data: Partner) {

    this.formPartner.patchValue({
      name: data.name,
      cpf: data.cpf,
      type: data.type,
      rg: data.rg,
      professionalNumber: data.professionalNumber,
      phone: data.phone,
      email: data.email,
      buyer: (data.buyer === 'S' ? true : false),
      pixKey: data.pixKey,
      bank: data.bank,
      agencia: data.agencia,
      conta: data.conta,
      zipCode: data.zipCode,
      address: data.address,
      number: data.number,
      complement: data.complement,
      neighborhood: data.neighborhood,
      city: data.city,
      state: data.state,
      category: this.selectedCategory,
      seller: this.selectedSeller,
      observer1: data.observer1,
      observer2: data.observer2,
      customerId: data.customerId,
      categoryId: data.categoryId,
      sellerId: data.sellerId,
      commission: data.commission,
    });

    if (this.selectedSeller != null) {
      this.formPartner.patchValue({
        seller: this.selectedSeller
      });
    }

    if (this.selectedCategory != null) {
      this.formPartner.patchValue({
        category: this.selectedCategory
      });
    }

    if (this.selectedCustomer != null) {
      this.formPartner.patchValue({
        customer: this.selectedCustomer
      });
    }

  }

  selectSeller(seller: any) {
    this.selectedSeller = seller;
    this.formPartner.patchValue({
      sellerId: this.selectedSeller.sellerId,
    });
  }

  selectCategory(category: any) {
    this.selectedCategory = category;
    this.formPartner.patchValue({
      categoryId: this.selectedCategory.id,
    });
  }

  handleFilterCustomer(value) {
    if (value.length > 3) {
      this.loadingCustomer = true;
      this.customer$ = this.customerService.getCustomer(value);
      this.customer$.pipe(
        tap(() => this.loadingCustomer = false)
      ).subscribe((data) => console.log(data));
    }
  }

  selectCustomer(customer: any) {
    console.log(customer);
    this.selectedCustomer = customer;
    this.formPartner.patchValue({
      customerId: this.selectedCustomer.customerId,
    });
  }

  filterCategory() {
    const categories = this.categoryPartners;
    const partnerType = this.formPartner.get('type').value;
    this.categoryPartners = categories.filter(c => c.partnerType === partnerType);
    console.log(JSON.stringify(this.categoryPartners));
    this.showCommission = partnerType == "B";
  }

  parceiroBellaObra() {
    const typePartner = this.formPartner.get('type').value;
    console.log(typePartner);
    this.showCommission = typePartner == "B";
  }

}
