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 { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute, Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { ArtitleService } from 'src/app/services/acquisition-management/artitle.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { DetailsArtitleComponent } from '../details-artitle/details-artitle.component';
import { DataTableResponse, ContentArtitle, ProductoDetails, ResponseDataById, ArtitleResponse, ShoppingCart } from 'src/app/interfaces/acquisition-management/artitle.interface';
import { MatPaginator } from '@angular/material/paginator';
import { SliderData } from 'src/app/interfaces/slider.interface';
import { PurchasePurpose } from 'src/app/interfaces/acquisition-management/purchase-purpose.interface';
import { SocketService } from 'src/app/services/socket.service';
import { UsersProfilesService } from 'src/app/services/users-profiles.service';
import { UserConsultResponse } from 'src/app/interfaces/user.interface';
import { ProfileInterface } from 'src/app/interfaces/profile.interface';
import { PermissionsData } from '../../../acquisition-management.component';

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

  public isLoading: boolean;
  public isError: boolean;

  public createGroupEnable: boolean;
  public cartShoppingEnabled: boolean;

  public displayedColumns: string[] = ['SELECT','MODELO','CODIGO','CARACTERISTICAS','PRECIO','CANTIDAD','ACCIONES'];
  public dataSource = new MatTableDataSource<DataTableResponse>([]);
  public selection = new SelectionModel<DataTableResponse>(true, []);

  public idDescArtitle:string;
  public idProvider:string;

  

  public artitle: ArtitleResponse;
  public quantityShoppingCart: number | null;

  public arrSlider: Array<SliderData>;

  private _purchasePurpose: PurchasePurpose;

  @ViewChild(MatPaginator) paginator!: MatPaginator;

  constructor(
    public resourcesService: ResourcesService,
    private dialog: MatDialog,
    private _activatedRouter: ActivatedRoute,
    private _encService: EncService,
    private _router: Router,
    private _artitleServices: ArtitleService,
    private _resourceService: ResourcesService,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
  ) {
    this.isLoading = false;
    this.isError = false;
    this.createGroupEnable = true;
    this.cartShoppingEnabled = true;
    this.artitle = {} as ArtitleResponse;
    this._purchasePurpose = {} as PurchasePurpose;
    this.quantityShoppingCart = null;
    this.idDescArtitle = "";
    this.arrSlider = [];
    this.idProvider = '';
  }

  async ngOnInit() {
    this.isLoading = true;
    await this.setPermissions();
    await this.refreshPermissions();
    await this.getPurchasePurpose();
    await this.getIdProviderAndIdArtitle();
    await this.getQuantityCarArtitle();
    this.isLoading = false;
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
  }

  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 == 'S002V01S01ADQU')[0];
              let panPerm1 = funPerm.children.filter(item => item.id == "S002V01F01NSCO")[0];
              this.cartShoppingEnabled = panPerm1.children.filter(item => item.id == 'S002V01P04BOLS')[0].access > 0;
              
              let panPerm2 = funPerm.children.filter(item => item.id == "S002V01F02CGPE")[0];
              this.createGroupEnable = panPerm2.children.filter(item => item.id == 'S002V01P01AOCO')[0].access > 0;

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

            } else {
              this.resourcesService.openSnackBar(`${responseData.msg}`);
            }
          }, ( httpErrorResponse: HttpErrorResponse ) => this.resourcesService.checkErrors(httpErrorResponse)
        );
      }
    });
  }

  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 panPerm1 = funPerm.children.filter(item => item.id == "S002V01F01NSCO")[0];
    this.cartShoppingEnabled = panPerm1.children.filter(item => item.id == 'S002V01P04BOLS')[0].access > 0;
    
    let panPerm2 = funPerm.children.filter(item => item.id == "S002V01F02CGPE")[0];
    this.createGroupEnable = panPerm2.children.filter(item => item.id == 'S002V01P01AOCO')[0].access > 0;

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

  private async getPurchasePurpose() {
    const encInformation:string = this._activatedRouter.snapshot.paramMap.get('info')!;
    
    const strInformation:string = await this._encService.decrypt(encInformation);
    
    this._purchasePurpose = JSON.parse(strInformation);
  }

  // Método para obtener los ID del Artículo y del Proveedor para realizar la búsqueda
  private async getIdProviderAndIdArtitle(){
    const strPurchasePurpose:string = JSON.stringify(this._purchasePurpose);
    const encPurchasePurpose:string = await this._encService.encrypt(strPurchasePurpose);

    try{
      // Se obtiene el identificador del id del artículo encriptado
      const encIdArtitle:string = this._activatedRouter.snapshot.paramMap.get('idArtitle')!;
      this.idDescArtitle = await this._encService.decrypt(encIdArtitle);

      // Se obtiene el identificador del id del proveedor encriptado
      const encIdProvider:string = this._activatedRouter.snapshot.paramMap.get('idProvider')!;
      this.idProvider = await this._encService.decrypt(encIdProvider);
      
      const encInformation:string = this._activatedRouter.snapshot.paramMap.get('info')!;
      const strInformation:string = await this._encService.decrypt(encInformation);
      this._purchasePurpose = JSON.parse(strInformation);     


      // Se verifica que los ID sean válidos
      if ( (encIdArtitle !== '' && encIdArtitle !== null) && (encIdProvider !== '' && encIdProvider !== null)) {
        // Se obtiene el artículo seleccionado mediante los ID del artículo y el proveedor
        await this.getArtitle(encIdArtitle, encIdProvider);
      }else{
        this.resourcesService.openSnackBar('Ocurrió un error al obtener el identificador del artículo y/o proveedor, intentelo nuevamente.');
        this._router.navigate([`/sam/home`]);
      }
    }catch(error: any){
      this.resourcesService.openSnackBar('Ocurrió al desencriptar el identificador del artículo y/o proveedor.');
      this._router.navigate([`/sam/home`]);
    }
  }

  private async getArtitle(encIdArtitle:string, encIdProvider:string){
    await lastValueFrom(this._artitleServices.getArtitleByProvider(encIdArtitle, encIdProvider)).then(
      (responseData: ResponseDataById) => {
        if (!responseData.error) {
          this.artitle = responseData.response;
          this.artitle.URL_IMAGEN.forEach(element => {
            this.arrSlider.push({
              image: element,
            })
          });
          this.dataSource.data = this.setQuatityTable( JSON.parse(this.artitle.INFO_PRODUCTO) );
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`)
        }
      }, (error: HttpErrorResponse) => {
        this._resourceService.checkErrors(error);
        this.isError = true;
      }
    );
  }

  // Colocación de la variable de CANTIDAD
  private setQuatityTable(arrTables: Array<DataTableResponse>): Array<DataTableResponse>{
    let arrNewData: Array<DataTableResponse> = [];
    arrTables.map( (element:DataTableResponse) => {
      element.CANTIDAD = 0;
      arrNewData.push(element);
    })
    return arrNewData;
  }

  // Método para obtener la cantidad de productos en el carrito
  public async getQuantityCarArtitle() {
    let storeShoppingCart = localStorage.getItem('shopping_cart');
    if (storeShoppingCart !== null) {
      const decShoppingCart: string = await this._encService.decrypt(storeShoppingCart);
      const arrShoppingCart: Array<DataTableResponse> = JSON.parse(decShoppingCart);
      let quantity = 0;
      arrShoppingCart.map((dataTableResponse: DataTableResponse) => {
        quantity += dataTableResponse.CANTIDAD;
      });
      this.quantityShoppingCart = quantity;
    }
  }

  // Agregar artículos al carrito de compra
  public async getShoppingCar() {
    if (this.selection.selected.length === 0) {
      this.resourcesService.openSnackBar(`Debe seleccionar al menos un artículo para continuar.`)
      return;
    }

    let isInvalid = this.selection.selected.some((dataTableResponse: DataTableResponse) => dataTableResponse.CANTIDAD === 0);
    if (isInvalid) {
      this.resourcesService.openSnackBar(`Debe seleccionar una cantidad mayor a 0.`)
      return;
    }

    let storeShoppingCart = localStorage.getItem('shopping_cart');
    if (storeShoppingCart === null) {
      let arrShoppingCart: Array<ShoppingCart> = [];
      this.selection.selected.map((dataTableResponse: DataTableResponse) => {        
        arrShoppingCart.push({
          NUMERO_ARTICULO: this.artitle.ID_ARTICULO,
          NUMERO_DESCRIPCION: this.artitle.ID_DESC_ARTI,
          NUMERO_PROVEEDOR: this.artitle.ID_PROVEEDOR,
          IMAGENES: this.artitle.URL_IMAGEN,
          ARTICULO: this.artitle.MODELO,
          CANTIDAD: dataTableResponse.CANTIDAD,
          CARACTERISTICAS: dataTableResponse.CARACTERISTICAS,
          CODIGO: dataTableResponse.CODIGO,
          MODELO: dataTableResponse.MODELO,
          MONEDA: dataTableResponse.MONEDA,
          MONEDA_DESCRIPCION: dataTableResponse.MONEDA_DESCRIPCION,
          MONTO_MINIMO: dataTableResponse.MONTO_MINIMO,
          NUMERO_INFORMACION: dataTableResponse.NUMERO_INFORMACION,
          PRECIO: dataTableResponse.PRECIO,
        })
      });
      const strShoppingCart: string = JSON.stringify(arrShoppingCart);
      const encShoppingCart: string = await this._encService.encrypt(strShoppingCart);
      localStorage.setItem('shopping_cart', encShoppingCart);

    } else {
      const decShoppingCart: string = await this._encService.decrypt(storeShoppingCart);
      const arrShoppingCart: Array<ShoppingCart> = JSON.parse(decShoppingCart);

      this.selection.selected.map(( selected:DataTableResponse ) => {
        let shoppingCartIndex = arrShoppingCart.findIndex(( shoppingCart: ShoppingCart) => shoppingCart.NUMERO_INFORMACION === selected.NUMERO_INFORMACION);
        if (shoppingCartIndex === -1) {
          arrShoppingCart.push({
            NUMERO_ARTICULO: this.artitle.ID_ARTICULO,
            NUMERO_DESCRIPCION: this.artitle.ID_DESC_ARTI,
            NUMERO_PROVEEDOR: this.artitle.ID_PROVEEDOR,
            IMAGENES: this.artitle.URL_IMAGEN,
            ARTICULO: this.artitle.MODELO,
            CANTIDAD: selected.CANTIDAD,
            CARACTERISTICAS: selected.CARACTERISTICAS,
            CODIGO: selected.CODIGO,
            MODELO: selected.MODELO,
            MONEDA: selected.MONEDA,
            MONEDA_DESCRIPCION: selected.MONEDA_DESCRIPCION,
            MONTO_MINIMO: selected.MONTO_MINIMO,
            NUMERO_INFORMACION: selected.NUMERO_INFORMACION,
            PRECIO: selected.PRECIO,
          });
        } else {
          let countItem = arrShoppingCart[shoppingCartIndex].CANTIDAD;
          countItem += selected.CANTIDAD
          arrShoppingCart[shoppingCartIndex].CANTIDAD = countItem;
        }
      });

      const strShoppingCart: string = JSON.stringify(arrShoppingCart);
      const encShoppingCart: string = await this._encService.encrypt(strShoppingCart);
      localStorage.setItem('shopping_cart', encShoppingCart);
    }

    this.resourcesService.openSnackBar('Se registraron los artículos en el carrito de compras');
    this.redirectShopping();
  }

  public async redirectShopping() {
    const strPurchasePurpose:string = JSON.stringify(this._purchasePurpose);
    const encPurchasePurpose:string = await this._encService.encrypt(strPurchasePurpose);      
    this._router.navigate([ `/sam/GEAD/ADQU/CGPE/shopping-cart/${encPurchasePurpose}` ]);
  }

  // Modificación de la cantidad de los productos
  public quantityProducts(accion: string, data: any) {
    this.dataSource.data.map( (element:DataTableResponse) => {
      if (element.NUMERO_INFORMACION === data.NUMERO_INFORMACION && accion == 'suma') {
        element.CANTIDAD ++;
      }else if (element.NUMERO_INFORMACION === data.NUMERO_INFORMACION && accion == 'resta') {
        element.CANTIDAD --;
      } else {
        this.resourcesService.openSnackBar(`Opción no disponible.`);
      }

      let isRegister: boolean = this.selection.selected.some((dataTableResponse: DataTableResponse) => dataTableResponse.NUMERO_INFORMACION === element.NUMERO_INFORMACION);
      if (element.CANTIDAD > 0 && isRegister === false) {
        this.selection.select(element);        
      } else if (element.CANTIDAD === 0 && isRegister === true) {        
        this.selection.selected.map((dataTableResponse: DataTableResponse) => {
          if (dataTableResponse.NUMERO_INFORMACION === element.NUMERO_INFORMACION) {
            this.selection.deselect(element);
          }
        });
      }
    });
  }

  // Validación de la cantidad de los artículos
  public validateQuantity(cantidad: number, data: any){
    if (cantidad < 0 ) {
      this.dataSource.data.map((element:any) => {
        if (element.NUMERO_INFORMACION === data.NUMERO_INFORMACION) {
          element.CANTIDAD = 0;
        }
      });
    }
  }

  // Abrir dialogos
  public openDialog(action: string, data: DataTableResponse) {
    if (action === 'VIEW') {
      this.dialog.open(DetailsArtitleComponent, {
        width: '800px',
        disableClose: true,
        data: {
          ID_DESC_ARTI: this.artitle.ID_ARTICULO,
          ID_ARTICULO:this.artitle.ID_ARTICULO,
          CODIGO_ARTICULO: this.artitle.CODIGO,
          MODELO_ARTICULO: this.artitle.MODELO,
          ID_ARTICULO_FAMILIA: this.artitle.ID_FAMILIA,
          FAMILIA_ARTICULO: this.artitle.FAMILIA,
          ID_ARTICULO_SUBFAMILIA: this.artitle.ID_SUBFAMILIA,
          SUBFAMILIA_ARTICULO: this.artitle.SUBFAMILIA,
          DESCRIPCION_ARTICULO: this.artitle.DESCRIPCION,
          CARACTERISTICAS_ARTICULO: this.artitle.CARACTERISTICAS,
          COMPRA_ARTICULO_WEB: this.artitle.COMPRA_WEB,
          ID_UNIDAD: this.artitle.ID_UNIDAD,
          UNIDAD: this.artitle.UNIDAD,
          URL_ARTICULO_IMAGEN: this.artitle.URL_IMAGEN,
          ID_ARTICULO_PROVEEDOR: this.artitle.ID_PROVEEDOR,
          PROVEEDOR_ARTICULO: this.artitle.PROVEEDOR,
          CODIGO_PRODUCTO: data.CODIGO,
          MODELO_PRODUCTO: data.MODELO,
          PRECIO_PRODUCTO: data.PRECIO,
          CANTIDAD_PRODUCTO: data.CANTIDAD,
          CARACTERISTICAS_PRODUCTO: data.CARACTERISTICAS,
          // NUMERO_PRODUCTO: data.NUMERO_PRODUCTO,
        }
      });
    }
  }


  public isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  public toggleAllRows() {
    if (this.isAllSelected()) {
      this.selection.clear();
      return;
    }
    this.selection.select(...this.dataSource.data);
  }

  public checkboxLabel(row?: any): string {
    if (!row) {
      return `${this.isAllSelected() ? 'deselect' : 'select'} all`;
    }
    return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row.codigo + 1}`;
  }
}
