import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable, of, Subscription, throwError } from 'rxjs';
import { PartnerService } from 'src/app/services/partner.service';
import { Partners } from 'src/app/models/partners.model';
import { ConsultaCepService } from 'src/app/shared/services/consulta-cep.service';
import { LookupService } from 'src/app/services/lookup.service';
import { CustomerService } from 'src/app/services/customer.service';
import { Partner } from 'src/app/models/partner.model';
import { Seller } from 'src/app/models/seller.model';
import { CategoryPartner } from 'src/app/models/category-partner.model';
import { Customer } from 'src/app/models/customer.model';
import { catchError, map, tap } from 'rxjs/operators';
import { PartnerCategoryService } from 'src/app/services/partner-category.service';
import { Place } from 'src/app/models/places.model';
import { DataBindingDirective } from '@progress/kendo-angular-grid';
import { process } from "@progress/kendo-data-query";
import { AuthService } from 'src/app/auth/services/auth.service';


@Component({
  selector: 'app-partners',
  templateUrl: './partners.component.html',
  styleUrls: ['./partners.component.scss']
})
export class PartnersComponent implements OnInit, OnDestroy {
  @ViewChild(DataBindingDirective) dataBinding: DataBindingDirective;
  public gridView: unknown[];
  formFilter: FormGroup;
  partners$: Observable<Partners[]>;
  partners: Partners[] = [];

  formPartner: FormGroup;

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

  subscriptionSeller: Subscription;
  sellers: Seller[];
  selectedSeller: Seller;
  sellers$: Observable<Seller[]>;

  subscriptionCategory: Subscription;
  categoryPartners: CategoryPartner[];
  filterCategoryPartners: CategoryPartner[];
  selectedCategory: CategoryPartner;
  categoryPartners$: Observable<CategoryPartner[]>;

  subscriptionPartner: Subscription;

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

  places$: Observable<Place[]>;
  subscriptionPlaces: Subscription;
  places: Place[] = [];
  selectedPlace: Place;

  public opened = false;

  partnerType = 'M';

  showCommission = false;

