import {
  AfterViewInit,
  Component,
  ElementRef,
  Input,
  OnDestroy,
  OnInit,
  SimpleChanges,
  ViewChild,
} from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Store } from '@ngrx/store';
import {
  DialogCloseResult,
  DialogRef,
  DialogService,
  WindowCloseResult,
  WindowRef,
  WindowService,
} from '@progress/kendo-angular-dialog';
import {
  CellClickEvent,
  EditEvent,
  GridComponent,
} from '@progress/kendo-angular-grid';
import { BadgeAlign, BadgePosition } from '@progress/kendo-angular-indicators';
import { TextBoxComponent } from '@progress/kendo-angular-inputs';
import { HierarchyBindingDirective } from '@progress/kendo-angular-menu';
import { NotificationService } from '@progress/kendo-angular-notification';
import { TreeViewSize } from '@progress/kendo-angular-treeview/dist/es2015/size';
import { paperclipIcon } from '@progress/kendo-svg-icons';
import { Observable, of, Subscription } from 'rxjs';
import {
  catchError,
  debounceTime,
  distinctUntilChanged,
  filter,
  map,
  switchMap,
  tap,
} from 'rxjs/operators';
import { AuthService } from 'src/app/auth/services/auth.service';
import { BrandFilter } from 'src/app/models/brand.model';
import { ClasseMercadologica } from 'src/app/models/classe-mercadologica.model';
import { Departamento } from 'src/app/models/departamento.model';
import { FilterProduct } from 'src/app/models/filter-product.model';
import { OrderByProduct } from 'src/app/models/orderby-product.model';
import { SaleProduct, Stock } from 'src/app/models/sale-product.model';
import { StoreERP } from 'src/app/models/store.model';
import { LookupService } from 'src/app/services/lookup.service';
import { MessageService } from 'src/app/services/messages.service';
import { ProductService } from 'src/app/services/product.service';
import { ShoppingService } from 'src/app/services/shopping.service';
import { PreCustomerComponent } from '../../sales/components/pre-customer/pre-customer.component';
import { DataDeliveryComponent } from '../components/data-delivery/data-delivery.component';
import { ProductModalComponent } from '../components/product-modal/product-modal.component';
import {
  AddItemAction,
  DeleteItemAction,
  LoadShoppingAction,
  LoadShoppingItemsAction,
  UpdateQuantityItemAction,
} from '../store/actions/shopping.action';
import { SaleState } from '../store/models/sale-state.model';
import { ShoppingItem } from '../store/models/shopping-item';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.scss'],
})
export class ProductListComponent implements OnInit, AfterViewInit, OnDestroy {
  productPromotion =
    localStorage.getItem('promotion') === 'true' ? true : false;
  markdown = localStorage.getItem('markdown') === 'true' ? true : false;
  oportunity = localStorage.getItem('oportunity') === 'true' ? true : false;
  offers = localStorage.getItem('offers') === 'true' ? true : false;
  description = localStorage.getItem('text');
  onlyWithStock =
    localStorage.getItem('onlyWithStock') === 'true' ? true : false;
  storeStock = localStorage.getItem('storeStock');

  @ViewChild('hierarchy')
  public hierarchy: HierarchyBindingDirective;
  public selectedComponentSize: TreeViewSize = 'medium';
  public selectedKeys: any[] = [];
  public expandedKeys: any[] = [];
  @ViewChild('productCard') productCard: ElementRef;
  @ViewChild('quantityCart') quantityCart: TextBoxComponent;
  public userName: string;
  public storeName: string;

  public heightListProducts = 850;
  public widthListProducts = 850;

  /*Badge cart */
  public position: BadgePosition = 'inside';
  public get align(): BadgeAlign {
    return { vertical: 'top', horizontal: 'end' };
  }
  public themeBadge = 'warning';

  /* controle grid do carrinho de compras */
  @ViewChild(GridComponent) private grid: GridComponent;
  private editedRowIndex: number;
  private isNew = false;
  public get isInEditingMode(): boolean {
    return this.editedRowIndex !== undefined || this.isNew;
  }
  /* fim controle do carrinho de compras */

  searchProduct = new FormControl();
  quantitySale = new FormControl('1');
  public icons = { paperclip: paperclipIcon };
  pageNumber = 1;
  pageSize = 100;
  public themeColor = 'inherit';
  public keys: string[] = [];

  /* OrderBy for list of Products */
  public listOrderBy: Array<OrderByProduct> = [
    { text: 'Descrição', field: 'DESCRICAO' },
    { text: 'Menor Preço', field: 'PRECOVENDA' },
  ];

  public selectedOrderBy: OrderByProduct = this.listOrderBy[0];

  /*Filter by percent off the product */
  public percentOff: [number, number] = [0, 100];
  public minPercentOff = 0;
  public maxPercentOff = 100;
  public largeStep = 2;
  public smallStep = 10;

  public windowTop = 100;
  public windowLeft = 0;
  public opened = false;

  /* Image card product */
  public imageWidth = '100%';
  public imageHeight = '350px';

  products$: Observable<SaleProduct[]>;
  products: SaleProduct[];
  productsLoad: SaleProduct[];
  stock$: Observable<Stock[]>;
  images: string[] = [];
  brands: BrandFilter[] = [];
  store$: Observable<StoreERP[]>;

