import { Location } from '@angular/common';
import {
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnDestroy,
  OnInit,
  Output,
  QueryList,
  Renderer2,
  ViewChild,
  ViewChildren,
} from '@angular/core';
import {
  AbstractControl,
  FormBuilder,
  FormControl,
  FormGroup,
  ValidatorFn,
  Validators,
} from '@angular/forms';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import {
  DialogCloseResult,
  DialogRef,
  DialogService,
} from '@progress/kendo-angular-dialog';
import { CellClickEvent, GridComponent } from '@progress/kendo-angular-grid';
import { BadgeAlign, BadgePosition } from '@progress/kendo-angular-indicators';
import { NotificationService } from '@progress/kendo-angular-notification';
import { State } from '@progress/kendo-data-query';
import { Observable, Subscription } from 'rxjs';
import { map } from 'rxjs/operators';
import { AuthService } from 'src/app/auth/services/auth.service';
import { Customer } from 'src/app/models/customer.model';
import { LotProduct } from 'src/app/models/lot-product.model';
import { SaleProduct, Stock } from 'src/app/models/sale-product.model';
import { ProductService } from 'src/app/services/product.service';
import { ShoppingService } from 'src/app/services/shopping.service';
import { DataDeliveryComponent } from '../../components/data-delivery/data-delivery.component';
import { ProductModalComponent } from '../../components/product-modal/product-modal.component';
import {
  AddItemAction,
  DeleteItemAction,
  LoadShoppingAction,
  LoadShoppingItemsAction,
} from '../../store/actions/shopping.action';
import { SaleState } from '../../store/models/sale-state.model';
import { ShoppingItem } from '../../store/models/shopping-item';
import { MessageService } from './../../../services/messages.service';

@Component({
  selector: 'app-product-sale',
  templateUrl: './product-sale.component.html',
  styleUrls: ['./product-sale.component.scss'],
})
export class ProductSaleComponent implements OnInit, OnDestroy {
  constructor(
    private readonly authService: AuthService,
    public dialog: DialogRef,
    private fb: FormBuilder,
    public shoppingService: ShoppingService,
    private productService: ProductService,
    private store: Store<SaleState>,
    private formBuilder: FormBuilder,
    private renderer: Renderer2,
    private router: Router,
    private readonly dialogService: DialogService,
    private notificationService: NotificationService,
    private readonly messageService: MessageService,
    private location: Location
  ) {
    const navigation = this.router.getCurrentNavigation();
    this.product = navigation?.extras.state?.product;
  }

  ngOnDestroy(): void {
    if (this.subscriptionStock) {
      this.subscriptionStock.unsubscribe();
    }
    if (this.subscriptionItensShopping) {
      this.subscriptionItensShopping.unsubscribe();
    }
    if (this.subscriptionLotProduct) {
      this.subscriptionLotProduct.unsubscribe();
    }
    if (this.subscriptionByTogether) {
      this.subscriptionByTogether.unsubscribe();
    }
  }

  public userName: string;
  public storeName: string;

  product: SaleProduct;
  @Input() shoppingItem: ShoppingItem;

  @Output() public submitForm: EventEmitter<SaleProduct> = new EventEmitter();
  shoppingItens: ShoppingItem[] = [];
  shoppingItens$: Observable<ShoppingItem[]>;
  productsBuyTogether: SaleProduct[];
  productsSimilar: SaleProduct[];
  subscriptionStock: Subscription;
  subscriptionItensShopping: Subscription;
  subscriptionLotProduct: Subscription;
  subscriptionByTogether: Subscription;
  subscriptionSimilar: Subscription;
  subscriptionUpdate: Subscription;
  updatePrice = false;
  form: FormGroup;
  quantityOk = true;
  stockValid = true;
  listPrice: number;
  salePrice: number;
  loading$: Observable<boolean>;
  error$: Observable<Error>;
  stock$: Observable<Stock[]>;
  stocks: Stock[] = [];
  error: Error = null;
  showDescription = false;
  textShowMore = 'Ver mais';
  public data: any = {
    deliveryType: null,
    store: null,
    stockStore: null,
    quantity: 1,
  };

  public dataProductTogether: any = {
    deliveryType: null,
    store: null,
    stockStore: null,
    quantity: 1,
  };

  public dataProductSimilar: any = {
    deliveryType: null,
    store: null,
    stockStore: null,
    quantity: 1,
  };

  /* Cart Sale */
  shoppingItems$: Observable<ShoppingItem[]>;
  subscriptionShoppingItems: Subscription;
  shoppingItems: ShoppingItem[] = [];

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

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

  /* END Cart Sale */

  public createFormGroup = (dataItem) =>
    new FormGroup({
      Discontinued: new FormControl(dataItem.Discontinued),
      ProductID: new FormControl(dataItem.ProductID),
      ProductName: new FormControl(dataItem.ProductName, Validators.required),
      UnitPrice: new FormControl(dataItem.UnitPrice),
      UnitsInStock: new FormControl(
        dataItem.UnitsInStock,
        Validators.compose([
          Validators.required,
          Validators.pattern('^[0-9]{1,3}'),
        ])
      ),
    });

  public matches = (el, selector) =>
    (el.matches || el.msMatchesSelector).call(el, selector);

  public dataDelivery = [
    { type: 'RI', description: 'Retira imediata' },
    { type: 'EN', description: 'Entrega' },
    { type: 'RP', description: 'Retira posterior' },
    /*{ type: 'RA', description: 'Retira posterior (Imediata)' },*/
    { type: 'EF', description: 'Entrega futura' },
  ];

  /* Variaveis para mensagem */
  showInformation = false;
  titleInformation = 'Pedido de venda';
  messageInformation = '';
  informationDescription = '';

  public imageWidth = '100%';
  public imageHeight = '100%';

  /* edit Price */
  editPrice = false;
  @ViewChildren('inputPrice') inputPrice: QueryList<ElementRef>;
  @ViewChild(GridComponent)
  private grid: GridComponent;

  returnShowInformation() {
    this.showInformation = false;
  }
  /* FIM - Variaveis para mensagem */

