import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable, of } from 'rxjs';
import { PartnerRange } from 'src/app/models/partner-range.model';
import { PartnerRangeService } from 'src/app/services/partner-range.service';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AuthService } from 'src/app/auth/services/auth.service';
import { User } from 'src/app/models/user.model';
import { catchError, tap } from 'rxjs/operators';
import { DataBindingDirective } from '@progress/kendo-angular-grid';

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

  @ViewChild(DataBindingDirective) dataBinding: DataBindingDirective;
  public gridView: unknown[];

  partnerRange$: Observable<PartnerRange[]>;
  formRange: FormGroup;
  rangeIni = 0;
  rangeFin = 0;
  percent = 0;
  partnerRangeSelect: PartnerRange = null;
  loading = false;

  formFilter: FormGroup;

  public opened = false;
  selectedPartnerRange: PartnerRange;

  public resultDelete(status: string): void {
    console.log(`Dialog result: ${status}`);
    this.opened = false;
    if (status == 'yes') {
      this.deleteRange();
    }
  }


  constructor(
    private readonly partnerRangeService: PartnerRangeService,
    private route: ActivatedRoute,
    private router: Router,
    private authService: AuthService
  ) {
  }

  ngOnInit(): void {
    this.formFilter = new FormGroup({
      typeFilter: new FormControl('T', []),
    });
    this.partnerRangeService.getPartnerRange('T').subscribe(range => {
      this.gridView = range;
    });
    this.formRange = new FormGroup({
      id: new FormControl(),
      rangeIni: new FormControl(this.rangeIni, [Validators.required]),
      rangeFin: new FormControl(this.rangeFin, [Validators.required]),
      percentComiss: new FormControl(this.percent, [Validators.required]),
      type: new FormControl(),
    });
  }

  editPartnerRange(data) {
    console.log(data);
    this.partnerRangeSelect = data.dataItem as PartnerRange;
    this.formRange.patchValue({
      id: this.partnerRangeSelect.id,
      rangeIni: this.partnerRangeSelect.rangeIni,
      rangeFin: this.partnerRangeSelect.rangeFin,
      percentComiss: this.partnerRangeSelect.percentComiss,
      type: this.partnerRangeSelect.type,
    });
  //  this.router.navigate([`/partner/range/edit/range/${data.dataItem.id}`]);
  }

  confirmDelete(data: any) {
    console.log(data);
    this.selectedPartnerRange = data.dataItem as PartnerRange;
    this.opened = true;
  }

  createPartnerRange() {
    this.partnerRangeSelect = null;
    this.formRange.reset();
  }

  savePartnerRange() {
    console.log(this.formRange.value);
    const user = this.authService.getUser();
    console.log(this.formRange.get('rangeIni').value);
    if ( this.partnerRangeSelect == null ){
      this.partnerRangeSelect = new PartnerRange();
    }
    this.partnerRangeSelect.rangeIni = this.formRange.get('rangeIni').value;
    this.partnerRangeSelect.rangeFin = this.formRange.get('rangeFin').value;
    this.partnerRangeSelect.percentComiss = this.formRange.get('percentComiss').value;
    this.partnerRangeSelect.type = this.formRange.get('type').value;
    this.partnerRangeSelect.createUserId = user.id;
    this.partnerRangeSelect.updateUserId = user.id;

    this.loading = true;
    this.partnerRangeService.createOrReplace(this.partnerRangeSelect).pipe(
      tap(() => {
        this.searchRange();
        this.loading = false;
      }),
      catchError((error) => {
        console.log(error);
        return of(error.message);
      })
    ).subscribe();
  }

  searchRange() {
    const type = this.formFilter.get('typeFilter').value;
    this.partnerRangeService.getPartnerRange(type).subscribe(range => {
      this.gridView = range;
    });
  }

  deleteRange() {
    this.loading = true;
    this.partnerRangeService.DeletePartnerRangeById(this.selectedPartnerRange.id.toString())
      .pipe(
      tap(() => {
        this.searchRange();
        this.loading = false;
      }),
      catchError((error) => {
        console.log(error);
        return of(error.message);
      })
    ).subscribe();
  }

}
