import { Component, OnInit, ViewChild } from '@angular/core';
import { DateRangeService, SelectionRange } from '@progress/kendo-angular-dateinputs';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { arrowRightIcon, paperclipIcon } from '@progress/kendo-svg-icons';
import { ExtractPartner } from 'src/app/models/extract-partner.model';
import { PartnerService } from 'src/app/services/partner.service';
import { Partners } from 'src/app/models/partners.model';
import { FormGroup } from '@angular/forms';

@Component({
  selector: 'app-extract-partner',
  templateUrl: './extract-partner.component.html',
  styleUrls: ['./extract-partner.component.css']
})
export class ExtractPartnerComponent implements OnInit {
  public range: SelectionRange = { start: null, end: null };
  constructor (
    private readonly partnerService: PartnerService) {}

  extractPartner$: Observable<ExtractPartner[]>;
  public gridData: ExtractPartner[] = [];
  public loading: boolean = false;
  public icons = { arrowRight: arrowRightIcon };

  formFilter: FormGroup;
  partners$: Observable<Partners[]>;
  selectedPartner: Partners;

  @ViewChild('daterange', { read: DateRangeService })
  public service: DateRangeService;

  //dados do parceiro
  partnerId: number = 0;
  partnerName: string = '';
  partnerType: string = '';

  ngOnInit(): void {
    this.partners$ = this.partnerService.getPartnerByQuery('T', null, null);

    if (localStorage.getItem('user-partner') != null ) {
      const dataPartner = JSON.parse(localStorage.getItem('user-partner'));
      this.partnerId = dataPartner.id;
      this.partnerName = dataPartner.username + ' (Código: ' + dataPartner.id + ')';
      this.partnerType = dataPartner.type;
    }
  }

  getComission() {
    if ( this.selectedPartner == null ) {
      return;
    }
    this.loading = true;
    const partnerId = this.selectedPartner.id;
    this.partnerService.getExtractPartner(partnerId, this.range.start, this.range.end)
      .pipe(
        map(response => {
          this.gridData = response;
          console.log(response);
          this.loading = false;
        }),
        catchError(err => {
          this.loading = false;
          console.log(err);
          return of();
        })
      ).subscribe();
  }

  public selectPartner(partner: any) {
    this.selectedPartner = null;
    if (partner) {
      this.selectedPartner = partner;
    }
  }


}