  /* Controle para lotes do produto */
  showLotProduct = false;
  customerId = 0;
  lotProduct$: Observable<LotProduct[]>;
  lotProduct: LotProduct[];
  //  public view: Observable<GridDataResult>;

  returnShowLotProduct() {
    this.showLotProduct = false;
  }
  public gridState: State = {
    sort: [],
    skip: 0,
    take: 5,
  };

  public changes = {};

  public view: any[];

  public formGroup: FormGroup;
  public formProductTogether: FormGroup;
  public formProductSimilar: FormGroup;

  private editedRowIndex: number;
  private docClickSubscription: Subscription = new Subscription();
  private isNew: boolean;

  /* FIM - Controle para lotes do produto */

  /* produtos compre junto */
  loading = false;
  updating$: Observable<boolean>;
  images: string[] = [];
  openProductTogether = false;
  openProductSimilar = false;
  productTogether: SaleProduct;
  stockProductTogether$: Observable<Stock[]>;
  quantityStockProductTogether: number;
  stockProductSimilar$: Observable<Stock[]>;
  quantityStockProductSimilar: number;
  productSimilar: SaleProduct;
  public windowWidth = 850;
  public windowHeight = 695;

  ngOnInit() {
    this.userName = this.authService.getUserName();
    this.storeName = this.authService.getStoreName();

    this.docClickSubscription.add(
      this.renderer.listen('document', 'click', this.onDocumentClick.bind(this))
    );

    this.shoppingItens$ = this.store.select((store) => store.shopping.list);
    this.subscriptionItensShopping = this.shoppingItens$.subscribe(
      (itens) => (this.shoppingItens = itens)
    );

    this.form = this.fb.group({
      quantity: new FormControl(
        this.shoppingItem != null
          ? this.shoppingItem.quantity
          : this.product.mutiple.toFixed(2),
        []
      ),
      salePrice: new FormControl(
        this.shoppingItem != null
          ? this.shoppingItem.price
          : this.product.salePrice,
        []
      ),
      store: new FormControl(
        this.shoppingItem != null
          ? this.shoppingItem.stockStore
          : this.authService.getStore(),
        []
      ),
      deliveryType: new FormControl(
        this.shoppingItem != null ? this.shoppingItem.deliveryType : '',
        []
      ),
      price: new FormControl(
        this.shoppingItem != null
          ? this.shoppingItem.price
          : this.product.salePrice,
        []
      ),
      description: new FormControl(
        this.shoppingItem != null ? this.shoppingItem.auxDescription : '',
        []
      ),
      addUpQuantity: new FormControl(
        this.shoppingItem != null
          ? this.shoppingItem.percentUpQuantity > 0
          : false,
        []
      ),
      originalQuantity: new FormControl(
        this.shoppingItem != null ? this.shoppingItem.upQuantity : 0,
        []
      ),
      environment: new FormControl(
        this.shoppingItem != null ? this.shoppingItem.environment : '',
        []
      ),
    });

    this.listPrice =
      this.shoppingItem != null
        ? this.shoppingItem.listPrice
        : this.product.listPrice;
    this.salePrice =
      this.shoppingItem != null
        ? this.shoppingItem.price
        : this.product.salePrice;
    this.form.valueChanges.subscribe((_) => {
      const oldValue = this.form.get('quantity').value;
      this.quantityOk = Number.parseFloat(oldValue) <= this.product.stock;
    });

    /* Data Sale */
    this.userName = this.authService.getUserName();
    this.storeName = this.authService.getStoreName();

    let idCart = this.shoppingService.getCart();

    //    this.shopping$ = this.store.select(store => store.shopping.shopping);
    this.shoppingItems$ = this.store.select((store) => store.shopping.list);
    this.store.dispatch(new LoadShoppingItemsAction(idCart));
    this.store.dispatch(new LoadShoppingAction(idCart));
    this.store.dispatch(new LoadShoppingItemsAction(idCart));
    this.shoppingItems$.subscribe((data) => {
      this.shoppingItems = JSON.parse(JSON.stringify(data));
      console.log(this.shoppingItems);
    });
    /* END Data Sale */

    /* form product together */
    this.formProductTogether = this.fb.group({
      quantity: new FormControl(null, []),
      salePrice: new FormControl(null, []),
      store: new FormControl(
        this.shoppingItem != null
          ? this.shoppingItem.stockStore
          : this.authService.getStore(),
        [this.estoqueDisponivelValidator()]
      ),
      deliveryType: new FormControl(
        this.shoppingItem != null ? this.shoppingItem.deliveryType : '',
        []
      ),
      price: new FormControl(null, [this.priceValidator()]),
      addUpQuantity: new FormControl(null, []),
      originalQuantity: new FormControl(null, []),
    });

    /* form product similar */
    this.formProductSimilar = this.fb.group({
      quantity: new FormControl(null, []),
      salePrice: new FormControl(null, []),
      store: new FormControl(
        this.shoppingItem != null
          ? this.shoppingItem.stockStore
          : this.authService.getStore(),
        [this.estoqueDisponivelValidatorSimilar()]
      ),
      deliveryType: new FormControl(
        this.shoppingItem != null ? this.shoppingItem.deliveryType : '',
        []
      ),
      price: new FormControl(null, [this.priceValidatorSimilar()]),
      addUpQuantity: new FormControl(null, []),
      originalQuantity: new FormControl(null, []),
    });

    this.loading$ = this.store.select((store) => store.shopping.loading);
    this.error$ = this.store.select((store) => store.shopping.error);
    this.error$.subscribe((error) => {
      this.error = error;
    });
    this.stock$ = this.productService.getStocks(
      this.authService.getStore(),
      this.product.idProduct
    );
    this.stock$.subscribe((stocks) => {
      this.stocks = stocks;
    });
    const customer: Customer = JSON.parse(localStorage.getItem('customer'));
    this.customerId = customer !== null ? customer.customerId : 1;

    this.lotProduct$ = this.shoppingService.getLotProduct(
      this.product.idProduct,
      this.customerId
    );
    this.subscriptionLotProduct = this.shoppingService
      .getLotProduct(this.product.idProduct, this.customerId)
      .subscribe((lotes) => {
        console.log(JSON.stringify(lotes));
        this.shoppingService.setListLotProduct(lotes);
      });

    const storeSeller = this.authService.getStore();

    this.subscriptionByTogether = this.productService
      .getProductsBuyTogether(this.product.idProduct, storeSeller)
      .subscribe((data) => {
        this.productsBuyTogether = data;
      });

    this.subscriptionSimilar = this.productService
      .getProductSimilar(this.product.idProduct, storeSeller)
      .subscribe((data) => {
        this.productsSimilar = data;
      });
  }

