import { SelectionModel } from '@angular/cdk/collections';
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { ArtitleResponse, DataTableResponse, ResponseDataById, ShoppingCart } from '../../../../../interfaces/acquisition-management/artitle.interface';
import { SliderData } from '../../../../../interfaces/slider.interface';
import { PurchasePurpose } from '../../../../../interfaces/acquisition-management/purchase-purpose.interface';
import { MatPaginator } from '@angular/material/paginator';
import { ResourcesService } from '../../../../../services/resources.service';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, 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 { PermissionsData } from '../../../acquisition-management.component';
import { UserConsultResponse } from '../../../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../../../interfaces/profile.interface';
import { HttpErrorResponse } from '@angular/common/http';
import { AlertComponent } from '../../../../resources/dialogs/alert/alert.component';
import { DetailsArtitleComponent } from '../details-artitle/details-artitle.component';
import { FunctionsService } from '../../../../../services/functions.service';

const ID_MODULE = "S002V01M05GEAD";
@Component({
    selector: 'app-artitle-information',
    templateUrl: './artitle-information.component.html',
    styleUrl: './artitle-information.component.css',
    standalone: false
})
export class ArtitleInformationComponent implements OnInit, AfterViewInit {
  public isLoading: boolean;

  public createGroupEnable: boolean;
  public cartShoppingEnabled: boolean;

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

  public idDescArtitle:string;
  public idProvider:string;

  

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

  public arrSlider: Array<SliderData>;

  private _purchasePurpose: PurchasePurpose;


  public currentImg: number; 

  @ViewChild(MatPaginator) paginator!: MatPaginator;

