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';
import { ContractsBySubcontratists, ContractsBySubcontratistsResponse, SubcontratistItem, SubcontratistsResponse } from 'src/app/interfaces/personal-managment/subcontratists.interface';
import { FunctionsService } from 'src/app/services/functions.service';
import { SubcontratistDetailsDialogComponent } from './subcontratist-details-dialog/subcontratist-details-dialog.component';

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

  public isLoading: boolean;
  public isLoadingForm: boolean;
  public changeOnTab : boolean = false;
  public hasError: boolean;
  public errorStr: string;

  public btnSmall: boolean;
  public cardSmall: boolean;

  // Para Subcontratistas
  public txtBuscadorSubcontratists: string;
  public displayedColumnsSubcontratists: Array<string>;
  public dataSourceSubcontratists: MatTableDataSource<SubcontratistItem>;

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

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

  constructor(
    private _subcontratistService: SubcontratistService,
    private _resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _router: Router,
    private _encService: EncService,
    private _functionsService: FunctionsService,
  ) {
    this.screenMode = 'subcontratists';
    this.isLoading = true;
    this.isLoadingForm = false;
    this.btnSmall = false;
    this.cardSmall = false;
    this.hasError = false;
    this.errorStr = "";

    this.txtBuscadorSubcontratists = '';
    this.displayedColumnsSubcontratists = [
      'NAME',
      'TIPO',
      'INTERVENTIONS_COUNT',
      '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 {
    let currentRoute = this._router.url;
    let routeArr = currentRoute.split('/').reverse();
    
    if(routeArr[0] == 'GESU'){
      this.screenMode = 'subcontratists';
      this.getSubcontratists();
    }else{
      this.screenMode = 'contracts';
      this.getContractsBySubcontratists();
    }
    
    this.onResize();
  }

  public tabChange(tab : any){
    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.encrypt("0");
      this._router.navigate(['sam/GPRS/GESU/GESU/subcontratist/form/' + id + '/1']);
    } else if (typeForm === 'UPD') {
      const id = await this._encService.encrypt(`${element.ID_SUBCONTRATIST}`);
      this._router.navigate(['sam/GPRS/GESU/GESU/subcontratist/form/' + id + '/1']);
    } else if (typeForm === 'HIS') {
      this._dialog.open(ContractHistoryComponent, {
        data: element,
        width: '640px'
      });
      
      /*const id = await this._encService.encrypt(element.ID_SUBCONTRATIST);
      this._router.navigate(['sam/GPRS/GESU/GESU/subcontratist/contracts/' + id]);*/
    } else if (typeForm === 'DET') {
      const id = await this._encService.encrypt(`${element.ID_SUBCONTRATIST}`);
      this._dialog.open(SubcontratistDetailsDialogComponent, {
        width: '520px',
        data: {
          idSub: id,
        }
      });
    }else if (typeForm === 'PRO') {
      this._resourcesService.openSnackBar('Función para la vista de Proveedores');
      // const id = await this._encService.encrypt(element.ID_SUBCONTRATIST);
      // this._router.navigate(['sam/GPRS/GESU/GESU/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);
        }
      });
    } else if (typeForm === 'ACT') {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Activación de Subcontratista',
          description: '¿Está seguro que desea activar al subcontratista?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.activateSubcontratist(element!.ID_SUBCONTRATIST);
        }
      });
    }
  }
  
  public async getSubcontratists() {
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = '';
      
      let idUser = localStorage.getItem('idusuario')!;
      let subcontratists: SubcontratistsResponse = await lastValueFrom(this._subcontratistService.getConsultOfSubcontratists(idUser));

      this.hasError = subcontratists.error;
      this.errorStr = subcontratists.msg;

      if(!this.hasError){
        let subcontratistsArr: SubcontratistItem[] = [];
        subcontratists.response.forEach(item => {
          let regFormatted = this._functionsService.orderDate(item.REGISTER_DATE);
          let modFormatted = null;

          if(item.UPDATE_DATE != null){
            modFormatted = this._functionsService.orderDate(item.UPDATE_DATE);
          }
          
          item.REGISTER_DATE = regFormatted;
          item.UPDATE_DATE = modFormatted;

          subcontratistsArr.push(item);
        }),

        this.dataSourceSubcontratists = new MatTableDataSource(subcontratistsArr);
        this.dataSourceSubcontratists.sort = this.sort2;
        this.dataSourceSubcontratists.paginator = this.paginator2;
      }
      
      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  private async deleteSubcontratist(subcontratistId: string) {
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idSubEnc = await this._encService.encrypt(`${subcontratistId}`);
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_subcontratist', idSubEnc);

      await lastValueFrom(this._subcontratistService.updateToInactiveStatus(formData));
      this._resourcesService.openSnackBar('Eliminación exitosa.');
      this.getSubcontratists();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

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

  public async getContractsBySubcontratists() {
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let contracts: ContractsBySubcontratistsResponse = await lastValueFrom(this._subcontratistService.getContractsOfEverySubcontratist(idUser));
      
      this.hasError = contracts.error;
      this.errorStr = contracts.msg;

      if(!this.hasError){
        this.dataSourceContracts = new MatTableDataSource(contracts.response);
        this.dataSourceContracts.paginator = this.paginator;
        this.dataSourceContracts.sort = this.sort;
      }

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      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;
    }
    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;
    }
    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 <= 1885;
    this.cardSmall = window.innerWidth >= 722;
  }
}
