import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { ContractsBySubcontratists, ContractsBySubcontratistsResponse } from '../../../../interfaces/personal-managment/subcontratists.interface';
import { ResourcesService } from '../../../../services/resources.service';
import { SubcontratistService } from '../../../../services/personal-management/subcontratist.service';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { ProviderService } from '../../../../services/acquisition-management/provider.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { ContractHistoryComponent } from '../contract-history/contract-history.component';
import { GenerateSheetComponent } from '../../../resources/dialogs/generate-sheet/generate-sheet.component';
import { ResponseData } from '../../../../interfaces/response-data';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';

@Component({
    selector: 'app-contract-management',
    templateUrl: './contract-management.component.html',
    styleUrl: './contract-management.component.css',
    standalone: false
})
export class ContractManagementComponent implements OnInit, AfterViewInit {
  public dataSource: MatTableDataSource<ContractsBySubcontratists>;
  public displayedColumnsContracts: string[];
  public isLoading: boolean;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  
  constructor (
    public resourcesService: ResourcesService,
    private _subcontratistService: SubcontratistService,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _providerService: ProviderService,
  ) {
    this.dataSource = new MatTableDataSource<ContractsBySubcontratists>();
    this.displayedColumnsContracts = [
      'RAZON_SOCIAL',
      'EMPLEADO',
      'NUMERO_CONTRATOS',
      'ACCIONES'
    ];
    this.isLoading = false;
  }

  ngAfterViewInit(): void {
    throw new Error('Method not implemented.');
  }

  async ngOnInit() {
    this.isLoading = true;
    await this.getContractsBySubcontratists();
    this.isLoading = false;
  }

  public async getContractsBySubcontratists() {
    this.isLoading = true;
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._subcontratistService.getContractsOfEverySubcontratist(USER, LINE)).then(
      (responseData: ContractsBySubcontratistsResponse) => {        
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
          this.dataSource.paginator = this.paginator;
          this.dataSource.sort = this.sort;
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getContractsBySubcontratists();
        }
      }
    );
    this.isLoading = false;
  }

  public async viewHistory (contract: ContractsBySubcontratists) {
    this._dialog.open(ContractHistoryComponent, {
      data: contract,
      width: '900px',
      maxWidth: '900px',
    });
  }

  public async viewSheetProviders (contract: ContractsBySubcontratists) {
    const ID_SUBCONTRACT: string = await this._encService.decrypt(contract.ID_SUBCONTRATISTA);
    this._dialog.open(GenerateSheetComponent, {
      data:  {
        title: `Generar Ficha de Subcontratista`,
        description: `¿Está seguro de generar la ficha del subcontratista #${ID_SUBCONTRACT}?`,
        icon: 'warning',
      },
      disableClose: true,
      width: '400px',
      maxWidth: '400px',
    }).afterClosed().subscribe((result) => {
      if (result === 'XLS') {
        this.generateSheetXLS(contract.ID_SUBCONTRATISTA);
      } else if (result === 'PDF') {
        this.generateSheetPDF(contract.ID_SUBCONTRATISTA);
      }
    });
  }

  public async generateSheetXLS(ID_SUBCONTRACT: string) {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._providerService.generateSheetProviderXLS(ID_SUBCONTRACT, 'S', user, line)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open(`${ responseData.response.url }`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.generateSheetXLS(ID_SUBCONTRACT);
        }
      }
    );
    this.isLoading = false;
  }

  public async generateSheetPDF(ID_SUBCONTRACT: string) {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._providerService.generateSheetProviderPDF(ID_SUBCONTRACT, 'S', user, line)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {          
          window.open(`${ responseData.response.url }`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.generateSheetPDF(ID_SUBCONTRACT);
        }
      }
    );
    this.isLoading = false;
  }
}
