import { AfterViewInit, Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ConditionProviderComponent } from './condition-provider/condition-provider.component';
import { ContactProviderComponent } from './contact-provider/contact-provider.component';
import { PaymentMethodsProviderComponent } from './payment-methods-provider/payment-methods-provider.component';
import { ReferencesProviderComponent } from './references-provider/references-provider.component';
import { CatalogsProviderComponent } from './catalogs-provider/catalogs-provider.component';
import { MatTableDataSource } from '@angular/material/table';
import { lastValueFrom } from 'rxjs';
import { ProviderService } from 'src/app/services/acquisition-management/provider/provider.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { HttpErrorResponse } from '@angular/common/http';
import { DeleteProvider, InformationsData, ProviderData, ResponseDataProvider, TypeForm } from 'src/app/interfaces/acquisition-management/provider/provider.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { Router } from '@angular/router';
import { ReferencesFormComponent } from './references-provider/references-form/references-form.component';
import { ContactProviderFormComponent } from './contact-provider/contact-provider-form/contact-provider-form.component';
import { ConditionProviderFormComponent } from './condition-provider/condition-provider-form/condition-provider-form.component';
import { InformationProviderComponent } from './information-provider/information-provider.component';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResponseData } from 'src/app/interfaces/response-data';
import { AlertData } from 'src/app/interfaces/alert.interface';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';

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

  public isLoading: boolean = false;
  public isLoadingForm: boolean = false;
  public btnSmall: boolean = false;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public displayedColumns: Array<string>;
  public dataSource:MatTableDataSource<ProviderData>
  public txtBuscador:string;

  constructor(
    public dialog: MatDialog,
    public resourcesServices: ResourcesService,
    private _providerService: ProviderService,
    private _resourcesService: ResourcesService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _router: Router,
  ) {
    this.displayedColumns = [/* 'NUMERO_PROVEEDOR',  */'RAZON_SOCIAL', 'USUARIO_PROVEEDOR', 'GIRO_EMPRESA', 'CORREO', /* 'TELEFONO1', */ 'ESTADO', 'ACTION'];
    this.txtBuscador = '';
    this.dataSource = new MatTableDataSource<ProviderData>();
  }

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

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

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

  public async openDialog(action: string, elementData: any = null) {
    if (action === 'REGI' || action === 'EDIT') {
      let form:TypeForm = { type: action, element: elementData }
      let strForm: string = JSON.stringify(form);
      let encForm: string = await this._encService.encriptar(strForm);
      this._router.navigate([`/sam/provider-form/${encForm}`]);
    } else if(action === 'INFO') {
      console.log(elementData);

      this.dialog.open(InformationProviderComponent, {
        width: '1200px',
        disableClose: true,
        data: elementData,
      });
    } else if(action === 'REFE') {
      this.dialog.open(ReferencesProviderComponent, {
        width: '1200px',
        disableClose: true,
        data: elementData,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.dialog.open(ReferencesFormComponent, {
            width: '500px',
            disableClose: true,
            data: result,
          }).afterClosed().subscribe((result) => {
            this.openDialog(action, elementData);
          });
        }
      });
    } else if (action === 'CONT') {
      this.dialog.open(ContactProviderComponent, {
        width: '1200px',
        disableClose: true,
        data: elementData,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.dialog.open(ContactProviderFormComponent, {
            width: '600px',
            disableClose: true,
            data: result,
          }).afterClosed().subscribe((result) => {
            this.openDialog(action, elementData);
          });
        }
      });
    } else if (action === 'COND') {
      this.dialog.open(ConditionProviderComponent, {
        width: '500px',
        disableClose: true,
        data: elementData,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.dialog.open(ConditionProviderFormComponent, {
            width: '600px',
            disableClose: true,
            data: result,
          }).afterClosed().subscribe((result) => {
            this.openDialog(action, elementData);
          });
        }
      });

    } else if (action === 'MEPA') {
      this.dialog.open(PaymentMethodsProviderComponent, {
        width: '500px',
        disableClose: true,
        data: elementData,
      });
    } else if (action === 'CATA') {
      this.dialog.open(CatalogsProviderComponent, {
        width: '700px',
        disableClose: true,
        data: elementData,
      });
    }
  }

  public async deteleProvider(numeroProveedor:string){
    let objRequest:DeleteProvider = {
      line: '1',
      user: this._resourcesService.getUser(),
      numero_proveedor: await this._encService.encriptar(numeroProveedor)
    }
    await lastValueFrom(this._providerService.deteleProvider(objRequest)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this._resourcesService.openSnackBar('¡El proveedor fue eliminado exitosamente!');
          this.getAllProvider();
        }
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }

  public setName(objProvider: InformationsData) {
    let name:string = `${objProvider.NOMBRE} ${objProvider.PRIMER_APELLIDO} ${objProvider.SEGUNDO_APELLIDO}`;
    return this._resourcesService.resizeText(name, 27);
  }

  public async alert(type: string, dataElement: any = null):Promise<void> {
    let dataDialog: AlertData = {} as AlertData;
    if (type === 'ELIM') {
      dataDialog = {
        icon: "warning",
        title: "Eliminar Proveedor",
        description: "¿Está seguro de eliminar el proveedor?",
      };
    }

    this._dialog.open(AlertComponent, {
      data: dataDialog,
      disableClose: true,
    }).afterClosed().subscribe((result) => {
      if (type === 'ELIM' && result) {
        this.deteleProvider(dataElement.NUMERO_PROVEEDOR);
      }
    });
  }
  public redirectLink(link: string) {
    window.open(link, '_blank');
  }

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


