import { HttpErrorResponse } from '@angular/common/http';
import { AfterViewInit, 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 { resolve } from 'path';
import { lastValueFrom } from 'rxjs';
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';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { ContractHistoryComponent } from './contract-history/contract-history.component';

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

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

  public btnSmall: boolean;

  // Para Subcontratistas
  public txtBuscadorSubcontratists: string;
  public displayedColumnsSubcontratists: Array<string>;
  public dataSourceSubcontratists: 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 _subcontratistService: SubcontratistService,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _router: Router,
    private _encService: EncService
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.btnSmall = false;

    this.txtBuscadorSubcontratists = '';
    this.displayedColumnsSubcontratists = [
      'NAME',
      'INTERVENTIONS_COUNT',
      'REGISTER_DATE',
      'REGISTERED_BY_USER',
      'UPDATE_DATE',
      'UPDATED_BY_USER',
      'STATUS',
      'ACCIONES']
    this.dataSourceSubcontratists = new MatTableDataSource<any>();

    this.txtBuscadorContracts = '';
    this.displayedColumnsContracts = [
      'NAME',
      'CONTRACTS_COUNT',
      'ACCIONES']
    this.dataSourceContracts = new MatTableDataSource<any>();
  }
  
  ngAfterViewInit() {
    this.dataSourceSubcontratists.paginator = this.paginator;
    this.dataSourceSubcontratists.sort = this.sort;
    this.dataSourceContracts.paginator = this.paginator2;
    this.dataSourceContracts.sort = this.sort2;
  }

  ngOnInit(): void {
    this.getSubcontratists();
    this.getContractsBySubcontratists();
  }

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 === 'UPD') {
      const id = await this._encService.encriptar(element.ID_SUBCONTRATIST);
      this._router.navigate(['sam/GPRS/subcontratist/form/' + id + '/1']);
    } else if (typeForm === 'HIS') {
      const id = await this._encService.encriptar(element.ID_SUBCONTRATIST);
      this._router.navigate(['sam/GPRS/subcontratist/contracts/' + id]);
    } else if (typeForm === 'DET') {
      const id = await this._encService.encriptar(element.ID_SUBCONTRATIST);
      this._router.navigate(['sam/GPRS/subcontratist/form/' + id + '/0']);
    }else if (typeForm === 'PRO') {
      this.resourcesService.openSnackBar('Función para la vista de Proveedores');
      // const id = await this._encService.encriptar(element.ID_SUBCONTRATIST);
      // this._router.navigate(['sam/GPRS/subcontratist/form/' + id + '/0']);
    } else if (typeForm === 'DEL') {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Eliminación de Subcontratista',
          description: '¿Está seguro que desea eliminar al subcontratista?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.deleteSubcontratist(element!.ID_SUBCONTRATIST);
        }
      });
    }
  }
  
  public async getSubcontratists() {
    this.isLoading = true;
    await lastValueFrom(this._subcontratistService.getConsultOfSubcontratists()).then(
      (responseData: any) => {
        this.dataSourceSubcontratists.data = responseData.response;
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  private async deleteSubcontratist(subcontratistId: string) {
    await lastValueFrom(this._subcontratistService.updateToInactiveStatus({
      ID_SUBCONTRATIST: subcontratistId,
      LINE_NUMBER: '01',
      SAVED_BY_USER: this.resourcesService.getUser()
    })).then(
      (responseData: any) => {
        this.getSubcontratists();
        this.resourcesService.openSnackBar('¡Eliminación Exitosa!');
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  public async getContractsBySubcontratists() {
    this.isLoading = true;
    await lastValueFrom(this._subcontratistService.getContractsOfEverySubcontratist()).then(
      (responseData: any) => {
        this.dataSourceContracts.data = responseData.response;
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

    // Método de filtrado de datos
    public applyFilterSubcontratists(event: any, type: string): void {
      let filterValue: string;
      if (type == 'INP') {
        filterValue = (event.target as HTMLInputElement).value;
      } else {
        this.txtBuscadorSubcontratists = event;
        filterValue = event;
      }
      console.log(filterValue);
      this.dataSourceSubcontratists.filter = filterValue.trim().toLowerCase();
      if (this.dataSourceSubcontratists.paginator) {
        this.dataSourceSubcontratists.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;
  }

}
