import { HttpErrorResponse } from '@angular/common/http';
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
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 { Observable, lastValueFrom, map, startWith } from 'rxjs';
import { GetInvoice, ResponseDataInvoice } from 'src/app/interfaces/acquisition-management/invoice.interface';
import { InformationsData, ResponseDataProvider } from 'src/app/interfaces/acquisition-management/provider.interface';
import { ResponseDataGetPublicDocumentUrl } from 'src/app/interfaces/gdel.interface';
import { ProfileInterface } from 'src/app/interfaces/profile.interface';
import { UserConsultResponse } from 'src/app/interfaces/user.interface';
import { InvoiceService } from 'src/app/services/acquisition-management/invoice.service';
import { ProviderService } from 'src/app/services/acquisition-management/provider.service';
import { GdelService } from 'src/app/services/document-management/gdel.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { SocketService } from 'src/app/services/socket.service';
import { UsersProfilesService } from 'src/app/services/users-profiles.service';

@Component({
  selector: 'payment-order-invoice',
  templateUrl: './payment-order.component.html',
  styleUrls: ['./payment-order.component.css']
})
export class PaymentOrderComponent 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<InformationsData>;
  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
  ) {
    this.displayedColumns = [ 'FALS_IDFA','FALS_IDLI','LINE_NUPR','FALS_UUID','FALS_USMO','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();
  }

  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 createFormGroup() {
    return new FormGroup({
      'PROVIDER': new FormControl('')
    });
  }

  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(parseInt(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}`);
            }
          }, ( httpErrorResponse: HttpErrorResponse ) => this.resourcesService.checkErrors(httpErrorResponse)
        );
      }
    });
  }

  public async getInvoice() {
    this.isLoading = true;
    await lastValueFrom(this._invoiceService.getInvoicePayment()).then(
      (responseData: ResponseDataInvoice) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
          this.arrInvoicesFilter = [... responseData.response];
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoading = false;
  }

  public async downloadInvoice(getInvoice:GetInvoice) {
    this.isLoadingForm = true;
    const encCodeDocument:string = getInvoice.FALS_CODO;
    let codeDocument: string = await this._encService.decrypt(encCodeDocument);
    
    const idUser:string = this.resourcesService.getUser();
    const line:number = parseInt(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}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoadingForm = false;
  }

  private async getActiveProvider() {
    let idUser = localStorage.getItem('idusuario')!;
    await lastValueFrom(this._providerService.getProviderActives()).then(
      (responseData: ResponseDataProvider) => {
        if (!responseData.error) {
          this.arrProvider = responseData.response;
          this.providerStr = [];
          this.arrProvider.forEach(element => {
            this.providerStr.push(`(${element.PROV_NUPR}) ${element.PROV_NOCO}`);
          });
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
  }

}
