import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute, Router } from '@angular/router';
import { lastValueFrom, map } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { DownoloadSubcontratistInfo, ResponseDataSubcontratist, ResponseDataSubcontratistInfo } from 'src/app/interfaces/personal-managment/subcontractist.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { SubcontratistService } from 'src/app/services/personal-management/subcontratist.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-contract-history',
  templateUrl: './contract-history.component.html',
  styleUrls: ['./contract-history.component.css']
})
export class ContractHistoryComponent implements OnInit {

  public idSubcontratist: string;
  public isLoading: boolean;
  public isLoadingForm: boolean;

  public btnSmall: boolean;

  // Para Subcontratistas
  public txtBuscador: string;
  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<any>;


  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public infoSubcontracts!: DownoloadSubcontratistInfo;

  constructor(
    private _dialog: MatDialog,
    private _router: Router,
    private _activatedRoute: ActivatedRoute,
    private _resourcesService: ResourcesService,
    private _subcontratistService: SubcontratistService,
    private _encService: EncService,
  ) {
    this.idSubcontratist = "";
    this.isLoading = false;
    this.isLoadingForm = false;
    this.btnSmall = false;

    this.txtBuscador = '';
    this.displayedColumns = [
      'START_DATE',
      'END_DATE',
      'COST']
    this.dataSource = new MatTableDataSource<any>();
  }

  ngOnInit(): void {
    this.idSubcontratist = this._activatedRoute.snapshot.paramMap.get('id')!;
    this.decript();
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  private async decript() {
    this.idSubcontratist = await this._encService.desencriptar(this.idSubcontratist);
    this.getData();
    console.log(this.idSubcontratist);
  }

  public async getData() {
    this.isLoading = true;
    await lastValueFrom(this._subcontratistService.getContractsBySubcontratist(this.idSubcontratist)).then(
      (responseData: ResponseDataSubcontratistInfo) => {
        responseData.response.CONTRACTS.forEach(async element => {
          element.COST = await this._encService.desencriptar(element.COST);
        });
        this.dataSource.data = responseData.response.CONTRACTS;
        this.infoSubcontracts = responseData.response;
        this.infoSubcontracts.SAVED_BY_USER = this.idSubcontratist;
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  public async openDialog(typeForm: string, element?: any) {
    if (typeForm === 'PDF') {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Ficha de Subcontratación',
          description: 'Visualizar la ficha de subcontratación en PDF?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this._subcontratistService.downoloadSubcontratistContractsInfoOnPdf(this.infoSubcontracts).subscribe(
            (val) => window.open(val.response.replace('localhost', '192.168.1.50:8000'))
          );
        }
      });
    } else {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Ficha de Subcontratación',
          description: 'Descargar la ficha de subcontratación en Excel?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this._subcontratistService.downoloadSubcontratistContractsInfoOnExcel(this.infoSubcontracts).subscribe(
            (val) => window.open(val.response.replace('localhost', '192.168.1.50:8000'))
          );
        }
      });
    }
  }

  // Método de filtrado de datos
  public applyFilter(event: any, type: string): void {
    let filterValue: string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    } else {
      this.txtBuscador = event;
      filterValue = event;
    }
    console.log(filterValue);
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  // Método para reajustar los botones según sus dimensiones
  public onResize(): void {
    this.btnSmall = window.innerWidth <= 1405;
  }

}
