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 { ArtitleResponse, ResponseDataArtitle, TypeFormArticle } from '../../../../interfaces/acquisition-management/artitle.interface';
import { SelectionModel } from '@angular/cdk/collections';
import { ResourcesService } from '../../../../services/resources.service';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { EncService } from '../../../../services/enc.service';
import { AcquisitionService } from '../../../../services/acquisition-management/acquisition.service';
import { SocketService } from '../../../../services/socket.service';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { UserConsultResponse } from '../../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../../interfaces/profile.interface';
import { HttpErrorResponse } from '@angular/common/http';
import { PermissionsData } from '../../acquisition-management.component';
import { AssociatedProviderComponent } from './associated-provider/associated-provider.component';
import { InformationProviderComponent } from '../providers/information-provider/information-provider.component';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';
import { ResponseData } from '../../../../interfaces/response-data';
import { ArtitleLoadComponent } from './artitle-load/artitle-load.component';
import { FunctionsService } from '../../../../services/functions.service';

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

  public isLoading: boolean;
  public getArtitleEnabled: boolean;
  public providerAsociatedEnabled: boolean;

  constructor(
    public resourcesService: ResourcesService,
    public dialog: MatDialog,
    private _router: Router,
    private _encService: EncService,
    private _acquisitionServices: AcquisitionService,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
    private _functionsService: FunctionsService,
  ) {
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.displayedColumns = [
      'ID_ARTICULO',
      'MODELO',
      'FAMILIA',
      'SUBFAMILIA',
      'ESTADO',
      'FECHA_MODIFICA',
      'USUARIO_MODIFICA',
      'ACCIONES',
    ];
    this.isLoading = false;
    this.dataSource = new MatTableDataSource<ArtitleResponse>();
    this.selection = new SelectionModel<ArtitleResponse>(true, []);
    this.getArtitleEnabled = true;
    this.providerAsociatedEnabled = true;
  }

  async ngOnInit() {
    await this.refreshPermissions();
    await this.setPermissions();
    await this.getAllArtitles();
  }

  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 == 'S002V02S02PROV')[0];
              let panPerm = funPerm.children.filter(item => item.id == "S002V01F05GVPA")[0];

              this.getArtitleEnabled = panPerm.children.filter(item => item.id == 'S002V01P01COAR')[0].access > 0;
              this.providerAsociatedEnabled = panPerm.children.filter(item => item.id == 'S002V01P02PRAS')[0].access > 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 setPermissions() {
    const encPermissions = localStorage.getItem('permisos');
    if (encPermissions === null || encPermissions === undefined || encPermissions === '') {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener los permisos del usuario.`);
      this._router.navigate(['/sam/home']);
      return;
    }
    const strPermissions:string = await this._encService.decrypt(encPermissions);
    const arrPermissions:Array<PermissionsData> = JSON.parse(strPermissions).permissions;

    let modPerm = arrPermissions.filter(item => item.id == 'S002V01M05GEAD')[0];
    let funPerm = modPerm.children.filter(item => item.id == 'S002V01S01ADQU')[0];
    let panPerm = funPerm.children.filter(item => item.id == "S002V01F01NSCO")[0];

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

  public async getAllArtitles() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionServices.getAllArtitle(user, line)).then(
      (responseData: ResponseDataArtitle) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getAllArtitles();
        }
      }
    );
    this.isLoading = false;
  }

  public async openDialogForm (type: 'R' | 'M', element?: ArtitleResponse ) {
    let typeForm: TypeFormArticle = {} as TypeFormArticle;
    typeForm.type = type;
    if (type === 'M' && element !== undefined) {
      typeForm.idArticle = element.ID_ARTICULO;
    }
    const STR_FORM: string = JSON.stringify(typeForm);
    const ENC_FORM: string = await this._encService.encrypt(STR_FORM);
    this._router.navigate([`/sam/GEAD/PROV/GVPA/${ENC_FORM}`]);
  }

  public async openDialog(typeDialog: string, element: any = null) {
    if (typeDialog === 'PROV') {

      this.dialog.open(AssociatedProviderComponent, {
        width: '1000px',
        maxWidth: '1000px',
        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.encrypt(`${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.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._router.navigate([ `/sam/GEAD/ADQU/CGPE/information/${encIdArtitle}/${encIdProveedor}/${encPurchasePurpose}` ]);
    } else if (typeDialog === 'INFO_PROV'){
      
      this.dialog.open(InformationProviderComponent, {
        width: '1200px',
        maxWidth: '1200px',
        disableClose: true,
        data: element.provider.NUMERO_PROVEEDOR,
      }).afterClosed().subscribe(async (result) => {
        this.openDialog('PROV' , element.artitle);
      });
    } else if (typeDialog === 'ALER_ELIM'){
      this.dialog.open(AlertComponent, {
        disableClose: true,
        data: { 
          icon: 'warning', 
          title: 'Confirmación', 
          description: '¿Está seguro de eliminar el artículo?' 
        },
      }).afterClosed().subscribe(async (result) => {
        if (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.encrypt(strRequest);
      this._router.navigate(['/sam/GEAD/PROV/GVPA/' + encRequest]);
    } else if (typeDialog === 'CARGA'){
      this.dialog.open(ArtitleLoadComponent, {
        width: '400px',
        maxWidth: '400px',
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.getAllArtitles();
        }
      });
    }
  }

  private async deleteArtitle(numeroArticulo:string) {
    await lastValueFrom(this._acquisitionServices.deleteArtitle({
      NUMERO_ARTITULO: await this._encService.encrypt(numeroArticulo.toString()),
      NUMERO_LINEA: '1',
      USUARIO: this.resourcesService.getUser()
    })).then(
      (response:ResponseData) => {
        if (!response.error) {
          this.resourcesService.openSnackBar('¡Eliminación Exitosa!');
          this.getAllArtitles();
        } else {
          this.resourcesService.openSnackBar(response.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.deleteArtitle(numeroArticulo);
        }
      }
    );
  }
}