  goBack(): void {
    this.location.back();
  }

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

  onDialogClose() {
    this.dialog.close();
  }

  isShowDescription() {
    this.showDescription = !this.showDescription;
    this.textShowMore = this.showDescription ? 'Ver menos' : 'Ver mais';
  }

  calcBoxProduct(product: SaleProduct) {
    const quantityProduct = Number.parseFloat(this.form.get('quantity').value);
    let boxQuantity = quantityProduct / product.mutiple;
    if (boxQuantity - Number.parseFloat(boxQuantity.toFixed()) > 0.01) {
      boxQuantity += 1;
    }
    return boxQuantity.toFixed();
  }

  addQuantity(product: SaleProduct) {
    const oldValue = this.form.get('quantity').value;
    let addQuantity = 1;
    if (product.mutiple !== 1) {
      addQuantity = product.mutiple;
    }
    let newValue = Number.parseFloat(oldValue) + addQuantity;
    if (newValue > product.stock) {
      newValue = oldValue;
    }
    newValue = Number.parseFloat(newValue.toFixed(3));
    this.form.patchValue({ quantity: newValue });
  }

  minusQuantity(product: SaleProduct) {
    const oldValue = this.form.get('quantity').value;
    let addQuantity = 1;
    if (product.mutiple !== 1) {
      addQuantity = product.mutiple;
    }
    let newValue = Number.parseFloat(oldValue) - addQuantity;
    if (newValue < 0 || newValue < product.mutiple) {
      newValue = product.mutiple;
    }
    newValue = Number.parseFloat(newValue.toFixed(3));
    this.form.patchValue({ quantity: newValue });
  }

  openLotProduct() {
    this.shoppingService
      .getListLotProduct()
      .subscribe((data) => (this.view = data));
    this.shoppingService
      .getListLotProduct()
      .subscribe((lotes) => (this.lotProduct = lotes));
    this.showLotProduct = true;
  }

  editingPrice() {
    this.editPrice = !this.editPrice;
    if (!this.editPrice) {
      this.form.patchValue({
        price: this.product.salePrice,
      });
    }
  }

  confirmPrice() {
    const newPrice = Number.parseFloat(this.form.get('price').value);
    let listPrice = this.product.listPrice;
    if (this.product.salePromotion > 0) {
      listPrice = this.product.salePromotion;
    }

    if (newPrice < listPrice) {
      this.form.patchValue({
        price:
          this.shoppingItem != null
            ? this.shoppingItem.price
            : this.product.salePrice,
      });
      this.messageInformation = 'Preço menor que o preço de tabela!';
      this.informationDescription =
        'Preço informado é menor que o preço de tabela, em caso de desconto utilize a função de desconto por item ou pedido.';
      this.showInformation = true;
      return;
    }
    this.salePrice = newPrice;
    this.editPrice = !this.editPrice;
    this.updatePrice = true;
  }

  addQuantityM2() {
    console.log('Adicionar 10%: ' + this.form.get('addUpQuantity').value);
    const isAddPercentQuantity = !(this.form.get('addUpQuantity')
      .value as boolean);
    if (isAddPercentQuantity) {
      const quantityProduct = Number.parseFloat(
        this.form.get('quantity').value
      );
      const quantity = Number.parseFloat((quantityProduct * 0.1).toFixed(3));
      let newQuantity = quantityProduct + quantity;
      if (this.product.mutiple > 1) {
        newQuantity =
          Number.parseFloat((newQuantity / this.product.mutiple).toFixed()) *
          this.product.mutiple;
        if (newQuantity < quantityProduct + quantity) {
          newQuantity += this.product.mutiple;
        }
      }
      newQuantity = Number.parseFloat(newQuantity.toFixed(3));
      this.form.patchValue({
        quantity: newQuantity.toFixed(3),
        originalQuantity: quantityProduct.toFixed(3),
        addUpQuantity: newQuantity - quantityProduct,
      });
    } else {
      const quantityProduct = Number.parseFloat(
        this.form.get('quantity').value
      );
      const quantity = Number.parseFloat((quantityProduct / 1.1).toFixed(3));
      let newQuantity = quantity;
      if (this.product.mutiple > 1) {
        newQuantity =
          Number.parseInt((newQuantity / this.product.mutiple).toFixed(3), 10) *
          this.product.mutiple;
      }
      console.log(newQuantity);
      this.form.patchValue({
        quantity: newQuantity.toFixed(2),
        originalQuantity: newQuantity.toFixed(2),
        addUpQuantity: 0,
      });
    }
  }

