import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { GetInvoice, ResponseDataInvoice } from '../../../../interfaces/acquisition-management/invoice.interface';
import { FormControl, FormGroup } from '@angular/forms';
import { GetProvidersActives, ResponseDataGetProvidersActives } from '../../../../interfaces/acquisition-management/provider.interface';
import { lastValueFrom, map, Observable, startWith } from 'rxjs';
import { ResourcesService } from '../../../../services/resources.service';
import { InvoiceService } from '../../../../services/acquisition-management/invoice.service';
import { GdelService } from '../../../../services/gdel.service';
import { ActivatedRoute, Router } from '@angular/router';
import { EncService } from '../../../../services/enc.service';
import { SocketService } from '../../../../services/socket.service';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { ProviderService } from '../../../../services/acquisition-management/provider.service';
import { UserConsultResponse } from '../../../../interfaces/user.interface';
import { ProfileInterface } from '../../../../interfaces/profile.interface';
import { HttpErrorResponse } from '@angular/common/http';
import { ResponseDataGetPublicDocumentUrl } from '../../../../interfaces/gdel.interface';
import { FunctionsService } from '../../../../services/functions.service';

const ID_MODULE = "S002V01M05GEAD";
@Component({
    selector: 'app-control-invoice',
    templateUrl: './control-invoice.component.html',
    styleUrl: './control-invoice.component.css',
    standalone: false
})
export class ControlInvoiceComponent implements AfterViewInit, OnInit {
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<GetInvoice>;
  private arrInvoicesFilter: Array<GetInvoice>;

  public formGroup: FormGroup;

  public isLoading: boolean;
  public isLoadingForm: boolean;

  private arrProvider: Array<GetProvidersActives>;
  public providerStr: Array<string>;

  public filteredOptionsProvider?: Observable<Array<string>>

  constructor(
    public resourcesService: ResourcesService,
    private _invoiceService: InvoiceService,
    private _gdelService: GdelService,
    private _router: Router,
    private _encService: EncService,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
    private _providerService: ProviderService,
    private _activatedRoute:ActivatedRoute,
    private _functionsService: FunctionsService,
  ) {
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.displayedColumns = [ 'FALS_IDFA','FALS_IDLI','LINE_NUPR','DLSC_TIPO','FALS_UUID','FALS_FEMO','FALS_ESTA','ACCIONES' ];
    this.dataSource = new MatTableDataSource();
    this.arrInvoicesFilter = [];
    this.isLoading = false;
    this.isLoadingForm = false;
    this.arrProvider = [];
    this.providerStr = [];
    this.formGroup = this.createFormGroup();
  }

  private createFormGroup() {
    return new FormGroup({
      'PROVIDER': new FormControl('')
    });
  }

  async ngOnInit() {
    this.isLoading = true;
    await this.refreshPermissions();
    await this.getActiveProvider();
    await this.getInvoice();
    this.isLoading = false;

    this.filteredOptionsProvider = this.formGroup.controls['PROVIDER'].valueChanges.pipe(
      startWith(''),
      map((value:string) => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.providerStr.filter(item => item.toLowerCase().includes(filterValue));
      }),
    );

    this.formGroup.controls['PROVIDER'].valueChanges.subscribe((provider:string) => {

      this.providerStr = [];
      if (provider === '') {
        this.dataSource.data = this.arrInvoicesFilter;
      } else if (provider.includes('(') && provider.includes(')')) {
        
        try {
          const providerNumber:string = provider.split('(')[1].split(')')[0];
          let tempArrInvoice: Array<GetInvoice> = [];
          this.arrInvoicesFilter.map((element: GetInvoice) => {
            if (element.LINE_NUPR === providerNumber) {
              tempArrInvoice.push(element);
            }
          });
          this.dataSource.data = tempArrInvoice;
        } catch (error) {
          this.resourcesService.openSnackBar(`Ocurrió un error al realizar la busqueda por proveedor.`);
          return;
        }
      }

    });
  }

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

  private async refreshPermissions() {
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      let idUser = localStorage.getItem('idusuario')!;
      let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesSevice.getUser(idUser, idUser, 1));
      let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

      if(currentProfile != usrInfo.response.PERFIL){
        this._router.navigate(['/sam/home']);
      }

      let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
      if(profileUpdated == currentProfile){
        let profile = localStorage.getItem('perfil')!;

        await lastValueFrom(this._usersProfilesSevice.getProfile( profile, idUser, 1 )).then(
          (responseData: ProfileInterface) => {
            if (!responseData.error) {
              let modPerm = responseData.response.PERMISOS.permissions.filter(item => item.id == 'S002V01M05GEAD')[0];
              let funPerm = modPerm.children.filter(item => item.id == 'S002V04S04FACT')[0];
              let panPerm = funPerm.children.filter(item => item.id == "S002V01F01COFA")[0];

              if (panPerm.access === 0) {
                this._router.navigate(['/sam/home']);
              }

            } else {
              this.resourcesService.openSnackBar(`${responseData.msg}`);
            }
          }, async (httpErrorResponse: HttpErrorResponse) => {
            let response = this.resourcesService.checkErrors(httpErrorResponse)
            if (response !== null && response.reload) {
              await this.refreshPermissions();
            }
          }
        );
      }
    });

    this._socketService.refreshModules().subscribe(async () => this._functionsService.consultModuleStatus(ID_MODULE));
  }

  private async getActiveProvider() {
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._providerService.getProviderActives(user, line)).then(
      (responseData: ResponseDataGetProvidersActives) => {
        if (!responseData.error) {
          this.arrProvider = responseData.response;
          this.providerStr = [];
          this.arrProvider.forEach(element => {
            this.providerStr.push(`(${element.NUMERO_PROVEEDOR}) ${element.RAZON_SOCIAL}`);
          });
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getActiveProvider();
        }
      }
    );
  }

  public async getInvoice() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._invoiceService.getInvoice(user, line)).then(
      (responseData: ResponseDataInvoice) => {
        if (!responseData.error) {
          responseData.response = responseData.response.map(( getInvoice:GetInvoice ) => {
            if ( getInvoice.DLSC_TIPO === 'Cotización' ) {
              getInvoice.DLSC_TIPO = 'Factura de Cotización';
            } else if ( getInvoice.DLSC_TIPO === 'Orden' ) {
              getInvoice.DLSC_TIPO = 'Factura de Orden de Compra';
            } else if ( getInvoice.DLSC_TIPO === 'Abono' ) {
              getInvoice.DLSC_TIPO = 'Factura de Abono';
            } else {

            }
            return getInvoice;
          });
          
          this.dataSource.data = responseData.response;
          this.arrInvoicesFilter = [... responseData.response];
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getInvoice();
        }
      }
    );
    this.isLoading = false;
  }

  public async downloadInvoice(getInvoice: GetInvoice) {
    this.isLoadingForm = true;
    const encCodeDocument:string = getInvoice.FALS_CODO;
        
    const idUser:string = this.resourcesService.getUser();
    const line:number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._gdelService.getPublicDocumentUrl(encCodeDocument, idUser, line)).then(
      (responseData: ResponseDataGetPublicDocumentUrl) => {
        if (!responseData.error) {
          window.open(responseData.response.public_uri, '_blank');
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.downloadInvoice(getInvoice);
        }
      }
    );
    this.isLoadingForm = false;
  }
}