  shopping$: Observable<ShoppingItem[]>;
  shoppingItens: ShoppingItem[] = [];
  totalCart$: Observable<number>;

  searchSubscription: Subscription;
  loadProducts: SaleProduct[];
  existsProduct = false;
  departmentSubscription: Subscription;
  departments$: Observable<Departamento[]>;
  classeMercadologica$: Observable<ClasseMercadologica[]>;

  subscriptionProduct: Subscription;
  subscriptionStock: Subscription;
  subscriptionFilterProducts: Subscription;
  subscriptionUpdate: Subscription;

  items: any[];
  categories: any[] = [];
  filteredProducts: any[] = [];

  loading$: Observable<boolean>;
  loading = false;
  error$: Observable<Error>;
  error: Error = null;
  updating$: Observable<boolean>;
  newShoppingItem: ShoppingItem = {
    id: null,
    invoiceStore: null,
    idCart: null,
    idProduct: null,
    description: null,
    promotion: null,
    image: null,
    productType: null,
    quantity: null,
    price: null,
    brand: null,
    ean: null,
    percentUpQuantity: null,
    upQuantity: null,
    deliveryType: null,
    stockStore: null,
    seller: null,
    listPrice: null,
    smallDescription: null,
    discount: null,
    discountValue: null,
    userDiscount: null,
    mutiple: null,
    auxDescription: null,
    base: null,
    line: null,
    can: null,
    color: null,
    letter: null,
  };

  showInformation = false;
  titleInformation = 'Pedido de venda';
  messageInformation = '';
  informationDescription = '';

  showConfirmationCancelSale = false;
  openedConfirmationCancelItem = false;
  titleMessage = 'Pedido de venda';
  messageConfirmation = 'Confirma cancelamento da venda?';
  textButtonConfirmation = 'Sim';
  textButtonCancel = 'Não';
  itemCancel: ShoppingItem;

  /* Filters for products */
  // @Input() filters: FilterProduct;
  @Input() filters: FilterProduct = { brands: [] };
  // filters: FilterProduct = { brands: [] };
  urlDepartment = '';
  urlProduct = '';
  filterProducts = '';
  filterDescription = '';
  productType = '';
  stockSotre = '';
  orderBy = '';

  constructor(
    private productService: ProductService,
    private store: Store<SaleState>,
    private readonly authService: AuthService,
    private readonly shoppingService: ShoppingService,
    private readonly lookupService: LookupService,
    private readonly fb: FormBuilder,
    private windowService: WindowService,
    private readonly route: ActivatedRoute,
    private readonly dialogService: DialogService,
    private readonly router: Router,
    private readonly messageService: MessageService,
    private notificationService: NotificationService
  ) {}

  public expandedOnClear = 'none';

  public data: any[] = [];

  public formQuantity: FormGroup = this.fb.group({
    quantity: [],
  });
  public formFilter: FormGroup = this.fb.group({
    onlyWithStock: new FormControl(false),
    outLine: new FormControl(false),
    campaign: new FormControl(false),
  });
  public checkedKeysBrand: any[] = [];
  public selectedBrandKeys: any[] = [];
  public childrenBrand = (dataItem: any): Observable<any[]> =>
    of(dataItem.items);
  public hasChildrenBrand = (dataItem: any): boolean => !!dataItem.items;

  ngOnDestroy(): void {
    if (this.departmentSubscription) {
      this.departmentSubscription.unsubscribe();
    }
    if (this.searchSubscription) {
      this.searchSubscription.unsubscribe();
    }
    if (this.subscriptionProduct) {
      this.subscriptionProduct.unsubscribe();
    }
    if (this.subscriptionStock) {
      this.subscriptionStock.unsubscribe();
    }
    if (this.subscriptionUpdate) {
      this.subscriptionUpdate.unsubscribe();
    }
  }

  // ngOnChanges(changes: SimpleChanges): void {
  //   if (changes['products'] && changes['products'].currentValue) {
  //     this.filteredProducts = changes['products'].currentValue;
  //     console.log('Produtos recebidos do pai:', this.filteredProducts);
  //   }
  // }

  ngOnChanges(changes: SimpleChanges): void {
    console.log('🚀 ~ ProductListComponent ~ ngOnChanges ~ changes:', changes);

    if (changes['filters'] && changes['filters'].currentValue) {
      this.getSaleProducts(changes['filters'].currentValue); // Atualiza a busca com o filtro recebido
    }
  }

  ngAfterViewInit(): void {
    this.heightListProducts =
      document.getElementById('listProducts').offsetHeight;
    this.widthListProducts =
      document.getElementById('listProducts').offsetWidth;
  }

