import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetDocumentAssociation, ResponseDataGetDocumentAssociation } from '../../../interfaces/inventory-management/document-association.interface';
import { ResourcesService } from '../../../services/resources.service';
import { InventoryManagementService } from '../../../services/inventory-management/inventory-management.service';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { ProviderService } from '../../../services/acquisition-management/provider.service';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { GenerateSheetComponent } from '../../resources/dialogs/generate-sheet/generate-sheet.component';
import { ResponseData } from '../../../interfaces/response-data';

@Component({
    selector: 'app-document-association',
    templateUrl: './document-association.component.html',
    styleUrl: './document-association.component.css',
    standalone: false
})
export class DocumentAssociationComponent implements OnInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;
  public txtSearch: string;
  public dataSource: MatTableDataSource<GetDocumentAssociation>;
  public arrDocumentAssociation: GetDocumentAssociation[];

  constructor (
    public resourcesService: ResourcesService,
    private _inventoryManagementService: InventoryManagementService,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _providerService: ProviderService,
    private _router: Router,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;

    this.txtSearch = '';
    this.dataSource = new MatTableDataSource<GetDocumentAssociation>();
    this.arrDocumentAssociation = [];
  }

  async ngOnInit() {
    await this.getDocumentAssociation();
  }

  public async getDocumentAssociation() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getDocumentAssociation(user, line)).then(
      (responseData: ResponseDataGetDocumentAssociation) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
          this.arrDocumentAssociation = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getDocumentAssociation();
        }
      }
    );
    this.isLoading = false;
  }

  public applyFilter() {
    
    const dataValue: string = this.txtSearch.toString().trim().toUpperCase();
    if (dataValue.length > 0) {
      let arrDataValue: GetDocumentAssociation[] = [];
      this.arrDocumentAssociation.forEach((documentAssociation: GetDocumentAssociation) => {      

        let exists: boolean = false;
        
        const arrValues = Object.values(documentAssociation);
        arrValues.forEach((value: string) => {
          value = value.toString().trim().toUpperCase();
          if (value.includes(dataValue)) {
            exists = true;
          }
        });

        if (exists) {
          arrDataValue.push(documentAssociation);
        }
      });

      this.dataSource.data = arrDataValue;
    } else {
      this.dataSource.data = this.arrDocumentAssociation;
    }
  }

  public getSheetProvider(documentAssociation: GetDocumentAssociation) {
    this._dialog.open(GenerateSheetComponent, {
      data:  {
        title: `Generar ficha proveedor`,
        description: `¿Está seguro de generar la ficha del proveedor ${documentAssociation.NUMERO_PROVEEDOR}?`,
        icon: 'warning',
      },
      disableClose: true,
      width: '400px'
    }).afterClosed().subscribe((result) => {
      if (result === 'XLS') {
        this.generateSheetXLS( documentAssociation.NUMERO_PROVEEDOR );
      } else if (result === 'PDF') {
        this.generateSheetPDF( documentAssociation.NUMERO_PROVEEDOR );
      }
    });
  }

  private async generateSheetXLS(providerNumber: string) {
    this.isLoadingForm = true;
    const encProvider:string = await this._encService.encrypt(providerNumber);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._providerService.generateSheetProviderXLS(encProvider, 'P', 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(providerNumber);
        }
      }
    );
    this.isLoadingForm = false;
  }

  private async generateSheetPDF(providerNumber: string) {
    this.isLoadingForm = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    const encProvider:string = await this._encService.encrypt(providerNumber);
    await lastValueFrom(this._providerService.generateSheetProviderPDF(encProvider, 'P', 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(providerNumber);
        }
      }
    );
    this.isLoadingForm = false;
  }

  public async getDocumentsByStock(documentAssociation: GetDocumentAssociation) {
    const encStock = await this._encService.encrypt(documentAssociation.ID_STOCK);
    this._router.navigate([`/sam/GIST/ASDO/detalles/${encStock}`]);
  }
}
