import { DOCUMENT } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute, Router } from '@angular/router';
import { lastValueFrom, map } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { DownoloadSubcontratistInfo } from 'src/app/interfaces/personal-managment/subcontractist.interface';
import { ContractsBySubcontratist, ContractsBySubcontratistResponse, ContractsBySubcontratists } from 'src/app/interfaces/personal-managment/subcontratists.interface';
import { GdelService } from 'src/app/services/document-management/gdel.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { FunctionsService } from 'src/app/services/functions.service';
import { SubcontratistService } from 'src/app/services/personal-management/subcontratist.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-contract-history',
  templateUrl: './contract-history.component.html',
  styleUrls: ['./contract-history.component.css']
})
export class ContractHistoryComponent implements OnInit {
  public isLoading: boolean;
  public hasError: boolean;
  public errorStr: string;
  public idSubcontratist: string;
  public isLoadingForm: boolean;
  public subcontratist: ContractsBySubcontratists;

  public btnSmall: boolean;

  // Para Subcontratistas
  public txtBuscador: string;
  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<ContractsBySubcontratist>;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public infoSubcontracts!: DownoloadSubcontratistInfo;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: ContractsBySubcontratists,
    @Inject(DOCUMENT) private _document: Document,
    private _dialog: MatDialog,
    private _router: Router,
    private _activatedRoute: ActivatedRoute,
    private _resourcesService: ResourcesService,
    private _subcontratistService: SubcontratistService,
    private _encService: EncService,
    private _functionsService: FunctionsService,
    private _gdelService: GdelService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.idSubcontratist = "";
    this.isLoadingForm = false;
    this.btnSmall = false;

    this.txtBuscador = '';
    this.displayedColumns = [
      'CONTRACT_NAME',
      'START_DATE',
      'END_DATE',
      'COST']
    this.dataSource = new MatTableDataSource<any>();
    this.subcontratist = this._data;
  }

  ngOnInit(): void {
    this.getData();
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  public async getData() {
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let subContracts: ContractsBySubcontratistResponse = await lastValueFrom(this._subcontratistService.getContractsBySubcontratist(
        this.subcontratist.ID_EMPLOYEE, 
        idUser
      ));

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

      if(!this.hasError){
        let contracts: ContractsBySubcontratist[] = [];
        for(const contract of subContracts.response){
          contract.START_DATE = this._functionsService.orderDate(contract.START_DATE)!;
          contract.END_DATE = this._functionsService.orderDate(contract.END_DATE)!;

          contracts.push(contract);
        }

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

  async downloadExcelHistory(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let document = await lastValueFrom(this._subcontratistService.downloadSubcontratistContractsInfoOnExcel(this.subcontratist.ID_EMPLOYEE, idUser));
      let documentEnc = await this._encService.encrypt(document.response.fileID);
      let downloadToken = await lastValueFrom(this._gdelService.getDownloadToken(documentEnc, 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);
      }
    }
  }

  async downloadPDFHistory(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let document = await lastValueFrom(this._subcontratistService.downloadSubcontratistContractsInfoOnPdf(this.subcontratist.ID_EMPLOYEE, idUser));
      let documentEnc = await this._encService.encrypt(document.response.fileID);
      let downloadToken = await lastValueFrom(this._gdelService.getDownloadToken(documentEnc, 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);
      }
    }
  }

  // Método de filtrado de datos
  public applyFilter(event: any, type: string): void {
    let filterValue: string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    } else {
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

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

}
