import { Component, Input, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { GridDataResult, PageChangeEvent } from '@progress/kendo-angular-grid';
import { map, switchMap, tap } from 'rxjs/operators';
import { AuthService } from 'src/app/auth/services/auth.service';
import { FilterProduct } from 'src/app/models/filter-product.model';
import { ProductsOrder } from 'src/app/models/products-order.model';
import { SaleProduct } from 'src/app/models/sale-product.model';
import { OrderService } from 'src/app/services/order.service';
import { ProductService } from 'src/app/services/product.service';
import { SaleState } from '../../store/models/sale-state.model';
import { AddItemAction } from '../../store/actions/shopping.action';
import { ShoppingService } from 'src/app/services/shopping.service';
import { Router } from '@angular/router';
import { CalculatePriceColor } from 'src/app/models/calculate-price-color.model';
import { TintometricoService } from 'src/app/services/tintometrico.service';

@Component({
  selector: 'app-list-product-orders',
  templateUrl: './list-product-orders.component.html',
  styleUrls: ['./list-product-orders.component.scss']
})
export class ListProductOrdersComponent implements OnInit {

  productsOrder: ProductsOrder[] = [];
  public gridView: GridDataResult;
  public pageSize = 10;
  public skip = 0;
  public mySelection: string[] = [];

  insertProducts = false;


  constructor(
    private readonly orderService: OrderService,
    private readonly productService: ProductService,
    private readonly authService: AuthService,
    private store: Store<SaleState>,
    private readonly shoppingService: ShoppingService,
    private readonly router: Router,
    private readonly tintometricoService: TintometricoService,
  ) {
    this.loadItems();
  }

  ngOnInit() {
  }

  public pageChange(event: PageChangeEvent): void {
    this.skip = event.skip;
    this.loadItems();
  }

  private loadItems(): void {
    this.productsOrder = this.orderService.getProductsOrder();
    this.gridView = {
      data: this.productsOrder.slice(this.skip, this.skip + this.pageSize),
      total: this.productsOrder.length,
    };
  }

  addProductCart() {
    if (this.mySelection.length == 0) {
      return;
    }

    for (let index = 0; index < this.mySelection.length; index++) {
      this.insertProducts = true;
      const element = this.mySelection[index];
      console.log("Produtos: " + element);
      const productOrder = this.productsOrder.find(p => p.itemId == element);
      let product: SaleProduct;

      const priceColor = new CalculatePriceColor();

      if (productOrder !== null) {
        const filterProduct: FilterProduct = { brands: [], text: productOrder.productId.toString() };
        this.productService.getProductByFilter(this.authService.getStore(), 1, 50, filterProduct)
          .pipe(
            map(result => result.filter(p => p.idProduct == productOrder.productId)),
            map((listProduct) => product = listProduct[0]),
            map((product) => {
              priceColor.productId = product.idProduct;
              priceColor.can = product.can;
              priceColor.letter = product.letter;
              priceColor.line = product.line;
              priceColor.price = 0;
              priceColor.storeId = this.authService.getStore();
              priceColor.color = productOrder.color;
            }),
            switchMap((product) => this.tintometricoService.calculatePrice(priceColor) ),
            map((resultPriceColor) => priceColor.price = resultPriceColor.price),
            switchMap(() =>
            this.productService
                .validateStock(product.idProduct, (product.productType == "A") ? 'RI' : 'EN', this.authService.getStore(),
                  (productOrder.quantity))
            ),
            map((stockValid) => {
              if (stockValid) {
                const id = null;
                const idCart =  this.shoppingService.getCart();
                const sellerId = this.authService.getSeller();
                const discount = null;
                const discountValue = null;
                const userDiscount = null;
                const cost = null;
                const deliveryType = (product.productType == "A") ? 'RI' : 'EN';
                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: productOrder.quantity,
                  price: (productOrder.color != null) ? priceColor.price : product.salePrice,
                  deliveryType, cost: cost,
                  stockStore: this.authService.getStore(), seller: sellerId, percentUpQuantity: 0, upQuantity: 0,
                  discount, discountValue, ean: product.ean,
                  promotion: (product.offPercent > 0) ? (productOrder.color != null) ? priceColor.price : product.salePrice : 0,
                  listPrice: (productOrder.color != null) ? priceColor.price : product.listPrice, userDiscount,
                  mutiple: product.mutiple,
                  auxDescription: productOrder.color, smallDescription: product.smallDescription, brand: product.brand,
                  base: product.base, letter: product.letter, line: product.line, color: productOrder.color,
                  can: product.can, environment: productOrder.local
                }));

              }
            })
          ).subscribe(() => {
            this.insertProducts = false;
          }
          );
      }
    }

  }

  openProductOrder() {
    this.router.navigate(['sales/menu/product-order']);
  }

}
