import { SelectionModel } from '@angular/cdk/collections';
import { HttpErrorResponse } from '@angular/common/http';
import { AfterViewInit, Component, 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 { ActivatedRoute, Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { GetArtitleDetails, GetArtitlesByProvider, ObjResponseDownload, ObjResponseUpload, ResponseDataGetArtitlesByProvider } from 'src/app/interfaces/acquisition-management/artitle.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { ArtitleService } from 'src/app/services/acquisition-management/artitle.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-artitles-by-provider',
  templateUrl: './artitles-by-provider.component.html',
  styleUrls: ['./artitles-by-provider.component.css']
})
export class ArtitlesByProviderComponent implements OnInit, AfterViewInit{


  public providerNumber: string;
  public isLoading: boolean;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public dataSource: MatTableDataSource<GetArtitlesByProvider>;
  public displayedColumns:Array<string>;
  public arrDataSelected = new SelectionModel<GetArtitlesByProvider>(true, []);

  public isLoadingForm: boolean;

  constructor(
    private _artitleService: ArtitleService,
    public resourcesService: ResourcesService,
    private _encService: EncService,
    private _activatedRouter: ActivatedRoute,
    private _route: Router,
    private _dialog: MatDialog,
  ) {

    this.dataSource = new MatTableDataSource<GetArtitlesByProvider>();
    this.providerNumber = "";
    this.isLoading = true;
    this.isLoadingForm = false;
    this.displayedColumns = ['SELECT','ARTI_IDAR','FAMI_NOMB','SUBF_NOMB','ARTI_NOMB','ARTI_CODI','DETAILS','DEAR_USMO','DEAR_FEMO','ACTIONS']
  }
  
  ngOnInit(): void {
    this.validateProvider();
  }

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

  isAllSelected() {
    const numSelected = this.arrDataSelected.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  toggleAllRows() {
    if (this.isAllSelected()) {
      this.arrDataSelected.clear();
      return;
    }

    this.arrDataSelected.select(...this.dataSource.data);
  }

  checkboxLabel(row?: GetArtitlesByProvider): string {
    if (!row) {
      return `${this.isAllSelected() ? 'deselect' : 'select'} all`;
    }
    return `${this.arrDataSelected.isSelected(row) ? 'deselect' : 'select'} row ${row.ARTI_IDAR + 1}`;
  }

  public async validateProvider() : Promise<void> {
    let provider = this._activatedRouter.snapshot.paramMap.get('provider');
    if (provider === null) {
      this.resourcesService.goBack();
      this.resourcesService.openSnackBar('No se pudo obtener el Número del Proveedor');
    } else {
      this.providerNumber = await this._encService.decrypt(provider.toString());
      
      this.getArtitlesByProvider(this.providerNumber);
    }
  }

  private async getArtitlesByProvider(providerNumber: string) : Promise<void> {
    this.isLoading = true;
    providerNumber = await this._encService.encrypt(providerNumber);
    await lastValueFrom(this._artitleService.getArtitlesByProvider(providerNumber)).then(
      (responseData: ResponseDataGetArtitlesByProvider) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  public countDetails(arrDetails:Array<GetArtitleDetails>){
    let count:number = arrDetails.length;
    let response: string = '';
    if (count === 0) {
      response = 'Sin detalles';
    } else if (count === 1) {
      response = '1 Detalle';
    } else {
      response = count + ' Detalles';
    }
    return response;
  }

  public async alert(typeAlert: string, elementData?:any) {

    if (typeAlert === 'DOWNLOAD') {
      this._dialog.open(AlertComponent, {
        data: {
          icon: "warning",
          title: "Descargar Contenido",
          description: `¿Está seguro de descargar el contenido en formato XLSX?`
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.downloadDataArtitles();
        }
      });
    } else if (typeAlert === 'UPLOAD') {
      this._dialog.open(AlertComponent, {
        data: {
          icon: "warning",
          title: "Subir Contenido",
          description: `¿Está seguro de subir el contenido para actualizar los datos?`
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.uploadDataArtitles(elementData);
          // document.getElementById('upfile')!!.click();
        }
      });
    }
    
  }

  public async downloadDataArtitles() {
    this.isLoadingForm = true;
    this.resourcesService.openSnackBar("Generando Documento, espere por favor.");
    
    
    let arrDownload: Array<number> = [];
    this.arrDataSelected.selected.map((element: GetArtitlesByProvider) => {
      arrDownload.push(element.DEAR_IDDE);
    });
    
    let objResponse: ObjResponseDownload = {
      PROVIDER: this.providerNumber,
      USER: this.resourcesService.getUser(),
      LINE_NUMBER: "1",
      DOWNLOAD: arrDownload
    }
    
    /* await lastValueFrom(this._artitleService.downloadArtitlesByProvider(objResponse)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          let download: string = `${apiUriJeanDownload}/GEAD/${responseData.response}`;
          window.open(download, '_blank');
          this.resourcesService.openSnackBar("¡El documento se generó exitosamente!");
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );   */ 

    this.isLoadingForm = false;
  }

  public async uploadDataArtitles(event: any) {
    
    // this.resourcesService.openSnackBar("Subiendo el archivo...");
    this.isLoadingForm = true;
    //Verifica cuantos archivos se seleccionaron
    let files: File = event.target.files[0];
    
    let base64document:string = '';
    if (files !== undefined) {
      await this.resourcesService.convertisBase64(files).then((document: any) => {
        base64document = document.base;
      });
    } else {
      this.resourcesService.openSnackBar('No se pudo obtener el documento.');
      this.isLoadingForm = false;
      return ;
    }

    if (base64document === '') {      
      this.resourcesService.openSnackBar('No se pudo obtener el contenido del documento.');
      this.isLoadingForm = false;
      return ;
    }

    let objResponse: ObjResponseUpload = {
      PROVIDER: this.providerNumber,
      DOCUMENT: base64document,
      USER: this.resourcesService.getUser(),
      LINE_NUMBER: '1',
    }

    await lastValueFrom(this._artitleService.uploadArtitleByProvider(objResponse)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar("¡La actualización de los artículos fue exitosa!");
          this.validateProvider();
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoadingForm = false;
    const elementInputFile: HTMLInputElement = <HTMLInputElement>document.getElementById('upfile')!;
    elementInputFile.value = '';
  }

  public async openDialog(typeDialog:string, dataElement?:GetArtitlesByProvider) {
    if (typeDialog == "ART") {
      // Se transforma en string los datos del artículo
      const strIdArtitle:number = dataElement?.DEAR_IDDE!;
      // Se encripta la información
      const encIdArtitle = await this._encService.encrypt(`${strIdArtitle}`);

      // Se transforma en string los datos del proveedor
      const strIdProvider:string = this.providerNumber;
      // Se encripta la información
      const encIdProveedor = await this._encService.encrypt(`${strIdProvider}`);

      const strPurchasePurpose:string = JSON.stringify({ PROPOSITO: 'NA' });
      const encPurchasePurpose:string = await this._encService.encrypt(strPurchasePurpose);


      // Redirigir a la ruta con el ID Encriptado
      this._route.navigate([ `sam/GEAD/ADQU/CGPE/information/${encIdArtitle}/${encIdProveedor}/${encPurchasePurpose}` ]);
    }
  }

}