  ngOnInit(): void {
    if (localStorage.getItem('text') != null) {
      this.filters.text = localStorage.getItem('text');
    }
    if (localStorage.getItem('promotion') != null) {
      this.filters.promotion =
        localStorage.getItem('promotion') === 'true' ? true : false;
    }
    if (localStorage.getItem('markdown') != null) {
      this.filters.markdown =
        localStorage.getItem('markdown') === 'true' ? true : false;
    }
    if (localStorage.getItem('oportunity') != null) {
      this.filters.oportunity =
        localStorage.getItem('oportunity') === 'true' ? true : false;
    }
    if (localStorage.getItem('offers') != null) {
      this.filters.offers =
        localStorage.getItem('offers') === 'true' ? true : false;
    }
    if (localStorage.getItem('onlyWithStock') != null) {
      this.filters.onlyWithStock =
        localStorage.getItem('onlyWithStock') === 'true' ? true : false;
    }
    this.filters.urlCategory = '';

    console.log('Filtros de pesquisa: ' + JSON.stringify(this.filters));

    /* Atualizar componentes de tela */
    this.markdown = this.filters.markdown;
    this.productPromotion = this.filters.promotion;
    this.offers = this.filters.offers;
    this.oportunity = this.filters.oportunity;
    this.storeStock = this.filters.storeStock;
    this.onlyWithStock = this.filters.onlyWithStock;

    this.userName = this.authService.getUserName();
    this.storeName = this.authService.getStoreName();
    this.filterProducts = this.route.snapshot.params.filter;
    this.urlDepartment = this.route.snapshot.params.url;
    this.filterDescription = this.route.snapshot.params.description;
    this.productType = this.route.snapshot.params.type;
    this.brands = [];
    this.store$ = this.lookupService.getStore();

    if (this.route.snapshot.params.description != null) {
      localStorage.setItem('text', this.route.snapshot.params.description);
    }

    // if (this.filterProducts === 'category') {
    //   this.getProductByDepartment(this.urlDepartment);
    // }

    // if (this.filterProducts === 'product') {
    //   this.searchProducts(this.urlDepartment);
    //   this.loadProducts = this.products;
    // }

    // if (this.filterDescription && this.filterDescription.length >= 3) {
    //   this.searchProducts(this.filterDescription);
    //   this.loadProducts = this.products;
    // }

    // if (this.productType === 'markdown') {
    //   this.filters = { brands: [], markdown: true };
    //   //      this.searchProductsByType(filterProducts);
    //   //      this.loadProducts = this.products;
    // }

    // if (this.productType === 'promotion') {
    //   this.filters = { brands: [], promotion: true };
    // }

    // if (this.productType === 'oportunity') {
    //   this.filters = {
    //     brands: [], productPromotion: this.productPromotion,
    //     oportunity: this.oportunity, markdown: this.markdown,
    //     offers: this.offers, text: this.description
    //   };
    // }

    this.searchSubscription = this.searchProduct.valueChanges
      .pipe(
        map((value) => value.trim()),
        filter((value) => value.length > 3),
        debounceTime(400),
        distinctUntilChanged(),
        tap((value) => {
          this.loadProducts = null;
          this.filters.text = value;
        }),
        switchMap((value) =>
          this.productService.getProductByFilter(
            this.authService.getStore(),
            this.pageNumber,
            this.pageSize,
            this.filters
          )
        ),
        map((products) => (this.loadProducts = products)),
        tap((products) => (this.existsProduct = products.length > 0)),
        tap(() => (this.filters.text = null))
      )
      .subscribe();

    this.shopping$ = this.store.select((store) => store.shopping.list);
    this.totalCart$ = this.store.select((store) => store.shopping.total);
    this.loading$ = this.store.select((store) => store.shopping.loading);
    this.error$ = this.store.select((store) => store.shopping.error);
    this.updating$ = this.store.select((store) => store.shopping.updating);

    this.categories = [];
    this.products = [];
    this.productsLoad = [];
    this.loading = true;

    this.subscriptionProduct = this.productService
      .getClasseMercadologica()
      .pipe(
        map((data) => {
          this.items = this.mapItems(
            data.filter((d) => d.tituloEcommerce != null),
            ['tituloEcommerce', 'descricaoSecao', 'descricaoCategoria'],
            ['secoes', 'categorias']
          );
          this.data = this.items;
          console.log(this.items);
        }),
        switchMap(() =>
          this.productService.getProductByFilter(
            this.authService.getStore(),
            this.pageNumber,
            this.pageSize,
            this.filters
          )
        ),
        map((products: SaleProduct[]) => {
          this.products = products;
          //   console.log(this.products);
          this.loadMoreProducts();
          products
            .sort((a, b) =>
              a.brand.replace('#', '') < b.brand.replace('#', '')
                ? -1
                : a.brand.replace('#', '') > b.brand.replace('#', '')
                ? 1
                : 0
            )
            .forEach((product) => {
              const brandFilter = this.brands.find(
                (brand) => brand.description === product.brand
              );
              if (brandFilter == null) {
                const newBrand = new BrandFilter();
                newBrand.description = product.brand;
                newBrand.checked = false;
                this.brands.push(newBrand);
              }
            });
          //   this.searchProduct.setValue('');
          this.existsProduct = false;
        }),
        tap(() => (this.loading = false)),
        tap(() => (this.filters.text = ''))
      )
      .subscribe(() => this.loadCart());
  }

  onSearchFromChild(searchTerm: string): void {
    console.log('Busca recebida do componente filho:', searchTerm);
    this.filters.text = searchTerm.toUpperCase(); // Atualiza o filtro com o termo de busca
    this.getSaleProducts(this.filters); // Realiza a busca
  }

  onProductsFound(products: any[]): void {
    this.filteredProducts = products; // Atualiza os produtos filtrados
  }

