import { HttpErrorResponse } from '@angular/common/http';
import { Component, Inject, 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 { ContractsInfo, InterventionsListItem, InterventionsListResponse, 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';
import { GdelService } from 'src/app/services/document-management/gdel.service';
import { DOCUMENT } from '@angular/common';
import { ContractDetailsComponent } from './contract-details/contract-details.component';
import { FunctionsService } from 'src/app/services/functions.service';
import { InterventionDetailsComponent } from './intervention-details/intervention-details.component';

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

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

  public btnSmall: boolean;

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

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

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

  constructor(
    @Inject(DOCUMENT) private _document: Document,
    private _interventionService: InterventionService,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _router: Router,
    private _encService: EncService,
    private _gdelService: GdelService,
    private _functionsService: FunctionsService,
  ) {
    this.screenMode = 'subcontratists';
    this.isLoading = true;
    this.isLoadingForm = false;
    this.btnSmall = false;
    this.hasError = false;
    this.errorStr = "";

    this.txtBuscadorInterventions = '';
    this.displayedColumnsInterventions = [
      'EQUIPMENTS_ID',
      'ORDER_TYPE',
      'STATUS',
      'START_DATE',
      'END_DATE',
      'ACCIONES'
    ];
    this.dataSourceInterventions = new MatTableDataSource();

    this.txtBuscadorContracts = '';
    this.displayedColumnsContracts = [
      'CONTRACT_NAME',
      'CONTRACT_TYPE',
      'DURATION',
      'DENOMINATION',
      'CONTRACT_COST',
      'REGISTER_DATE',
      'REGISTERED_BY',
      'STATUS',
      'ACCIONES'
    ];
    this.dataSourceContracts = new MatTableDataSource();
  }

  ngOnInit(): void {
    let currentRoute = this._router.url;
    let routeArr = currentRoute.split('/').reverse();
    
    if(routeArr[0] == 'ADIN'){
      this.screenMode = 'interventions';
      this.getInterventions();
    }else{
      this.screenMode = 'contracts';
      this.getContracts();
    }
  }

  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/GEIN/ADCN/intervention/contract-form/' + id + '/1']);
    } else if (typeForm === 'DEI') {
      this._dialog.open(InterventionDetailsComponent, {
        data: element,
        width: '520px'
      });
    } else if (typeForm === 'DEC') {
      this._dialog.open(ContractDetailsComponent, {
        data: element,
        disableClose: true,
        width: '480px'
      })
    } else if (typeForm === 'DOW') {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Descarga de Documento',
          description: '¿Está seguro que desea descargar el documento?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.downloadFile(element!.DOCUMENT);
        }
      });
    }
  }

  public async downloadFile(idFileStr: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idFileArr = JSON.parse(idFileStr);
      let downloadToken = await lastValueFrom(this._gdelService.getDownloadToken(idFileArr[0].id, idUser, 1));
      let download = this._document.getElementById('download') as HTMLAnchorElement;
      
      download.href = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${idUser}/1`;
      download.download = "";
      download.click();
    }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);
      }
    }
  }

  public async getInterventions() {
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let interventions: InterventionsListResponse = await lastValueFrom(this._interventionService.getConsultOfInterventions(idUser));

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

      if(!this.hasError){
        let interventionsArr: InterventionsListItem[] = [];
        for(const intervention of interventions.response){
          let idEnc = await this._encService.encrypt(`${intervention.IDORDER}`);

          intervention.IDORDER = idEnc;
          intervention.START_DATE = this._functionsService.orderDate(intervention.START_DATE)!;
          intervention.END_DATE = this._functionsService.orderDate(intervention.END_DATE)!;
          interventionsArr.push(intervention);
        }

        this.dataSourceInterventions = new MatTableDataSource(interventionsArr);
        this.dataSourceInterventions.paginator = this.paginator;
      }
      
      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;
    }
  }

  public async getContracts() {
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let contracts: ResponseDataInterventionContracts = await lastValueFrom(this._interventionService.getConsultOfContracts(idUser));
      
      this.hasError = contracts.error;
      this.errorStr = contracts.msg;

      if(!this.hasError){
        let contractsArr: ContractsInfo[] = [];

        for(const contract of contracts.response){
          let idDec = await this._encService.decrypt(contract.CONTRACT_ID as string);
          let valueDec = await this._encService.decrypt(contract.CONTRACT_COST as string);

          contract.CONTRACT_NAME = `${contract.CONTRACT_NAME} (${idDec})`;
          contract.CONTRACT_COST = `${valueDec}`;

          contractsArr.push(contract);
        }

        this.dataSourceContracts = new MatTableDataSource(contractsArr);
        this.dataSourceContracts.paginator = this.paginator2;
        this.dataSourceContracts.sort = this.sort2;
      }

      this.isLoading = false;
    }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);
      }
    }
  }

  // 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;
    }
    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;
    }
    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 <= 1560;
  }
}