  async addProductCard(product: any) {
    const idCart = this.shoppingService.getCart();
    const quantity = this.form.get('quantity').value;
    let quantityBox = Math.trunc(quantity / product.mutiple);
    const quantityArred = quantityBox * Number.parseFloat(product.mutiple);
    if (quantityArred < quantity) {
      quantityBox = quantityBox + 1;
    }
    const quantitySale = quantityBox * product.mutiple;
    const descriptionAux = this.form.get('description').value;
    const deliveryType = this.form.get('deliveryType').value;
    const store = this.form.get('store').value;
    console.log('filial selecionada:' + store);
    const environment = this.form.get('environment').value;
    let price = this.product.listPrice; // Number.parseFloat(this.form.get('price').value);
    //  if (product.base === 'S') {
    if (this.product.salePromotion > 0) {
      price = this.product.salePromotion;
    }
    const newPrice = Number.parseFloat(this.form.get('price').value);
    console.log(
      `Preço de tabela: ${price} - Novo Preço: ${newPrice} - Promocional: ${this.product.offPercent}`
    );
    if (this.updatePrice && newPrice < price) {
      this.messageInformation = 'Preço de venda inválido!';
      this.informationDescription =
        'Preço informado não pode ser inferior ao preço de tabela!';
      this.showInformation = true;
      return;
    }
    price = newPrice;

    if (
      deliveryType === null ||
      deliveryType === '' ||
      deliveryType === undefined
    ) {
      this.messageInformation = 'Não foi informado o tipo de entrega!';
      this.informationDescription =
        'Para incluir o item selecione um tipo de entrega para o produto!';
      this.showInformation = true;
      return;
    }

    /* Validação filial venda x filial estoque */
    const stockSelected = this.stocks.filter((s) => s.store == store);
    if (
      stockSelected[0].allowDelivery == 0 &&
      (deliveryType == 'EN' || deliveryType == 'EF')
    ) {
      this.messageInformation =
        'Filial de estoque não realiza entrega para esta loja!';
      this.informationDescription =
        'A filial de estoque selecionada não realiza entrega para esta loja!';
      this.showInformation = true;
      return;
    }

    const initialValue = 0;
    let stockCart = this.shoppingItens
      .filter(
        (i) => i.idProduct === product.idProduct && i.stockStore === store
      )
      .reduce(
        (previousValue, item) => previousValue + item.quantity,
        initialValue
      );
    if (this.shoppingItem !== undefined && this.shoppingItem !== null) {
      stockCart = stockCart - this.shoppingItem.quantity;
    }
    this.subscriptionStock = this.productService
      .validateStock(
        product.idProduct,
        deliveryType,
        store,
        quantitySale + stockCart
      )
      .pipe(
        map((stockValid) => {
          if (stockValid) {
            try {
              this.error = null;
              const id =
                this.shoppingItem != null ? this.shoppingItem.id : null;
              const sellerId =
                this.shoppingItem != null
                  ? this.shoppingItem.seller
                  : this.authService.getSeller();
              const discount =
                this.shoppingItem != null ? this.shoppingItem.discount : null;
              const discountValue =
                this.shoppingItem != null
                  ? this.shoppingItem.discountValue
                  : null;
              const userDiscount =
                this.shoppingItem != null
                  ? this.shoppingItem.userDiscount
                  : null;
              const cost =
                this.shoppingItem != null ? this.shoppingItem.cost : null;
              this.store.dispatch(
                new AddItemAction({
                  id,
                  idCart,
                  invoiceStore: this.authService.getStore(),
                  idProduct: product.idProduct,
                  description: product.title,
                  image: product.images[0],
                  productType: product.productType,
                  quantity: quantitySale,
                  price,
                  deliveryType,
                  cost: cost,
                  stockStore: store,
                  seller: sellerId,
                  percentUpQuantity: 0,
                  upQuantity: 0,
                  discount,
                  discountValue,
                  ean: product.ean,
                  promotion: product.offPercent > 0 ? product.salePrice : 0,
                  listPrice: price,
                  userDiscount,
                  mutiple: product.mutiple,
                  auxDescription: descriptionAux,
                  smallDescription: product.smallDescription,
                  brand: product.brand,
                  base: product.base,
                  letter: product.letter,
                  line: product.line,
                  color: product.color,
                  can: product.can,
                  environment: environment,
                })
              );

              this.loading$.subscribe((inProcess) => {
                console.log(inProcess);
                if (this.error) {
                  this.dialog.close({
                    success: false,
                    message: this.error.message,
                  });
                  console.log('Erro ocorrido: ' + JSON.stringify(this.error));
                }
                if (!inProcess && this.error == null) {
                  this.messageInformation = 'Produto incluído com sucesso!';
                  this.informationDescription = '';
                  if (this.productsBuyTogether.length > 0) {
                    this.informationDescription =
                      'ATENÇÃO! Produto com itens compre junto!';
                  }
                  this.showInformation = true;
                }
              });
            } catch (e) {
              console.log(e);
            }
          } else {
            // mostrar mensagem de falta de estoque
            this.messageInformation = 'Produto sem estoque disponível!';
            this.informationDescription =
              'Verifique a disponibilidade do produto em outras filiais de estoque.';
            this.showInformation = true;
          }
        })
      )
      .subscribe();
  }

  public cellClickHandler({
    isEdited,
    dataItem,
    rowIndex,
  }: CellClickEvent): void {
    if (isEdited || (this.formGroup && !this.formGroup.valid)) {
      return;
    }

    if (this.isNew) {
      rowIndex += 1;
    }

    this.saveCurrent();

    this.formGroup = this.createFormGroup(dataItem);
    this.editedRowIndex = rowIndex;

    this.grid.editRow(rowIndex, this.formGroup);
  }

  private saveCurrent(): void {
    if (this.formGroup) {
      this.save(this.formGroup.value);
      this.closeEditor();
    }
  }

  private closeEditor(): void {
    this.grid.closeRow(this.editedRowIndex);

    this.isNew = false;
    this.editedRowIndex = undefined;
    this.formGroup = undefined;
  }

  public save(dataLotproduct: LotProduct): void {
    Object.assign(
      this.lotProduct.find(
        ({ lotProduct }) => lotProduct === dataLotproduct.lotProduct
      ),
      this.lotProduct
    );
  }

  public saveRow(): void {
    if (this.formGroup && this.formGroup.valid) {
      this.saveCurrent();
    }
  }

  public cancelHandler(): void {
    this.closeEditor();
  }

  private onDocumentClick(e: Event): void {
    if (
      this.formGroup &&
      this.formGroup.valid &&
      !this.matches(
        e.target,
        '#productsGrid tbody *, #productsGrid .k-grid-toolbar .k-button'
      )
    ) {
      this.saveCurrent();
    }
  }