  onFilterSelected(filter: any): void {
    console.log('Filtro recebido do componente filho:', filter); // Verifique se os filtros estão chegando corretamente
    this.filters = { ...this.filters, ...filter }; // Atualiza os filtros no pai
    this.getSaleProducts(this.filters); // Executa a busca com os filtros atualizados
  }

  loadCart() {
    console.log('consultando carrinho');
    this.shoppingItens = [];
    let idCart = this.shoppingService.getCart();
    if (idCart == null) {
      idCart = 'SV';
    }
    //  if ( idCart && idCart != null ) {
    this.store.dispatch(new LoadShoppingItemsAction(idCart));
    this.store.dispatch(new LoadShoppingAction(idCart));
    this.shopping$.subscribe(
      (data) => (this.shoppingItens = JSON.parse(JSON.stringify(data)))
    );
    //  }
  }

  selectedCategory(data: any, categoryAll: boolean = false) {
    this.selectedBrandKeys = [];
    this.filters.brands = [];
    this.brands = [];
    if (categoryAll) {
      this.filters.urlCategory = null;
      this.selectedKeys = null;
    } else {
      this.filters.urlCategory = data.dataItem.path;
    }
    this.getSaleProducts(this.filters);
    // this.getProductByDepartment(data.dataItem.path);
  }

  keyDownFunction(event) {
    if (event.keyCode === 13) {
      // tslint:disable-next-line: no-shadowed-variable
      this.filters.text = this.searchProduct.value;
      this.getSaleProducts(this.filters);
    }
  }

  selectProductByDescription(text: string) {
    this.filters.text = text;
    this.getSaleProducts(this.filters);
  }

  selectDepartment(select: any) {
    console.log(select.item.path);
    this.urlDepartment = select.item.path;
    this.getProductByDepartment(select.item.path);
  }

  // convert the received data to menu items.
  private mapItems(
    items: any[],
    textFields: string[],
    childFields: string[],
    level: number = 0
  ): any[] {
    const childField = childFields[level];
    const textField = textFields[level];

    return items.map((item) => {
      const result: any = {
        text: item[textField],
        path: item.url,
      };
      // convert the children data to menu items.
      if (childField && item[childField]) {
        result.items = this.mapItems(
          item[childField],
          textFields,
          childFields,
          level + 1
        );
      }
      return result;
    });
  }

  public isExpanded = (dataItem: any, index: string) => {
    return this.keys.indexOf(index) > -1;
  };

  public handleCollapse(node) {
    this.keys = this.keys.filter((k) => k !== node.index);
  }

  public handleExpand(node) {
    this.keys = this.keys.concat(node.index);
  }

  public children = (dataitem: any): Observable<any[]> => of(dataitem.items);
  public hasChildren = (dataitem: any): boolean => !!dataitem.items;

  public openClose(isOpened: boolean) {
    this.opened = isOpened;
  }

  fechProducts() {
    this.loading = true;
    this.productsLoad = [];
    this.products$
      .pipe(
        map((products) => {
          console.log(
            'Recebendo dados da pesquisa de produtos - Quantidade: ' +
              products.length
          );
          this.products = products;
          this.loadMoreProducts();
          products
            .sort((a, b) =>
              a.brand.replace('#', '') < b.brand.replace('#', '')
                ? -1
                : a.brand.replace('#', '') > b.brand.replace('#', '')
                ? 1
                : 0
            )
            .forEach((product) => {
              const brandFilter = this.brands.find(
                (brand) => brand.description === product.brand
              );
              if (brandFilter == null) {
                const newBrand = new BrandFilter();
                newBrand.description = product.brand;
                newBrand.checked = false;
                this.brands.push(newBrand);
              }
            });
          //    this.searchProduct.setValue('');
          this.existsProduct = false;
        }),
        tap(() => (this.loading = false)),
        tap(() => (this.filters.text = null)),
        catchError((error) => {
          this.loading = false;
          return of(error);
        })
      )
      .subscribe();
  }

  searchProductsByType(filterProducts: FilterProduct) {
    try {
      console.log(
        'Iniciando pesquisa de produtos ' + JSON.stringify(filterProducts)
      );
      this.categories = [];
      this.products = [];
      this.productsLoad = [];
      this.products$ = this.productService.getSaleProducts(
        this.authService.getStore(),
        this.pageNumber,
        this.pageSize,
        filterProducts
      );
      this.fechProducts();
    } catch (e) {
      console.log('Erro ao consultar produtos.');
      console.log(e);
    }
  }

  getSaleProducts(filterProduct: FilterProduct = null) {
    console.log('Filtros recebidos:', filter);
    try {
      console.log(filterProduct);
      this.loading = true;
      this.categories = [];
      this.products = [];
      this.productsLoad = [];
      // this.products$ = this.productService.getSaleProducts(this.authService.getStore(), this.pageNumber, this.pageSize, filterProduct);
      this.products$ = this.productService.getProductByFilter(
        this.authService.getStore(),
        this.pageNumber,
        this.pageSize,
        filterProduct
      );
      this.fechProducts();
    } catch (e) {
      console.log('Erro ao consultar produtos.');
      console.log(e);
    }
  }

