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 { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { ArtitleResponse, ResponseDataArtitle } from 'src/app/interfaces/acquisition-management/acquisition/artitle.interface';
import { ProviderInformation, ResponseDataProvider, ResponseDataProviderInformation } from 'src/app/interfaces/acquisition-management/provider/provider.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { ArtitleService } from 'src/app/services/acquisition-management/acquisition/artitle.service';
import { ProviderService } from 'src/app/services/acquisition-management/provider/provider.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { InformationProviderComponent } from '../providers/information-provider/information-provider.component';
import { AssociatedProviderComponent } from './associated-provider/associated-provider.component';

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

  // Tables
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<ArtitleResponse>
  public selection: SelectionModel<any>
  public txtBuscador: string;

  // Loadings
  public isLoading: boolean;
  public isLoadingForm: boolean;

  // Smart Page
  public btnSmall: boolean;

  constructor(
    public dialog: MatDialog,
    private _router: Router,
    private _encService: EncService,
    private _artitleServices: ArtitleService,
    private _providerService: ProviderService,
    public resourcesServices: ResourcesService,
  ) {
    this.displayedColumns = ['MODELO','FAMILIA','SUBFAMILIA','FECHA','USUARIO','ESTADO','ACCIONES'];
    this.btnSmall = false;
    this.isLoading = false;
    this.isLoadingForm = false;
    this.dataSource = new MatTableDataSource<ArtitleResponse>();
    this.selection = new SelectionModel<any>(true, []);
    this.txtBuscador = '';
  }

  ngOnInit(): void {
    this.onResize();
    this.getAllArtitles();
  }

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

  public async getAllArtitles() {
    this.isLoading = true;
    await lastValueFrom(this._artitleServices.getAllArtitle()).then(
      (data : ResponseDataArtitle) => {
        this.dataSource.data = !data.error ? data.response : [];
      },(error: HttpErrorResponse) => this.resourcesServices.checkErrors(error)
    );
    this.isLoading = false;
  }

  public async openDialog(typeDialog: string, element: any = null) {
    if (typeDialog === 'PROV') {
      this.dialog.open(AssociatedProviderComponent, {
        width: '1200px',
        disableClose: true,
        data: element,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.openDialog(result.type , result.dataElement);
        }
      });
    } else if (typeDialog === 'INFO_ARTI'){
      // Se transforma en string los datos del artículo
      const strIdArtitle:string = element.provider.NUMERO_DESCRIPTION;
      // Se encripta la información
      const encIdArtitle = await this._encService.encriptar(`${strIdArtitle}`);

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

      // Redirigir a la ruta con el ID Encriptado
      this._router.navigate([ `sam/artitle-details/${encIdArtitle}/${encIdProveedor}` ]);
    } else if (typeDialog === 'INFO_PROV'){
      this.dialog.open(InformationProviderComponent, {
        width: '1200px',
        disableClose: true,
        data: element.provider,
      }).afterClosed().subscribe(async (result) => {
        this.openDialog('PROV' , element.artitle);
      });
    } else if (typeDialog === 'ALER_ELIM'){
      this.dialog.open(AlertComponent, {
        disableClose: true,
        data: { icon: 'warning', title: 'Eliminación de Artículo', description: '¿Está seguro de eliminar el artículo?' },
      }).afterClosed().subscribe(async (result) => {
        this.deleteArtitle(element.ID_ARTICULO);
      });
    } else if (typeDialog === 'REGI' || typeDialog === 'EDIT') {
      let objResquest = { type: typeDialog, element: element };
      let strRequest = JSON.stringify(objResquest);
      let encRequest = await this._encService.encriptar(strRequest);
      this._router.navigate(['/sam/artitle-form/' + encRequest]);
    }
  }

  private async deleteArtitle(numeroArticulo:string) {
    await lastValueFrom(this._artitleServices.deleteArtitle( { NUMERO_ARTITULO: await this._encService.encriptar(numeroArticulo), NUMERO_LINEA: '1', USUARIO: this.resourcesServices.getUser() } )).then(
      (response:ResponseData) => {
        this.resourcesServices.openSnackBar('¡Eliminación Exitosa!');
      }, (error:HttpErrorResponse) => this.resourcesServices.checkErrors(error)
    );
  }

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


}