  //functions for products together

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

  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.addItemProductTogether(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);
    }
  }

  async addProductCardProductSimilar(productSimilar: any) {
    const idCart = this.shoppingService.getCart();
    const quantity = this.formProductSimilar.get('quantity').value;
    let quantityBox = Math.trunc(quantity / productSimilar.mutiple);
    const quantityArred =
      quantityBox * Number.parseFloat(productSimilar.mutiple);
    if (quantityArred < quantity) {
      quantityBox = quantityBox + 1;
    }
    const quantitySale = quantityBox * productSimilar.mutiple;
    const descriptionAux = '';
    const deliveryType = this.formProductSimilar.get('deliveryType').value;
    const store = this.formProductSimilar.get('store').value;
    const environment = this.form.get('environment').value;
    let price = productSimilar.listPrice;
    if (productSimilar.salePromotion > 0) {
      price = productSimilar.salePromotion;
    }
    const newPrice = Number.parseFloat(
      this.formProductSimilar.get('price').value
    );
    console.log(
      `Preço de tabela: ${price} - Novo Preço: ${newPrice} - Promocional: ${this.product.offPercent}`
    );
    if (this.updatePrice && newPrice < price) {
      this.messageInformation = 'Preço de venda inválido!';
      this.informationDescription =
        'Preço informado não pode ser inferior ao preço de tabela!';
      this.showInformation = true;
      return;
    }
    price = newPrice;

    if (
      deliveryType === null ||
      deliveryType === '' ||
      deliveryType === undefined
    ) {
      this.messageInformation = 'Não foi informado o tipo de entrega!';
      this.informationDescription =
        'Para incluir o item selecione um tipo de entrega para o produto!';
      this.showInformation = true;
      return;
    }

    const initialValue = 0;
    let shoppingProductSimilar = this.shoppingItens.filter(
      (i) => i.idProduct === productSimilar.idProduct && i.stockStore === store
    );
    let itemSaleProductSimilar: ShoppingItem;
    if (shoppingProductSimilar.length > 0) {
      itemSaleProductSimilar = shoppingProductSimilar[0];
    }
    let stockCart = this.shoppingItens
      .filter(
        (i) =>
          i.idProduct === productSimilar.idProduct && i.stockStore === store
      )
      .reduce(
        (previousValue, item) => previousValue + item.quantity,
        initialValue
      );
    if (
      itemSaleProductSimilar !== undefined &&
      itemSaleProductSimilar !== null
    ) {
      stockCart = stockCart - itemSaleProductSimilar.quantity;
    }
    this.subscriptionStock = this.productService
      .validateStock(
        productSimilar.idProduct,
        deliveryType,
        store,
        quantitySale + stockCart
      )
      .pipe(
        map((stockValid) => {
          if (stockValid) {
            try {
              this.error = null;
              const id =
                itemSaleProductSimilar != null
                  ? itemSaleProductSimilar.id
                  : null;
              const sellerId =
                itemSaleProductSimilar != null
                  ? itemSaleProductSimilar.seller
                  : this.authService.getSeller();
              const discount =
                itemSaleProductSimilar != null
                  ? itemSaleProductSimilar.discount
                  : null;
              const discountValue =
                itemSaleProductSimilar != null
                  ? itemSaleProductSimilar.discountValue
                  : null;
              const userDiscount =
                itemSaleProductSimilar != null
                  ? itemSaleProductSimilar.userDiscount
                  : null;
              const cost =
                itemSaleProductSimilar != null
                  ? itemSaleProductSimilar.cost
                  : null;
              this.store.dispatch(
                new AddItemAction({
                  id,
                  idCart,
                  invoiceStore: this.authService.getStore(),
                  idProduct: productSimilar.idProduct,
                  description: productSimilar.title,
                  image: productSimilar.images[0],
                  productType: productSimilar.productType,
                  quantity: quantitySale,
                  price,
                  deliveryType,
                  cost: cost,
                  stockStore: store,
                  seller: sellerId,
                  percentUpQuantity: 0,
                  upQuantity: 0,
                  discount,
                  discountValue,
                  ean: productSimilar.ean,
                  promotion:
                    productSimilar.offPercent > 0
                      ? productSimilar.salePrice
                      : 0,
                  listPrice: price,
                  userDiscount,
                  mutiple: productSimilar.mutiple,
                  auxDescription: descriptionAux,
                  smallDescription: productSimilar.smallDescription,
                  brand: productSimilar.brand,
                  base: productSimilar.base,
                  letter: productSimilar.letter,
                  line: productSimilar.line,
                  color: productSimilar.color,
                  can: productSimilar.can,
                  environment: environment,
                })
              );

              this.loading$.subscribe((inProcess) => {
                console.log(inProcess);
                if (this.error) {
                  this.dialog.close({
                    success: false,
                    message: this.error.message,
                  });
                  console.log('Erro ocorrido: ' + JSON.stringify(this.error));
                }
                if (!inProcess && this.error == null) {
                  this.messageInformation = 'Produto incluído com sucesso!';
                  this.informationDescription = '';
                  this.openCloseProductSimilar(null, false);
                  this.showInformation = true;
                }
              });
            } catch (e) {
              console.log(e);
            }
          } else {
            // mostrar mensagem de falta de estoque
            this.messageInformation = 'Produto sem estoque disponível!';
            this.informationDescription =
              'Verifique a disponibilidade do produto em outras filiais de estoque.';
            this.showInformation = true;
          }
        })
      )
      .subscribe();
  }

  async addProductCardProductTogether(productTogether: any) {
    const idCart = this.shoppingService.getCart();
    const quantity = this.formProductTogether.get('quantity').value;
    let quantityBox = Math.trunc(quantity / productTogether.mutiple);
    const quantityArred =
      quantityBox * Number.parseFloat(productTogether.mutiple);
    if (quantityArred < quantity) {
      quantityBox = quantityBox + 1;
    }
    const quantitySale = quantityBox * productTogether.mutiple;
    const descriptionAux = '';
    const deliveryType = this.formProductTogether.get('deliveryType').value;
    const store = this.formProductTogether.get('store').value;
    const environment = this.form.get('environment').value;
    let price = productTogether.listPrice; // Number.parseFloat(this.form.get('price').value);
    //  if (product.base === 'S') {
    if (productTogether.salePromotion > 0) {
      price = productTogether.salePromotion;
    }
    const newPrice = Number.parseFloat(
      this.formProductTogether.get('price').value
    );
    console.log(
      `Preço de tabela: ${price} - Novo Preço: ${newPrice} - Promocional: ${this.product.offPercent}`
    );
    if (this.updatePrice && newPrice < price) {
      this.messageInformation = 'Preço de venda inválido!';
      this.informationDescription =
        'Preço informado não pode ser inferior ao preço de tabela!';
      this.showInformation = true;
      return;
    }
    price = newPrice;

    if (
      deliveryType === null ||
      deliveryType === '' ||
      deliveryType === undefined
    ) {
      this.messageInformation = 'Não foi informado o tipo de entrega!';
      this.informationDescription =
        'Para incluir o item selecione um tipo de entrega para o produto!';
      this.showInformation = true;
      return;
    }

    const initialValue = 0;
    let shoppingProductTogether = this.shoppingItens.filter(
      (i) => i.idProduct === productTogether.idProduct && i.stockStore === store
    );
    let itemSaleProductTogether: ShoppingItem;
    if (shoppingProductTogether.length > 0) {
      itemSaleProductTogether = shoppingProductTogether[0];
    }
    let stockCart = this.shoppingItens
      .filter(
        (i) =>
          i.idProduct === productTogether.idProduct && i.stockStore === store
      )
      .reduce(
        (previousValue, item) => previousValue + item.quantity,
        initialValue
      );
    if (
      itemSaleProductTogether !== undefined &&
      itemSaleProductTogether !== null
    ) {
      stockCart = stockCart - itemSaleProductTogether.quantity;
    }
    this.subscriptionStock = this.productService
      .validateStock(
        productTogether.idProduct,
        deliveryType,
        store,
        quantitySale + stockCart
      )
      .pipe(
        map((stockValid) => {
          if (stockValid) {
            try {
              this.error = null;
              const id =
                itemSaleProductTogether != null
                  ? itemSaleProductTogether.id
                  : null;
              const sellerId =
                itemSaleProductTogether != null
                  ? itemSaleProductTogether.seller
                  : this.authService.getSeller();
              const discount =
                itemSaleProductTogether != null
                  ? itemSaleProductTogether.discount
                  : null;
              const discountValue =
                itemSaleProductTogether != null
                  ? itemSaleProductTogether.discountValue
                  : null;
              const userDiscount =
                itemSaleProductTogether != null
                  ? itemSaleProductTogether.userDiscount
                  : null;
              const cost =
                itemSaleProductTogether != null
                  ? itemSaleProductTogether.cost
                  : null;
              this.store.dispatch(
                new AddItemAction({
                  id,
                  idCart,
                  invoiceStore: this.authService.getStore(),
                  idProduct: productTogether.idProduct,
                  description: productTogether.title,
                  image: productTogether.images[0],
                  productType: productTogether.productType,
                  quantity: quantitySale,
                  price,
                  deliveryType,
                  cost: cost,
                  stockStore: store,
                  seller: sellerId,
                  percentUpQuantity: 0,
                  upQuantity: 0,
                  discount,
                  discountValue,
                  ean: productTogether.ean,
                  promotion:
                    productTogether.offPercent > 0
                      ? productTogether.salePrice
                      : 0,
                  listPrice: price,
                  userDiscount,
                  mutiple: productTogether.mutiple,
                  auxDescription: descriptionAux,
                  smallDescription: productTogether.smallDescription,
                  brand: productTogether.brand,
                  base: productTogether.base,
                  letter: productTogether.letter,
                  line: productTogether.line,
                  color: productTogether.color,
                  can: productTogether.can,
                  environment: environment,
                  productTogether: 'S',
                })
              );

              this.loading$.subscribe((inProcess) => {
                console.log(inProcess);
                if (this.error) {
                  this.dialog.close({
                    success: false,
                    message: this.error.message,
                  });
                  console.log('Erro ocorrido: ' + JSON.stringify(this.error));
                }
                if (!inProcess && this.error == null) {
                  this.messageInformation = 'Produto incluído com sucesso!';
                  this.informationDescription = '';
                  this.openCloseProductTogether(null, false);
                  this.showInformation = true;
                }
              });
            } catch (e) {
              console.log(e);
            }
          } else {
            // mostrar mensagem de falta de estoque
            this.messageInformation = 'Produto sem estoque disponível!';
            this.informationDescription =
              'Verifique a disponibilidade do produto em outras filiais de estoque.';
            this.showInformation = true;
          }
        })
      )
      .subscribe();
  }

  addItemProductTogether(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,
        productTogether: 'S',
      })
    );
    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();
        }
      });
    }
  }

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

  public openCloseProductTogether(
    productTogether: SaleProduct,
    isOpened: boolean
  ): void {
    if (!isOpened) {
      this.openProductTogether = false;
      this.productTogether = null; // Limpa o objeto ao fechar
      return;
    }

    this.productTogether = productTogether;
    this.stockProductTogether$ = this.productService.getStocks(
      this.authService.getStore(),
      this.productTogether.idProduct
    );
    this.formProductTogether.patchValue({
      quantity:
        productTogether != null ? productTogether.mutiple.toFixed(2) : 1,
      store: this.form.get('store').value,
      salePrice:
        productTogether != null
          ? productTogether.salePrice
          : this.product.salePrice,
      deliveryType:
        this.shoppingItem != null ? this.shoppingItem.deliveryType : '',
      price:
        productTogether != null
          ? productTogether.salePrice
          : this.product.salePrice,
      originalQuantity: productTogether != null ? productTogether.quantity : 0,
    });
    this.openProductTogether = isOpened;
  }

  public openCloseProductSimilar(
    productSimilar: SaleProduct,
    isOpened: boolean
  ): void {
    if (!isOpened) {
      this.openProductSimilar = false;
      this.productSimilar = null; // Limpa o objeto ao fechar
      return;
    }

    this.productSimilar = productSimilar;
    this.stockProductSimilar$ = this.productService.getStocks(
      this.authService.getStore(),
      this.productSimilar.idProduct
    );
    this.formProductSimilar.patchValue({
      quantity: productSimilar != null ? productSimilar.mutiple.toFixed(2) : 1,
      store: this.form.get('store').value,
      salePrice:
        productSimilar != null
          ? productSimilar.salePrice
          : this.product.salePrice,
      deliveryType:
        this.shoppingItem != null ? this.shoppingItem.deliveryType : '',
      price:
        productSimilar != null
          ? productSimilar.salePrice
          : this.product.salePrice,
      originalQuantity: productSimilar != null ? productSimilar.quantity : 0,
    });
    this.openProductSimilar = isOpened;
  }

  addQuantityProductTogether(productTogether: SaleProduct) {
    const oldValue = this.formProductTogether.get('quantity').value;
    let addQuantity = 1;
    if (productTogether.mutiple !== 1) {
      addQuantity = productTogether.mutiple;
    }
    let newValue = Number.parseFloat(oldValue) + addQuantity;
    if (newValue > productTogether.stock) {
      newValue = oldValue;
    }
    newValue = Number.parseFloat(newValue.toFixed(3));
    this.formProductTogether.patchValue({ quantity: newValue });
    this.formProductTogether.get('store').updateValueAndValidity();
  }

  minusQuantityProductTogether(productTogether: SaleProduct) {
    const oldValue = this.formProductTogether.get('quantity').value;
    let addQuantity = 1;
    if (productTogether.mutiple !== 1) {
      addQuantity = productTogether.mutiple;
    }
    let newValue = Number.parseFloat(oldValue) - addQuantity;
    if (newValue < 0 || newValue < productTogether.mutiple) {
      newValue = productTogether.mutiple;
    }
    newValue = Number.parseFloat(newValue.toFixed(3));
    this.formProductTogether.patchValue({ quantity: newValue });
    this.formProductTogether.get('store').updateValueAndValidity();
  }

  addQuantityProductSimilar(productSimilar: SaleProduct) {
    const oldValue = this.formProductSimilar.get('quantity').value;
    let addQuantity = 1;
    if (productSimilar.mutiple !== 1) {
      addQuantity = productSimilar.mutiple;
    }
    let newValue = Number.parseFloat(oldValue) + addQuantity;
    if (newValue > productSimilar.stock) {
      newValue = oldValue;
    }
    newValue = Number.parseFloat(newValue.toFixed(3));
    this.formProductSimilar.patchValue({ quantity: newValue });
    this.formProductSimilar.get('store').updateValueAndValidity();
  }

  minusQuantityProductSimilar(productSimilar: SaleProduct) {
    const oldValue = this.formProductSimilar.get('quantity').value;
    let addQuantity = 1;
    if (productSimilar.mutiple !== 1) {
      addQuantity = productSimilar.mutiple;
    }
    let newValue = Number.parseFloat(oldValue) - addQuantity;
    if (newValue < 0 || newValue < productSimilar.mutiple) {
      newValue = productSimilar.mutiple;
    }
    newValue = Number.parseFloat(newValue.toFixed(3));
    this.formProductSimilar.patchValue({ quantity: newValue });
    this.formProductSimilar.get('store').updateValueAndValidity();
  }

  calcBoxProductProductTogether(productTogether: SaleProduct) {
    const quantityProduct = Number.parseFloat(
      this.formProductTogether.get('quantity').value
    );
    let boxQuantity = quantityProduct / productTogether.mutiple;
    if (boxQuantity - Number.parseFloat(boxQuantity.toFixed()) > 0.01) {
      boxQuantity += 1;
    }
    return boxQuantity.toFixed();
  }

  calcBoxProductProductSimilar(productSimilar: SaleProduct) {
    const quantityProduct = Number.parseFloat(
      this.formProductSimilar.get('quantity').value
    );
    let boxQuantity = quantityProduct / productSimilar.mutiple;
    if (boxQuantity - Number.parseFloat(boxQuantity.toFixed()) > 0.01) {
      boxQuantity += 1;
    }
    return boxQuantity.toFixed();
  }

  editingPriceProductTogether() {
    this.editPrice = !this.editPrice;
    if (!this.editPrice) {
      this.formProductTogether.patchValue({
        price: this.productTogether.salePrice,
      });
    }
  }

  confirmPriceProductTogether(itemTogether: SaleProduct) {
    const newPrice = Number.parseFloat(
      this.formProductTogether.get('price').value
    );
    let listPrice = itemTogether.listPrice;
    console.log('Preco atual: ' + listPrice);
    console.log('Novo Preco: ' + newPrice);
    if (itemTogether.salePromotion > 0) {
      listPrice = itemTogether.salePromotion;
    }

    if (newPrice < listPrice) {
      this.formProductTogether.patchValue({ price: listPrice });
      this.messageInformation = 'Preço menor que o preço de tabela!';
      this.informationDescription =
        'Preço informado é menor que o preço de tabela, em caso de desconto utilize a função de desconto por item ou pedido.';
      this.showInformation = true;
      return;
    }
    this.salePrice = newPrice;
    this.editPrice = !this.editPrice;
    this.updatePrice = true;
    this.formProductTogether.patchValue({ price: newPrice });
  }

  editingPriceProductSimilar() {
    this.editPrice = !this.editPrice;
    if (!this.editPrice) {
      this.formProductSimilar.patchValue({
        price: this.productSimilar.salePrice,
      });
    }
  }

  confirmPriceProductSimilar(itemSimilar: SaleProduct) {
    const newPrice = Number.parseFloat(
      this.formProductSimilar.get('price').value
    );
    let listPrice = itemSimilar.listPrice;
    console.log('Preco atual: ' + listPrice);
    console.log('Novo Preco: ' + newPrice);
    if (itemSimilar.salePromotion > 0) {
      listPrice = itemSimilar.salePromotion;
    }

    if (newPrice < listPrice) {
      this.formProductSimilar.patchValue({ price: listPrice });
      this.messageInformation = 'Preço menor que o preço de tabela!';
      this.informationDescription =
        'Preço informado é menor que o preço de tabela, em caso de desconto utilize a função de desconto por item ou pedido.';
      this.showInformation = true;
      return;
    }
    this.salePrice = newPrice;
    this.editPrice = !this.editPrice;
    this.updatePrice = true;
    this.formProductSimilar.patchValue({ price: newPrice });
  }

  addQuantityM2ProductTogether() {
    console.log(
      'Adicionar 10%: ' + this.formProductTogether.get('addUpQuantity').value
    );
    const isAddPercentQuantity = !(this.formProductTogether.get('addUpQuantity')
      .value as boolean);
    if (isAddPercentQuantity) {
      const quantityProduct = Number.parseFloat(
        this.formProductTogether.get('quantity').value
      );
      const quantity = Number.parseFloat((quantityProduct * 0.1).toFixed(3));
      let newQuantity = quantityProduct + quantity;
      if (this.productTogether.mutiple > 1) {
        newQuantity =
          Number.parseFloat(
            (newQuantity / this.productTogether.mutiple).toFixed()
          ) * this.productTogether.mutiple;
        if (newQuantity < quantityProduct + quantity) {
          newQuantity += this.productTogether.mutiple;
        }
      }
      newQuantity = Number.parseFloat(newQuantity.toFixed(3));
      this.formProductTogether.patchValue({
        quantity: newQuantity.toFixed(3),
        originalQuantity: quantityProduct.toFixed(3),
        addUpQuantity: newQuantity - quantityProduct,
      });
    } else {
      const quantityProduct = Number.parseFloat(
        this.formProductTogether.get('quantity').value
      );
      const quantity = Number.parseFloat((quantityProduct / 1.1).toFixed(3));
      let newQuantity = quantity;
      if (this.product.mutiple > 1) {
        newQuantity =
          Number.parseInt(
            (newQuantity / this.productTogether.mutiple).toFixed(3),
            10
          ) * this.productTogether.mutiple;
      }
      console.log(newQuantity);
      this.formProductTogether.patchValue({
        quantity: newQuantity.toFixed(2),
        originalQuantity: newQuantity.toFixed(2),
        addUpQuantity: 0,
      });
    }
  }

  addQuantityM2ProductSimilar() {
    console.log(
      'Adicionar 10%: ' + this.formProductSimilar.get('addUpQuantity').value
    );
    const isAddPercentQuantity = !(this.formProductSimilar.get('addUpQuantity')
      .value as boolean);
    if (isAddPercentQuantity) {
      const quantityProduct = Number.parseFloat(
        this.formProductSimilar.get('quantity').value
      );
      const quantity = Number.parseFloat((quantityProduct * 0.1).toFixed(3));
      let newQuantity = quantityProduct + quantity;
      if (this.productSimilar.mutiple > 1) {
        newQuantity =
          Number.parseFloat(
            (newQuantity / this.productSimilar.mutiple).toFixed()
          ) * this.productSimilar.mutiple;
        if (newQuantity < quantityProduct + quantity) {
          newQuantity += this.productSimilar.mutiple;
        }
      }
      newQuantity = Number.parseFloat(newQuantity.toFixed(3));
      this.formProductSimilar.patchValue({
        quantity: newQuantity.toFixed(3),
        originalQuantity: quantityProduct.toFixed(3),
        addUpQuantity: newQuantity - quantityProduct,
      });
    } else {
      const quantityProduct = Number.parseFloat(
        this.formProductSimilar.get('quantity').value
      );
      const quantity = Number.parseFloat((quantityProduct / 1.1).toFixed(3));
      let newQuantity = quantity;
      if (this.productSimilar.mutiple > 1) {
        newQuantity =
          Number.parseInt(
            (newQuantity / this.productSimilar.mutiple).toFixed(3),
            10
          ) * this.productSimilar.mutiple;
      }
      console.log(newQuantity);
      this.formProductSimilar.patchValue({
        quantity: newQuantity.toFixed(2),
        originalQuantity: newQuantity.toFixed(2),
        addUpQuantity: 0,
      });
    }
  }

  setStockProductTogether(selectedStore: any) {
    this.quantityStockProductTogether = 0;
    if (selectedStore != null) {
      this.quantityStockProductTogether = selectedStore.quantity;
    }
  }

  setStockProductSimilar(selectedStore: any) {
    this.quantityStockProductSimilar = 0;
    if (selectedStore != null) {
      this.quantityStockProductSimilar = selectedStore.quantity;
    }
  }

  // Função que cria o validador
  estoqueDisponivelValidator(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
      let quantitySale = 0;
      if (this.formProductTogether) {
        quantitySale = Number.parseFloat(
          this.formProductTogether.get('quantity').value
        );
      }
      const indisponivel = quantitySale > this.quantityStockProductTogether;
      return indisponivel
        ? { estoqueIndisponivel: { value: quantitySale } }
        : null;
    };
  }

  estoqueDisponivelValidatorSimilar(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
      let quantitySale = 0;
      if (this.formProductSimilar) {
        quantitySale = Number.parseFloat(
          this.formProductSimilar.get('quantity').value
        );
      }
      const indisponivel = quantitySale > this.quantityStockProductSimilar;
      return indisponivel
        ? { estoqueIndisponivel: { value: quantitySale } }
        : null;
    };
  }

  priceValidator(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
      let newPrice = 0;
      newPrice = control.value;
      let listPrice = 0;
      if (this.productTogether) {
        listPrice = this.productTogether.listPrice;
        if (this.productTogether.salePromotion > 0) {
          listPrice = this.productTogether.salePromotion;
        }
      }
      console.log('Preco atual: ' + listPrice);
      console.log('Novo Preco: ' + newPrice);
      const indisponivel = newPrice < listPrice;
      return indisponivel ? { invalidPrice: { value: newPrice } } : null;
    };
  }

  priceValidatorSimilar(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
      let newPrice = 0;
      newPrice = control.value;
      let listPrice = 0;
      if (this.productSimilar) {
        listPrice = this.productSimilar.listPrice;
        if (this.productSimilar.salePromotion > 0) {
          listPrice = this.productSimilar.salePromotion;
        }
      }
      console.log('Preco atual: ' + listPrice);
      console.log('Novo Preco: ' + newPrice);
      const indisponivel = newPrice < listPrice;
      return indisponivel ? { invalidPrice: { value: newPrice } } : null;
    };
  }

  //the end functions for products together

  /*function shop cart */
  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);
          }
        });
      });
  }

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

  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;
    }
  }
  /* END Function shop cart */

  returnListProduct() {
    this.router.navigate(['product-list']);
  }
}