  searchProducts(text: string) {
    try {
      this.brands = [];
      this.selectedBrandKeys = [];
      this.categories = [];
      this.products = [];
      this.productsLoad = [];
      this.products$ = this.productService.searchProduct(
        this.authService.getStore(),
        this.pageNumber,
        this.pageSize,
        text
      );
      this.fechProducts();
    } catch (e) {
      console.log('Erro ao consultar produtos.');
      console.log(e);
    }
  }

  getProductByDepartment(urlDepartment: string) {
    let url = '';
    console.log(urlDepartment);
    if (urlDepartment.includes('/')) {
      url = 'category/' + urlDepartment;
    } else {
      url = 'department/' + urlDepartment;
    }
    url = 'category/' + urlDepartment;
    try {
      this.brands = [];
      this.selectedBrandKeys = [];
      this.categories = [];
      this.products = [];
      this.productsLoad = [];
      this.products$ = this.productService.getProductByDepartment(
        this.authService.getStore(),
        this.pageNumber,
        this.pageSize,
        url
      );
      this.fechProducts();
      /*this.products$
        .subscribe(products => {
          this.products = products;
          this.loadMoreProducts();
          products.forEach(product => {
            const brandFilter = this.brands.find(brand => brand.description === product.brand);
            if (brandFilter == null) {
              const newBrand = new BrandFilter();
              newBrand.description = product.brand;
              newBrand.checked = false;
              this.brands.push(newBrand);
            }
            if (!this.categories.find(category => category.description === product.category)) {
              this.categories.push({ description: product.category });
            }
          });
        });*/
    } catch (e) {
      console.log('Erro ao consultar produtos.');
      console.log(e);
    }
  }

  async getFilterProducts() {
    this.filters.promotion = this.productPromotion;
    this.filters.markdown = this.markdown;
    this.filters.oportunity = this.oportunity;
    this.filters.offers = this.offers;
    this.filters.onlyWithStock = this.onlyWithStock;
    this.filters.percentOffMin = this.percentOff[0];
    this.filters.percentOffMax = this.percentOff[1];
    this.products = [];
    this.productsLoad = [];
    this.subscriptionFilterProducts = this.productService
      .getProductByFilter(
        this.authService.getStore(),
        this.pageNumber,
        this.pageSize,
        this.filters
      )
      .subscribe((products) => {
        this.products = products;
        console.log(products);
        this.loadMoreProducts();
        this.brands = [];
        products
          .sort((a, b) =>
            a.brand.replace('#', '') < b.brand.replace('#', '')
              ? -1
              : a.brand.replace('#', '') > b.brand.replace('#', '')
              ? 1
              : 0
          )
          .forEach((product) => {
            const brandFilter = this.brands.find(
              (brand) => brand.description === product.brand
            );
            if (brandFilter == null) {
              const newBrand = new BrandFilter();
              newBrand.description = product.brand;
              newBrand.checked = false;
              this.brands.push(newBrand);
            }
          });
      });
  }

  getImage(urlImage: string) {
    if (urlImage === null) {
      return '';
    }
    if (urlImage.length > 0) {
      const re = /\s*;\s*/;
      if (urlImage.indexOf(';') === -1) {
        urlImage += ';';
      }
      this.images = urlImage.split(re);
      return this.images[0];
    }
  }

  addItem(product: any) {
    const initialValue = 0;
    const stockCart = this.shoppingItens
      .filter(
        (i) =>
          i.idProduct === product.idProduct &&
          i.stockStore === this.authService.getStore()
      )
      .reduce(
        (previousValue, item) => previousValue + item.quantity,
        initialValue
      );

    if (product.deliveryType !== 'EF') {
      // } && product.deliveryType !== 'EN') {
      if (
        product.stockStore <
        Number.parseFloat(product.quantity) + stockCart
      ) {
        this.showMessage(
          'Inclusão de produto',
          'Filial selecionada com estoque inferior a quantidade vendida.'
        );
        return;
      }
    }
    const idCart = this.shoppingService.getCart();
    const quantitySale =
      Math.ceil(product.quantity / product.mutiple) * product.mutiple;
    this.store.dispatch(
      new AddItemAction({
        id: null,
        idCart,
        invoiceStore: this.authService.getStore(),
        idProduct: product.idProduct,
        description: product.title,
        image: this.getImage(product.urlImage),
        productType: product.productType,
        ean: product.ean,
        percentUpQuantity: 0,
        upQuantity: 0,
        quantity: quantitySale,
        price: product.salePrice,
        deliveryType: product.deliveryType,
        stockStore: product.store,
        seller: this.authService.getSeller(),
        discount: 0,
        discountValue: 0,
        promotion: product.offPercent > 0 ? product.salePrice : 0,
        listPrice: product.listPrice,
        userDiscount: null,
        mutiple: product.mutiple,
        auxDescription: null,
        smallDescription: product.smallDescription,
        brand: product.brand,
        base: product.base,
        line: product.line,
        color: product.color,
        can: product.can,
        letter: product.letter,
      })
    );
    if (!this.subscriptionUpdate) {
      this.subscriptionUpdate = this.updating$.subscribe((inProcess) => {
        if (this.error) {
          this.notificationService.show({
            content: this.error.message,
            animation: { type: 'slide', duration: 400 },
            position: { horizontal: 'right', vertical: 'bottom' },
            type: { style: 'error', icon: true },
            hideAfter: 2000,
          });
          console.log('Erro ocorrido: ' + JSON.stringify(this.error));
        }
        if (!inProcess && this.error == null) {
          this.notificationService.show({
            content: 'Produto incluído com sucesso!',
            animation: { type: 'slide', duration: 400 },
            position: { horizontal: 'right', vertical: 'bottom' },
            type: { style: 'success', icon: true },
            hideAfter: 2000,
          });
          //  this.openFormPreCustomer();
        }
      });
    }
  }

