seleccion-articulos.component.ts 7.19 KB
import { Component, OnInit, OnDestroy, HostListener, ViewChild, AfterViewInit } from '@angular/core';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { ArticuloService } from 'src/app/services/articulo/articulo.service';
import { IArticulo } from 'src/app/interfaces/IArticulo';
import { APP_SETTINGS } from 'src/etc/AppSettings';
import { ICategoria } from 'src/app/interfaces/ICategoria';
import { ISinonimo } from 'src/app/interfaces/ISinonimo';
import { PromocionComponent } from 'src/app/shared/promocion/promocion.component';
import { InactiveScreenService } from 'src/app/services/inactive-screen/inactive-screen.service';
import { SinonimoService } from 'src/app/services/sinonimo/sinonimo.service';
import { SinonimoComponent } from 'src/app/shared/sinonimo/sinonimo.component';
import { FiltroCategoriasComponent } from './filtro-categorias/filtro-categorias.component';
import * as _ from 'lodash';
import { ANIMATIONS } from 'src/app/utils/animations';
import { NoStockComponent } from './no-stock/no-stock.component';
import { DateExtension } from 'src/app/utils/dateExtension';

@Component({
  selector: 'app-seleccion-articulos',
  templateUrl: './seleccion-articulos.component.html',
  styleUrls: ['./seleccion-articulos.component.scss'],
  animations: [ANIMATIONS.EnterLeaveY]
})
export class SeleccionArticulosComponent implements OnInit, AfterViewInit, OnDestroy {
  loading = true;
  timeoutHandler: any;
  urlImagenes = `${APP_SETTINGS.apiImagenes}/imagenes/`;
  articulos: IArticulo[] = [];
  auxArticulos: IArticulo[] = [];
  showQuantity = 100;
  searchTerm = '';
  ordenandoByVendidos = true;
  modalRef: BsModalRef;
  total = 0;
  @ViewChild(FiltroCategoriasComponent, { static: false }) filtroCategorias: FiltroCategoriasComponent;

  constructor(
    public articuloService: ArticuloService,
    private sinonimoService: SinonimoService,
    private modalService: BsModalService,
    private inactiveScreen: InactiveScreenService,
  ) { }

  ngOnInit() { }

  ngAfterViewInit(): void {
    this.filtroCategorias.getCategorias();
    this.mediaPantalla();
  }

  ngOnDestroy() {
    for (let i = 1; i <= this.modalService.getModalsCount(); i++) {
      this.modalService.hide(i);
    }
  }

  getProductos() {
    this.articuloService.getAll()
      .subscribe((result: IArticulo[]) => {
        this.articuloService.setArticulosSinImagen(result);
        if (this.filtroCategorias.queMostrar === 'ordenar') {
          this.filtroCategorias.categorias.forEach((categoria: ICategoria) => {
            const tempArticulos = result.filter((articulo: IArticulo) => {
              return articulo.categoria_selfservice === categoria.id;
            });
            result = tempArticulos;
          });
        }
        localStorage.setItem('articulos', JSON.stringify(result));
        this.setProductos();
      }, (error) => {
        console.error(error);
      });
  }

  setProductos() {
    this.articulos = JSON.parse(localStorage.getItem('articulos'));
    this.filterItems();
    this.loading = false;
  }

  filterItems() {
    if (this.filtroCategorias.categoriaActive === 0) {
      this.auxArticulos = this.articulos;
      return;
    }
    this.auxArticulos = this.articulos.filter(x => {
      return x.categoria_selfservice === this.filtroCategorias.categoriaActive;
    });
    this.ordenar();
  }

  ordenar() {
    if (this.ordenandoByVendidos) {
      this.auxArticulos.sort((a, b) => {
        return b.cantidadVendida - a.cantidadVendida;
      });
    }
  }