  constructor(
    private readonly partnerService: PartnerService,
    private route: ActivatedRoute,
    private router: Router,
    private cepService: ConsultaCepService,
    private lookupService: LookupService,
    private activeRoute: ActivatedRoute,
    private customerService: CustomerService,
    private readonly partnerCategoryService: PartnerCategoryService,
    private readonly authService: AuthService,
  ) {
    this.formFilter = new FormGroup({
      cpf: new FormControl(null),
      name: new FormControl(null),
      type: new FormControl('T'),
    });
    this.formPartner = new FormGroup({
      name: new FormControl('', [Validators.required]),
      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(''),
      buyer: new FormControl(''),
      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]),
      ibgeCode: new FormControl('', []),
      place: new FormControl(null, [Validators.required]),
      placeId: new FormControl(null, []),
      category: new FormControl(null),
      categoryId: new FormControl('', []),
      observer1: new FormControl(''),
      observer2: new FormControl(''),
      commission: new FormControl(''),
      userId: new FormControl(''),
    });
  }

  ngOnInit(): void {
    this.categoryPartners$ = this.partnerCategoryService.getPartnerCategory('', 'T');
    this.subscriptionCategory = this.categoryPartners$
      .subscribe(data => {
        this.categoryPartners = data;
        this.filterCategoryPartners = data;
      });
    this.places$ = this.lookupService.getPlaces();
    this.subscriptionPlaces = this.places$.subscribe(data => this.places = data);
    this.sellers$ = this.lookupService.getSellers();
    this.subscriptionSeller =  this.sellers$.subscribe(data => this.sellers = data);
    this.formPartner.valueChanges.subscribe(data => {
      const type = this.formPartner.get('type').value;
      this.showCommission = type == 'B';
    });
  }

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

  getPartners()  {
    const type = this.formFilter.get('type').value;
    const cpf = this.formFilter.get('cpf').value;
    const name = this.formFilter.get('name').value;

    this.partners$ = this.partnerService.getPartnerByQuery(type, cpf, name);
    this.subscriptionPartner = this.partners$.subscribe(data => {
      this.partners = data;
      console.log(data);
      this.gridView = process(this.partners, {}).data;
      this.dataBinding.skip = 0;
    });
  }

  editPartner(data) {
    console.log(data);
    this.formPartner.reset();
    const selectPartner = data.dataItem as Partner;
    const serachText = data.dataItem.cpf;
    this.partnerService.getPartner(serachText).pipe(
      map(result => {
        if (result != null) {
          this.partnerData = result;
          this.populatePartner(this.partnerData);
        }
      }),
      tap(() => {
        this.isloading = false;
        this.opened = true;
      }),
      catchError(err => {
        this.isloading = false;
        this.errorObject = err;
        return throwError(err);
      })).subscribe();
  }

  open() {
    this.formPartner.reset();
    this.opened = true;
  }

  close() {
    this.opened = false;
  }


  public submitForm(): void {
    this.formPartner.markAllAsTouched();
    console.log(this.formPartner.valid);
    console.log(this.formPartner.errors);
    const dataUser = localStorage.getItem('user');
    const user = JSON.parse(dataUser);
    this.formPartner.patchValue({
      userId: user.id,
    });

    const data = JSON.stringify(this.formPartner.value);
    console.log("DADOS DO FORMULARIO: " + data);
    const partner: Partner = JSON.parse(data);
    console.log(JSON.stringify(partner));

    this.partnerService.createOrReplace(this.formPartner.value).pipe(
      tap((resultData: Partner) => {
        this.isloading = false;
        this.opened = false;
        const category = this.categoryPartners.find(c => c.id === resultData.categoryId);
        const partnerData = new Partners();
        partnerData.id   = resultData.id;
        partnerData.name = resultData.name;
        partnerData.createDate = resultData.createDate;
        partnerData.userCreate = resultData.userCreate;
        partnerData.updateDate = resultData.updateDate;
        partnerData.userUpdate = resultData.userUpdate;

        if ( category != null) {
          partnerData.category = category.name;
        }
        partnerData.cpf = resultData.cpf;
        partnerData.phone = resultData.phone;
        partnerData.type = (resultData.type === 'P') ? 'PARCEIRO' :
              (resultData.type === 'M') ? 'MESTRE JURUNENSE' :  (resultData.type === 'B') ? 'BELLA OBRA' : 'NÃO INFORMADO';
        const partnerBD = this.partners.find(p => p.id === resultData.id);
        const index = this.partners.indexOf(partnerBD);
        if ( index === -1) {
          this.partners.push(partnerData);
        } else {
          this.partners[index] = partnerData;
        }
      }),
      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.opened = false;
  }

  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,
      ibgeCode: dadosCep.codigo_ibge,
    });
    console.log(JSON.stringify(this.formPartner.value));
  }

  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) {

    if ( data.sellerId != null) {
      const sellerPartner = this.sellers.find(s => s.sellerId === data.sellerId);
      if ( sellerPartner != null) {
        this.selectedSeller = sellerPartner;
      }
    }

    if ( data.categoryId != null) {
      const category = this.categoryPartners.find(c => c.id === data.categoryId);
      if ( category != null) {
        this.selectedCategory = category;
      }
    }

    if ( data.placeId != null) {
      const place = this.places.find(p => p.id === data.placeId);
      if ( place != null) {
        this.selectedPlace = place;
      }
    }

    this.filterCategory(data.type);
    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,
      ibgeCode: data.ibgeCode,
      address: data.address,
      number: data.number,
      complement: data.complement,
      neighborhood: data.neighborhood,
      city: data.city,
      state: data.state,
      category: this.selectedCategory,
      seller: this.selectedSeller,
      place: this.selectedPlace,
      observer1: data.observer1,
      observer2: data.observer2,
      customerId: data.customerId,
      categoryId: data.categoryId,
      sellerId: data.sellerId,
      placeId: data.placeId,
      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
      });
    }

    if ( this.selectedPlace != null ) {
      this.formPartner.patchValue({
        place: this.selectedPlace
      });
    }

  }

  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,
    });
  }

  selectPlace(place: any) {
    this.selectedPlace = place;
    this.formPartner.patchValue({
      placeId: this.selectedPlace.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,
    });
  }

  categoryDisabled(itemArgs: { dataItem: any; index: number }) {
    return itemArgs.dataItem.partnerType === this.partnerType;
  }

  filterCategory(type: any) {
    this.filterCategoryPartners = this.categoryPartners.filter(c => c.partnerType == type);
    console.log(type + ' - ' + this.formPartner.get('commission').value);
    if ( type == "B" && this.formPartner.get('commission').value == null) {
      this.formPartner.patchValue({
        commission: '4'
      });

    }
  }

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

  inputPercentPartner() {
    console.log(this.authService.userAction(1, 1, 1));
    return this.authService.userAction(1, 1, 1);
  }

}