  updateItem(value: ShoppingItem, quantity: number) {
    try {
      const idCart = this.shoppingService.getCart();
      this.store.dispatch(
        new UpdateQuantityItemAction({
          id: value.id,
          idCart,
          invoiceStore: value.invoiceStore,
          idProduct: value.idProduct,
          description: value.description,
          image: value.image,
          productType: value.productType,
          quantity,
          price: value.price,
          deliveryType: value.deliveryType,
          stockStore: value.stockStore,
          seller: value.seller,
          discount: value.discount,
          discountValue: value.discountValue,
          ean: value.ean,
          listPrice: value.listPrice,
          userDiscount: value.userDiscount,
          mutiple: value.mutiple,
          percentUpQuantity: value.percentUpQuantity,
          upQuantity: value.upQuantity,
          auxDescription: null,
          smallDescription: value.smallDescription,
          brand: value.brand,
          promotion: value.promotion,
          base: value.base,
          line: value.line,
          color: value.color,
          can: value.can,
          letter: value.letter,
        })
      );
    } catch (e) {
      console.log(e);
    }
  }

  selectBrand(brand: any) {
    console.log('url categoria: ' + this.urlDepartment);
    this.brands
      .filter((data) => data.description === brand.description)
      .forEach((item) => {
        item.checked = !item.checked;
      });
    const brandsSelect = this.brands
      .filter((data) => data.checked)
      .map((item) => item.description);
    const filterProduct: FilterProduct = { brands: brandsSelect };
    if (this.filterProducts === 'category') {
      filterProduct.urlCategory = this.urlDepartment;
    }
    this.getSaleProducts(filterProduct);
    // this.getSaleProducts();
  }

  getUserName() {
    return this.authService.getUserName();
  }

  getSeller() {
    return this.authService.getSeller();
  }

  public openFormPreCustomer() {
    console.log(this.productCard);
    const windowRef: WindowRef = this.windowService.open({
      title: 'Pré-cadastro de cliente',
      content: PreCustomerComponent,
      width: 350,
      height: 400,
    });

    windowRef.result.subscribe((result) => {
      if (result instanceof WindowCloseResult) {
        console.log('WindowCloseResult', result);
      }
    });

    windowRef.content.instance.submitForm.subscribe((formData) => {
      // handle form data
      console.log(formData);
      localStorage.setItem('preCustomer', JSON.stringify(formData));
      windowRef.close();
    });
  }

