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 { MatTabGroup } from '@angular/material/tabs';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { ResponseDataInterventionContracts } from 'src/app/interfaces/personal-managment/intervention.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { InterventionService } from 'src/app/services/personal-management/intervention.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

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

  public isLoading: boolean;
  public isLoadingForm: boolean;
  public changeOnTab : boolean = false;

  public btnSmall: boolean;

  // Para Subcontratistas
  public txtBuscadorInterventions: string;
  public displayedColumnsInterventions: Array<string>;
  public dataSourceInterventions: MatTableDataSource<any>;

  // Para Contratos
  public txtBuscadorContracts: string;
  public displayedColumnsContracts: Array<string>;
  public dataSourceContracts: MatTableDataSource<any>;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  @ViewChild('MatPaginator2') paginator2!: MatPaginator;
  @ViewChild('MatSort2') sort2!: MatSort;
  @ViewChild('TabGroup') tabGroup!: MatTabGroup;

  constructor(
    private _interventionService: InterventionService,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _router: Router,
    private _encService: EncService
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.btnSmall = false;

    this.txtBuscadorInterventions = '';
    this.displayedColumnsInterventions = [
      'EQUIPMENTS_ID',
      'START_DATE',
      'END_DATE',
      'ACCIONES']
    this.dataSourceInterventions = new MatTableDataSource<any>();

    this.txtBuscadorContracts = '';
    this.displayedColumnsContracts = [
      'CONTRACT_TYPE',
      'DURATION',
      'DENOMINATION',
      'CONTRACT_COST',
      'REGISTER_DATE',
      'REGISTERED_BY',
      'ACCIONES']
    this.dataSourceContracts = new MatTableDataSource<any>();
  }
  
  ngAfterViewInit() {
    this.dataSourceInterventions.paginator = this.paginator;
    this.dataSourceInterventions.sort = this.sort;
    this.dataSourceContracts.paginator = this.paginator2;
    this.dataSourceContracts.sort = this.sort2;
  }

  ngOnInit(): void {
    this.getInterventions();
    this.getContracts();
  }

public tabChange(tab : any){
  console.log("hola " + tab.index);
  if(tab.index == 0){
    this.changeOnTab = false;
  }else{
    this.changeOnTab = true;
  }
}

  public async openDialog(typeForm: string, element?: any) {
    if (typeForm === 'REG') {
      const id = await this._encService.encriptar("0");
      this._router.navigate(['sam/GPRS/subcontratist/form/' + id + '/1']);
    } else if (typeForm === 'DEI') {
      this.resourcesService.openSnackBar('Función para la vista de Proveedores');
      // const id = await this._encService.encriptar(element.INTERVENTION_ID);
      // this._router.navigate(['sam/GPRS/subcontratist/form/' + id + '/1']);
    } else if (typeForm === 'DEC') {
      const id = await this._encService.encriptar(element.CONTRACT_ID);
      this._router.navigate(['sam/GPRS/subcontratist/contracts/' + id]);
    } else if (typeForm === 'DOW') {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Descargar de Documento',
          description: '¿Está seguro que desea descargar el documento?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          window.open(element.DOCUMENT.replace('localhost', '192.168.1.50:8000'))
        }
      });
    }
  }
  
  public async getInterventions() {
    this.isLoading = true;
    await lastValueFrom(this._interventionService.getConsultOfInterventions()).then(
      (responseData: any) => {
        this.dataSourceInterventions.data = responseData.response;
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  public async getContracts() {
    this.isLoading = true;
    await lastValueFrom(this._interventionService.getConsultOfContracts()).then(
      (responseData: ResponseDataInterventionContracts) => {
        console.log(responseData.response);
        responseData.response.forEach(async element => {
          element.CONTRACT_COST = await this._encService.desencriptar(element.CONTRACT_COST);
          element.DOCUMENT = await this._encService.desencriptar(element.DOCUMENT);
        });
        this.dataSourceContracts.data = responseData.response;
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

    // Método de filtrado de datos
    public applyFilterInterventions(event: any, type: string): void {
      let filterValue: string;
      if (type == 'INP') {
        filterValue = (event.target as HTMLInputElement).value;
      } else {
        this.txtBuscadorInterventions = event;
        filterValue = event;
      }
      console.log(filterValue);
      this.dataSourceInterventions.filter = filterValue.trim().toLowerCase();
      if (this.dataSourceInterventions.paginator) {
        this.dataSourceInterventions.paginator.firstPage();
      }
    }
  
    // Método de filtrado de datos
    public applyFilterContracts(event: any, type: string): void {
      let filterValue: string;
      if (type == 'INP') {
        filterValue = (event.target as HTMLInputElement).value;
      } else {
        this.txtBuscadorContracts = event;
        filterValue = event;
      }
      console.log(filterValue);
      this.dataSourceContracts.filter = filterValue.trim().toLowerCase();
      if (this.dataSourceContracts.paginator) {
        this.dataSourceContracts.paginator.firstPage();
      }
    }
    
  // Método para reajustar los botones según sus dimensiones
  public onResize(): void {
    this.btnSmall = window.innerWidth <= 1405;
  }
}