  constructor(
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _activatedRouter: ActivatedRoute,
    private _encService: EncService,
    private _router: Router,
    private _acquisitionServices: AcquisitionService,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
    private _functionsService: FunctionsService,
  ) {
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.isLoading = false;
    this.createGroupEnable = true;
    this.cartShoppingEnabled = true;
    this.article = {} as ArtitleResponse;
    this._purchasePurpose = {} as PurchasePurpose;
    this.quantityShoppingCart = null;
    this.idDescArtitle = "";
    this.arrSlider = [];
    this.idProvider = '';

    this.currentImg = 0;
  }

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

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

  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 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 == '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}`);
            }
          }, 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 getPurchasePurpose() {

    this.isLoading = true;

    const DATA_INFO: string | null = this._activatedRouter.snapshot.paramMap.get('info');
    const DATA_ARTICLE: string | null = this._activatedRouter.snapshot.paramMap.get('idArtitle');
    const DATA_PROVIDER: string | null = this._activatedRouter.snapshot.paramMap.get('idProvider');

    if (DATA_INFO === null || DATA_ARTICLE === null || DATA_PROVIDER === null) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener el contenido del artículo desde la URL.`);
      this.resourcesService.goBack();
      return;
    }

    const STR_DATA = await this._encService.decrypt(DATA_INFO);
    this._purchasePurpose = JSON.parse(STR_DATA);

    const STR_ARTICLE= await this._encService.decrypt(DATA_ARTICLE);
    this.idDescArtitle = STR_ARTICLE;

    const STR_PROVIDER= await this._encService.decrypt(DATA_PROVIDER);
    this.idProvider = STR_PROVIDER;

    await this.getArtitle(DATA_ARTICLE, DATA_PROVIDER);

    this.isLoading = false;
  }

  private async getArtitle(ARTICLE:string, PROVIDER:string){
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionServices.getArtitleByProvider(ARTICLE, PROVIDER, USER, LINE)).then(
      (responseData: ResponseDataById) => {
        if (!responseData.error) {
          this.article = responseData.response;
          this.dataSource.data = [];
          let arrInfo = JSON.parse(responseData.response.INFO_PRODUCTO);
          arrInfo = arrInfo.map((element: any) => { element.CANTIDAD = 0; return element; });
          this.dataSource.data = arrInfo;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getArtitle(ARTICLE, PROVIDER);
        }
      }
    );
  }

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

  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 ++;
        if (element.CANTIDAD > 0) {
          this.selection.select(element);
        }
      }else if (element.NUMERO_INFORMACION === data.NUMERO_INFORMACION && accion == 'resta') {
        element.CANTIDAD --;
        if (element.CANTIDAD === 0) {
          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;
        }
      });
    }
  }

  public addShoppingCart (element: DataTableResponse) {
    this._dialog.open(AlertComponent, {
      data: {
        icon: `add_shopping_cart`,
        title: `Confirmación`,
        description: `¿Está seguro de agregar estos productos al carrito de compra?`,
      }
    }).afterClosed().subscribe(
      async (response: any) => {
        if (response) {
          await this.getShoppingCar(element);
          this.dataSource.data = this.dataSource.data.map((dataElement) => {
            if (dataElement.NUMERO_INFORMACION === element.NUMERO_INFORMACION) {
              element.CANTIDAD = 0;
            }
            return dataElement;
          });
        }
      }
    );
  }

  public async getShoppingCar(element: DataTableResponse) {
    if (element.CANTIDAD <= 0) {
      this.resourcesService.openSnackBar(`Debe seleccionar una cantidad mayor a 0.`)
      return;
    }

    let storeShoppingCart = localStorage.getItem('shopping_cart');
    if (storeShoppingCart === null) {
      let arrShoppingCart: Array<ShoppingCart> = [];
      arrShoppingCart.push({
        NUMERO_ARTICULO: this.article.ID_ARTICULO,
        NUMERO_DESCRIPCION: this.article.ID_DESC_ARTI,
        NUMERO_PROVEEDOR: this.article.ID_PROVEEDOR,
        IMAGENES: this.article.URL_IMAGEN,
        ARTICULO: this.article.MODELO,
        CANTIDAD: element.CANTIDAD,
        CARACTERISTICAS: element.CARACTERISTICAS,
        CODIGO: element.CODIGO,
        MODELO: element.MODELO,
        MONEDA: element.MONEDA,
        MONEDA_DESCRIPCION: element.MONEDA_DESCRIPCION,
        MONTO_MINIMO: element.MONTO_MINIMO,
        NUMERO_INFORMACION: element.NUMERO_INFORMACION,
        PRECIO: element.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);

      let shoppingCartIndex = arrShoppingCart.findIndex(( shoppingCart: ShoppingCart) => shoppingCart.NUMERO_INFORMACION === element.NUMERO_INFORMACION);

      if (shoppingCartIndex === -1) {
        arrShoppingCart.push({
          NUMERO_ARTICULO: this.article.ID_ARTICULO,
          NUMERO_DESCRIPCION: this.article.ID_DESC_ARTI,
          NUMERO_PROVEEDOR: this.article.ID_PROVEEDOR,
          IMAGENES: this.article.URL_IMAGEN,
          ARTICULO: this.article.MODELO,
          CANTIDAD: element.CANTIDAD,
          CARACTERISTICAS: element.CARACTERISTICAS,
          CODIGO: element.CODIGO,
          MODELO: element.MODELO,
          MONEDA: element.MONEDA,
          MONEDA_DESCRIPCION: element.MONEDA_DESCRIPCION,
          MONTO_MINIMO: element.MONTO_MINIMO,
          NUMERO_INFORMACION: element.NUMERO_INFORMACION,
          PRECIO: element.PRECIO,
        });
      } else {
        let countItem = arrShoppingCart[shoppingCartIndex].CANTIDAD;
        countItem += element.CANTIDAD
        arrShoppingCart[shoppingCartIndex].CANTIDAD = countItem;
      }

      const strShoppingCart: string = JSON.stringify(arrShoppingCart);
      const encShoppingCart: string = await this._encService.encrypt(strShoppingCart);
      localStorage.setItem('shopping_cart', encShoppingCart);
    }
    await this.getQuantityCarArtitle()
    this.resourcesService.openSnackBar('Se registraron los artículos en el carrito de compras');
  }

  // Abrir dialogos
  public openDialog(action: string, data: DataTableResponse) {
    if (action === 'VIEW') {
      this._dialog.open(DetailsArtitleComponent, {
        width: '800px',
        maxWidth: '800px',
        disableClose: true,
        data: {
          ID_DESC_ARTI: this.article.ID_ARTICULO,
          ID_ARTICULO:this.article.ID_ARTICULO,
          CODIGO_ARTICULO: this.article.CODIGO,
          MODELO_ARTICULO: this.article.MODELO,
          ID_ARTICULO_FAMILIA: this.article.ID_FAMILIA,
          FAMILIA_ARTICULO: this.article.FAMILIA,
          ID_ARTICULO_SUBFAMILIA: this.article.ID_SUBFAMILIA,
          SUBFAMILIA_ARTICULO: this.article.SUBFAMILIA,
          DESCRIPCION_ARTICULO: this.article.DESCRIPCION,
          CARACTERISTICAS_ARTICULO: this.article.CARACTERISTICAS,
          COMPRA_ARTICULO_WEB: this.article.COMPRA_WEB,
          ID_UNIDAD: this.article.ID_UNIDAD,
          UNIDAD: this.article.UNIDAD,
          URL_ARTICULO_IMAGEN: this.article.URL_IMAGEN,
          ID_ARTICULO_PROVEEDOR: this.article.ID_PROVEEDOR,
          PROVEEDOR_ARTICULO: this.article.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,
        }
      });
    }
  }
}