  receiveProductCard(product: any) {
    try {
      const baseValue = (product?.base ?? '').toString().trim().toUpperCase();
      if (baseValue === 'S') {
        this.messageService.showInformation(
          'Produto Tintométrico',
          'Esse produto só pode ser adicionado com coloração, usar o botão ver mais para adicionar cor'
        );
        return;
      }
      console.log(JSON.stringify(product));
      const initialValue = 0;
      const stockCart = this.shoppingItens
        .filter(
          (i) =>
            i.idProduct === product.idProduct &&
            i.stockStore === this.authService.getStore()
        )
        .reduce(
          (previousValue, item) => previousValue + item.quantity,
          initialValue
        );
      if (
        !product.store_stock ||
        Number.parseFloat(product.quantity) + stockCart > product.store_stock
      ) {
        const dialog: DialogRef = this.dialogService.open({
          title: product.idProduct + '-' + product.smallDescription,
          content: DataDeliveryComponent,
          actions: [
            { text: 'Cancelar', confirm: false, themeColor: 'danger' },
            { text: 'Gravar', confirm: true, themeColor: 'primary' },
          ],
          width: 450,
          height: 500,
          minWidth: 250,
          preventAction: (ev, formDialog) => {
            console.log('Resultado: ' + JSON.stringify(ev));
            const actionUser = JSON.parse(JSON.stringify(ev));
            const formGroup = (
              formDialog.content.instance as DataDeliveryComponent
            ).form;
            if (!formGroup.valid && actionUser.confirm) {
              const quantity = formGroup.get('quantity').value;
              const stockStore = formGroup.get('stockStore').value;
              const deliveryType = formGroup.get('deliveryType').value;

              if (deliveryType === '') {
                this.messageInformation = 'Tipo de entrega não foi informado.';
                this.informationDescription =
                  'Informe o tipo de entrega do produto para incluir o item no pedido.';
                this.showInformation = true;
                return !formGroup.valid;
              }

              if (deliveryType !== 'EF') {
                if (quantity >= Number.parseFloat(stockStore.toFixed(3))) {
                  this.messageInformation =
                    'Produto sem estoque disponível na filial selecionada.';
                  this.informationDescription =
                    'Selecione filial retira que tenha estoque disponível igual ou maior que a quantidade do desejada.';
                  this.showInformation = true;
                  return !formGroup.valid;
                }
              }
            }
            return !formGroup.valid && actionUser.confirm;
          },
        });

        const deliveryInfo = dialog.content.instance as DataDeliveryComponent;
        deliveryInfo.idProduct = product.idProduct;
        deliveryInfo.quantity = product.quantity;

        dialog.result.subscribe((result) => {
          if (result instanceof DialogCloseResult) {
            console.log('close');
          } else {
            console.log('action', result);
            const dataDelivery = JSON.stringify(result);
            if (result.text === 'Gravar') {
              console.log(deliveryInfo.form);
              if (deliveryInfo.form.status === 'INVALID') {
                this.showMessage(
                  'Inclusão de produto',
                  'Não foi informado uma filial retira / forma de entrega para o produto.'
                );
              }
              product.stockStore = deliveryInfo.form.get('stockStore').value;
              product.store = deliveryInfo.form.get('store').value;
              product.deliveryType =
                deliveryInfo.form.get('deliveryType').value;
              console.log('Quantidade: ' + deliveryInfo.quantity);
              console.log('Multiplo: ' + product.mutiple);
              let quantityBox = Math.trunc(
                deliveryInfo.quantity / product.mutiple
              );
              console.log('Quantidade de caixas: ' + quantityBox);
              const quantityArred =
                quantityBox * Number.parseFloat(product.mutiple);
              if (quantityArred < deliveryInfo.quantity) {
                quantityBox = quantityBox + 1;
              }
              const quantitySale = quantityBox * product.mutiple;
              deliveryInfo.quantity = quantitySale;

              this.addItem(product);
            }
          }
        });
      } else {
        const idCart = this.shoppingService.getCart();
        console.log('Quantidade: ' + product.quantity);
        console.log('Multiplo: ' + product.mutiple);
        let quantityBox = Math.trunc(product.quantity / product.mutiple);
        console.log('Quantidade de caixas: ' + quantityBox);
        const quantityArred = quantityBox * Number.parseFloat(product.mutiple);
        if (quantityArred < product.quantity) {
          quantityBox = quantityBox + 1;
        }
        const quantitySale = Number.parseFloat(
          (quantityBox * product.mutiple).toFixed(3)
        );

        // const quantitySale = Math.ceil(product.quantity / product.mutiple) * product.mutiple;
        this.store.dispatch(
          new AddItemAction({
            id: null,
            idCart,
            invoiceStore: this.authService.getStore(),
            idProduct: product.idProduct,
            description: product.title,
            image: this.getImage(product.urlImage),
            productType: product.productType,
            percentUpQuantity: 0,
            upQuantity: 0,
            quantity: quantitySale,
            price: product.salePrice,
            deliveryType: product.productType === 'A' ? 'RI' : 'EN',
            stockStore: this.authService.getStore(),
            seller: this.authService.getSeller(),
            discount: 0,
            discountValue: 0,
            ean: product.ean,
            promotion: product.offPercent > 0 ? product.salePrice : 0,
            listPrice: product.listPrice,
            userDiscount: null,
            mutiple: product.mutiple,
            auxDescription: null,
            smallDescription: product.smallDescription,
            brand: product.brand,
            base: product.base,
            line: product.line,
            color: product.color,
            can: product.can,
            letter: product.letter,
          })
        );

        if (!this.subscriptionUpdate) {
          this.subscriptionUpdate = this.updating$.subscribe((inProcess) => {
            console.log(inProcess);
            if (this.error) {
              this.notificationService.show({
                content: this.error.message,
                animation: { type: 'slide', duration: 400 },
                position: { horizontal: 'right', vertical: 'bottom' },
                type: { style: 'error', icon: true },
                hideAfter: 2000,
              });
              console.log('Erro ocorrido: ' + JSON.stringify(this.error));
            }
            if (!inProcess && this.error == null) {
              this.notificationService.show({
                content: 'Produto incluído com sucesso!',
                animation: { type: 'slide', duration: 400 },
                position: { horizontal: 'right', vertical: 'bottom' },
                type: { style: 'success', icon: true },
                hideAfter: 2000,
              });
            }
          });
        }
      }
    } catch (e) {
      console.log(e);
    }
  }

  /* Funções para alterar quantidade dos itens existentes no carrinho */
  addQuantity(product: ShoppingItem) {
    const oldValue = product.quantity;
    let addQuantity = 1;
    if (product.mutiple !== 1) {
      addQuantity = product.mutiple;
    }
    const newValue = oldValue + addQuantity;
    this.stock$ = this.productService.getStocks(
      this.authService.getStore(),
      product.idProduct
    );
    this.subscriptionStock = this.stock$.subscribe((stocks) => {
      const stock = stocks.filter((s) => s.store === product.stockStore);
      if (
        stock[0].quantity >= Number.parseFloat(newValue.toFixed(3)) ||
        product.deliveryType !== 'EF'
      ) {
        this.quantityCart.value = newValue.toString();
        this.updateItem(product, newValue);
      } else {
        this.quantityCart.value = oldValue.toString();
        this.messageInformation = 'Produto sem estoque!';
        this.informationDescription =
          'Produto esta sem estoque disponível para atender o pedido na filial de retira selecionada.';
        this.showInformation = true;
      }
      console.log(this.quantityCart.value);
    });
  }