  selectArticulo(articulo: IArticulo) {
    if (articulo.ExiVta < 1) {
      if (this.modalRef) return;
      this.modalRef = this.modalService.show(NoStockComponent, {
        class: 'modal-dialog-centered',
        backdrop: false,
        ignoreBackdropClick: true,
      });
      this.modalRef.content.onClose
        .subscribe(() => this.modalRef = null);
    } else {
      this.getByID(articulo.id);
    }
  }

  getByID(id: number) {
    this.articuloService.getById(id)
      .subscribe((res: IArticulo) => {
        if (res.FPP) {
          this.openModalPromos(res);
        } else {
          this.getSinonimos(res);
        }
      }, err => console.error(err));
  }

  getSinonimos(articulo: IArticulo) {
    this.sinonimoService.getSinonimos(articulo.CodSec, articulo.CodArt)
      .subscribe((res: any[]) => {
        if (res.length) {
          const sinonimos = [];
          const gruposArticulos = _.groupBy(res[0].productos, 'ID_SIN');
          Object.keys(gruposArticulos).forEach((key, i) => {
            sinonimos.push({ productos: gruposArticulos[key], });
            for (const a of articulo.productos) {
              if (key === a.idSinonimo.toString()) {
                sinonimos[i].cantidad = sinonimos[i].cantidadRestante = a.cantidad;
                continue;
              }
            }
          });
          res = sinonimos;
          this.openModalSinonimos(res, articulo);
        } else {
          this.articuloService.setArticulo(articulo);
        }
      });
  }

  openModalPromos(articulo: IArticulo) {
    if (this.modalRef) return;
    this.articuloService.setArticulosSinImagen([articulo]);
    this.modalRef = this.modalService.show(PromocionComponent, {
      initialState: { articulosPromo: [articulo] },
      class: 'modal-dialog-centered',
      ignoreBackdropClick: true,
    });
    this.modalRef.content.onClose
      .subscribe(() => this.modalRef = null);
    this.mediaPantalla();
  }

  openModalSinonimos(sinonimosData: ISinonimo[], articulo: IArticulo) {
    if (this.modalRef) return;
    this.modalRef = this.modalService.show(SinonimoComponent, {
      initialState: {
        sinonimos: sinonimosData,
        articulo
      },
      class: 'modal-dialog-centered',
      ignoreBackdropClick: true,
    });

    this.modalRef.content.onClose
      .subscribe((res: any) => {
        this.modalRef = null;
        if (!res) return;
        articulo.productos = res.articulos;
        this.articuloService.setArticulo(articulo);
      });
    this.mediaPantalla();
  }

  deleteArticulo(index: number) {
    this.articuloService.deleteArticulo(index);
  }

  increaseShow() {
    this.showQuantity += 100;
  }


  validarFecha(fechaInicio: string, fechaFin: string) {
    return DateExtension.ValidateDateRange(fechaInicio, fechaFin);
  }

  @HostListener('scroll', ['$event'])
  scrollEvent(event: Event) {
    clearTimeout(this.inactiveScreen.timerReposo);
    this.inactiveScreen.startTimeOutInactividad();
  }

  mouseup() {
    if (!this.timeoutHandler) return;
    clearInterval(this.timeoutHandler);
  }

  scrollY(el: HTMLElement, value) {
    el.scroll({ behavior: 'smooth', top: value + el.scrollTop });
    this.timeoutHandler = setInterval(() => {
      el.scroll({ behavior: 'smooth', top: value + el.scrollTop });
    }, 500);
  }

  scrollX(el: HTMLElement, value) {
    el.scroll({ behavior: 'smooth', left: value + el.scrollLeft });
    this.timeoutHandler = setInterval(() => {
      el.scroll({ behavior: 'smooth', left: value + el.scrollLeft });
    }, 500);
  }

  mediaPantalla() {
    if ($('body').hasClass('media-pantalla')) {
      $(`.cat-content,#cat-content,#content,.cat-btn,#boxCarrito,
        .cat-box,.img-categoria, .modal-content`)
        .addClass('media-pantalla')
        .addBack('media-pantalla');
    }
  }
}