import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { ContractsInfo, InterventionsListItem, InterventionsListResponse, ResponseDataInterventionContracts } from '../../../interfaces/personal-managment/intervention.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTabGroup } from '@angular/material/tabs';
import { DOCUMENT } from '@angular/common';
import { InterventionService } from '../../../services/personal-management/intervention.service';
import { ResourcesService } from '../../../services/resources.service';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { EncService } from '../../../services/enc.service';
import { GdelService } from '../../../services/gdel.service';
import { FunctionsService } from '../../../services/functions.service';
import { HttpErrorResponse } from '@angular/common/http';
import { lastValueFrom } from 'rxjs';
import { InterventionDetailsComponent } from './intervention-details/intervention-details.component';
import { ContractDetailsComponent } from './contract-details/contract-details.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-intervention',
    templateUrl: './intervention.component.html',
    styleUrl: './intervention.component.css',
    standalone: false
})
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 = [
      'ORDER_ID',
      '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 async getInterventions() {
    this.isLoading = true;
    
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._interventionService.getConsultOfInterventions(USER, LINE)).then(
      async (responseData: InterventionsListResponse) => {
        this.hasError = responseData.error;
        if (!responseData.error) {
          let interventionsArr: InterventionsListItem[] = [];
          for(const intervention of responseData.response){
            intervention.IDORDER = await this._encService.decrypt(intervention.IDORDER);
            intervention.EQUIPMENT = await this._encService.decrypt(intervention.EQUIPMENT);
            
            if (intervention.START_DATE !== null) {
              intervention.START_DATE = this._functionsService.orderDate(intervention.START_DATE)!;
            } else {
              intervention.START_DATE = 'Pendiente';
            }
            
            if (intervention.END_DATE !== null) {
              intervention.END_DATE = this._functionsService.orderDate(intervention.END_DATE)!;
            } else {
              intervention.END_DATE = '-';
            }

            interventionsArr.push(intervention);
          }

          this.dataSourceInterventions.data = interventionsArr;
          this.dataSourceInterventions.paginator = this.paginator;
          this.dataSourceInterventions.sort = this.sort;
        } else {
          this.errorStr = responseData.msg;
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getInterventions();
        }
      }
    );

    this.isLoading = false;
  }

  public async getContracts() {

    this.isLoading = true;
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._interventionService.getConsultOfContracts(USER, LINE)).then(
      async (responseData: ResponseDataInterventionContracts) => {
        this.hasError = responseData.error;
        if (!responseData.error) {

          for(const contract of responseData.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 = this.resourcesService.moneyFormat(parseInt(valueDec));
            contract.MODIFICATION_DATE = this.resourcesService.formatDate(contract.REGISTER_DATE, contract.MODIFICATION_DATE);
          }
          this.dataSourceContracts.data = responseData.response;
        } else {
          this.errorStr = responseData.msg;
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getContracts();
        }
      }
    );

    this.isLoading = false;
  }

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

  // 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();
    }
  }

  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',
        maxWidth: '520px',
      });
    } else if (typeForm === 'DEC') {
      this._dialog.open(ContractDetailsComponent, {
        data: element,
        disableClose: true,
        width: '480px',
        maxWidth: '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);
      }
    }
  }
}