  minusQuantity(dataItem) {
    const oldValue = dataItem.quantity; // this.formQuantity.get('quantity').value;
    let addQuantity = 1;
    if (dataItem.mutiple !== 1) {
      addQuantity = dataItem.mutiple;
    }
    let newValue = oldValue - addQuantity;
    if (newValue < 0 || newValue < dataItem.mutiple) {
      newValue = dataItem.mutiple;
    }
    let updateItem: ShoppingItem;
    updateItem = JSON.parse(JSON.stringify(dataItem));
    updateItem.quantity = newValue;
    this.updateItem(updateItem, newValue);
  }

  /* Funções para alterar quantidade dos itens existentes no carrinho */
  updateQuantity(args: EditEvent) {
    // const oldValue = product.quantity;
    console.log(args);
    // console.log(this.quantityCart.value);
    /*const newValue = Number.parseFloat(this.quantityCart.value);
    this.stock$ = this.productService.getStocks(product.idProduct);
    this.subscriptionStock = this.stock$.subscribe(stocks => {
      const stock = stocks.filter(s => s.store === product.stockStore);
      if (stock[0].quantity >= newValue) {
        this.quantityCart.value = newValue.toString();
        this.updateItem(product, newValue);
      }
      else {
        this.quantityCart.value = oldValue.toString();
        this.messageInformation = 'Produto sem estoque!';
        this.informationDescription = 'Produto esta sem estoque disponível para atender o pedido na filial de retira selecionada.';
        this.showInformation = true;
      }
    }); */
  }

  public editHandler({
    sender,
    columnIndex,
    rowIndex,
    dataItem,
  }: CellClickEvent): void {
    this.editedRowIndex = rowIndex;
    console.log(dataItem);
  }

  public selectedBrand() {
    console.log(this.selectedBrandKeys.join(','));
    const selectBrands: string[] = [];
    this.selectedBrandKeys.forEach((key) => {
      const brand = this.brands[key];
      selectBrands.push(brand.description);
    });
    this.filters.brands = selectBrands;
    console.log(this.filters);
    this.getSaleProducts(this.filters);
  }

  public selectCategory(category: any) {
    console.log(category);
  }

  public loadMoreProducts(): void {
    const next = this.productsLoad.length;
    this.productsLoad = [
      ...this.productsLoad,
      ...this.products.slice(next, next + 20),
    ];
    console.log(this.productsLoad);
  }

  public showMessage(title: string, message: string) {
    this.dialogService.open({
      title,
      height: 220,
      content: message,
      actions: [{ text: 'OK' }],
    });
  }

  public confirmSale(offCanvasId: string) {
    this.router.navigate(['sales/cart']);
  }

  cancelSale() {
    this.messageConfirmation = 'Confirma cancelamento da venda?';
    this.showConfirmationCancelSale = true;
  }

  returnConfirmationCancel(confirmation: any) {
    if (confirmation) {
      this.shoppingService.cancelShopping();
      this.router.navigate(['/sales/menu']);
    } else {
      this.showConfirmationCancelSale = false;
    }
  }

  returnShowInformation() {
    this.showInformation = false;
  }

  logout() {
    this.shoppingService.cancelShopping();
    this.authService.logout();
  }

  editShoppingItem(item: ShoppingItem) {
    this.productService
      .getSaleProduct(this.authService.getStore(), item.idProduct)
      .subscribe((product) => {
        console.log(product);
        let resultProduct: any;
        const dialogRef: DialogRef = this.dialogService.open({
          content: ProductModalComponent,
        });
        const productInfo = dialogRef.content.instance as ProductModalComponent;
        productInfo.product = product;
        productInfo.shoppingItem = item;
        dialogRef.result.subscribe((result) => {
          if (result instanceof DialogCloseResult) {
            console.log('WindowCloseResult', result);
          } else {
            console.log('action', result);
            resultProduct = JSON.stringify(result);
            console.log(resultProduct);
            this.messageService.showMessage(JSON.parse(resultProduct).message);
          }
        });
      });
  }

  selectedStore(store: any) {
    this.filters.storeStock = store.id;
    console.log(store);
  }

  async showConfirmationCancelItem(item: ShoppingItem) {
    console.log(item);
    this.itemCancel = item;
    this.titleMessage = 'Pedido de venda';
    this.messageConfirmation = `Confirma a exclusão do item do pedido?`;
    this.textButtonConfirmation = 'Confirma';
    this.openedConfirmationCancelItem = true;
  }

  async returnConfirmationCancelItem(result: any) {
    this.openedConfirmationCancelItem = false;
    if (result && this.itemCancel != null) {
      this.store.dispatch(new DeleteItemAction(this.itemCancel.id));
      this.updating$.subscribe((update) => {
        if (!update) {
          this.store.dispatch(
            new LoadShoppingItemsAction(this.shoppingService.getCart())
          );
          this.store.dispatch(
            new LoadShoppingAction(this.shoppingService.getCart())
          );
          this.itemCancel = null;
        }
      });
    }
  }

  orderByProductChange(orderBySelect: OrderByProduct) {
    console.log(orderBySelect);
    this.filters.orderBy = orderBySelect.field;
    this.getFilterProducts();
  }
}
