import { Component, Input, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { FabAlign } from '@progress/kendo-angular-buttons';
import { minusIcon, plusIcon } from '@progress/kendo-svg-icons';
import { Observable, of, Subscription } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { AuthService } from 'src/app/auth/services/auth.service';
import { Product } from 'src/app/models/product.model';
import { Rupture } from 'src/app/models/rupture.model';
import { SaleInstallment } from 'src/app/models/sale-installment.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 { AddItemAction, LoadShoppingItemsAction } from '../store/actions/shopping.action';
import { SaleState } from '../store/models/sale-state.model';
import { ShoppingItem } from '../store/models/shopping-item';

@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {
  id: number;
  saleProduct: SaleProduct;
  product: Product;
  images: string[] = [];
  quantity = 1;
  subscriptionProduct: Subscription;
  subscriptionParam: Subscription;
  shopping$: Observable<ShoppingItem[]>;
  loading$: Observable<boolean>;
  error$: Observable<Error>;
  stock$: Observable<Stock[]>;
  installment$: Observable<SaleInstallment[]>;
  public icons = { adicionar: plusIcon, deduzir: minusIcon };
  public topCenter: FabAlign = { vertical: 'top', horizontal: 'center' };
  public width = '100%';
  public height = '430px';
  public pageable = true;
  public form: FormGroup;
  public formRuptura: FormGroup;

  public enabled = true;
  public type = 'slide';
  public direction = 'right';
  public duration = 400;

  public get myAnimation(): any {
    if (this.enabled) {
      return {
        type: this.type,
        direction: this.direction,
        duration: this.duration,
      };
    }

    return false;
  }

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

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private productService: ProductService,
    private store: Store<SaleState>,
    private shoppingService: ShoppingService,
    private authService: AuthService) {
    this.form = new FormGroup({
      deliveryType: new FormControl(this.data.deliveryType, [
        Validators.required,
      ]),
      quantity: new FormControl(this.data.quantity, [
        Validators.required]),
      stockStore: new FormControl(this.data.stockStore, [Validators.required]),
      auxDescription: new FormControl(),
    });
    this.formRuptura = new FormGroup({
      document: new FormControl('', [Validators.required, ]),
      name: new FormControl('', [Validators.required]),
      cellPhone: new FormControl('', [Validators.required]),
      email: new FormControl('', [Validators.required]),
      description: new FormControl('', [Validators.required]),
      quantityRupture: new FormControl('', [Validators.required]),
    });

  }

  ngOnInit(): void {
    this.shopping$ = this.store.select(store => store.shopping.list);
    this.loading$ = this.store.select(store => store.shopping.loading);
    this.error$ = this.store.select(store => store.shopping.error);
    this.store.dispatch(new LoadShoppingItemsAction(this.shoppingService.getCart()));


    this.id = this.route.snapshot.params.id;
    this.subscriptionParam = this.route.params.subscribe((params: any) => {
      this.id = params.id;
      this.subscriptionProduct = this.productService.getSaleProduct(this.authService.getStore(), this.id)
        .subscribe(product => {
          this.saleProduct = product;
          this.createImagens(this.saleProduct.urlImage);
          this.productService.getProduct(this.authService.getStore(), this.id).subscribe((data) => {
            this.product = data;
          });
        });

      console.log("Filial: " + this.authService.getStore());
      console.log("ID: " + this.id);

      this.stock$ = this.productService.getStocks(this.authService.getStore(), this.id);
      this.stock$.subscribe(data => {
        console.log("FILIAIS: " + JSON.stringify(data));
      });
      this.shopping$.subscribe((data) => {
        data.forEach(item => {
          // tslint:disable-next-line: triple-equals
          if (item.idProduct == this.id) {
            this.form.patchValue({
              quantity: item.quantity,
              stockStore: item.stockStore,
              deliveryType: item.deliveryType,
              auxDescription: item.auxDescription,
            });
          }
        });
      });
    });

  }

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

  }

  changeQuantity(increment: boolean) {
    if (increment) {
      this.quantity += 1;
    }
    else {
      this.quantity -= 1;
    }
    if (this.quantity <= 0) {
      this.quantity = 1;
    }
  }

  createItemShopping() {
    console.log(this.form.value);
    const deliveryType = 'deliveryType';
    const stokeStore = 'stockStore';
    const auxDescription = 'auxDescription';
    const quantity = 'quantity';
    console.log('Descricao auxiliar: ' + this.form.value[auxDescription]);
    this.store.dispatch(new AddItemAction({
      id: null,
      invoiceStore: this.authService.getStore(),
      idCart: this.shoppingService.getCart(),
      idProduct: this.saleProduct.idProduct,
      description: this.saleProduct.title,
      image: this.images[0],
      productType: this.saleProduct.productType,
      quantity: this.form.value[quantity],
      price: this.saleProduct.salePrice,
      listPrice: this.saleProduct.listPrice,
      discount: 0,
      discountValue: 0,
      promotion: this.saleProduct.offPercent > 0 ? this.saleProduct.promotion : 0,
      deliveryType: this.form.value[deliveryType],
      stockStore: this.form.value[stokeStore],
      seller: this.authService.getSeller(),
      userDiscount: null,
      mutiple: this.saleProduct.mutiple,
      auxDescription: this.form.value[auxDescription],
      smallDescription: this.saleProduct.smallDescription,
      brand: this.saleProduct.brand,
      ean: this.saleProduct.ean,
      percentUpQuantity: 0,
      upQuantity: 0,
      base: this.saleProduct.base,
      letter: this.saleProduct.letter,
      line: this.saleProduct.line,
      color: this.saleProduct.color,
      can: this.saleProduct.can,
    }));

    this.loading$.subscribe(value => {
      if (!value) {
        this.error$.subscribe(err => {
          if (!err) {
            this.router.navigate(['appbar']);
          }
        });
      }
    });
  }

  public onTabSelect(e) {
    console.log(e);
  }

  getInstallment() {
    const quantity = this.form.get('quantity').value;
    this.installment$ = this.productService.getInstallment(this.authService.getStore(), this.saleProduct.idProduct, quantity);
  }

  showRuptura(){
    this.formRuptura.reset();
    const jsonCustomer = localStorage.getItem('preCustomer');
    if (jsonCustomer != null){
      const customer = JSON.parse(jsonCustomer);
      this.formRuptura.patchValue({
        document: customer.document,
        name: customer.name,
        cellPhone: customer.cellPhone,
      });
    }
    this.formRuptura.patchValue({
      description: this.saleProduct.title,
    });
  }

  registerRuptura() {
    console.log('dados formulario:' + JSON.stringify(this.formRuptura.value));
    const dataRupture: Rupture = {
      document: this.formRuptura.get('document').value,
      name: this.formRuptura.get('name').value,
      cellPhone: this.formRuptura.get('cellPhone').value,
      email: this.formRuptura.get('email').value,
      store: this.authService.getStore(),
      seller: this.authService.getSeller(),
      idProduct: this.saleProduct.idProduct,
      quantity: this.formRuptura.get('quantityRupture').value,
    };
    console.log(dataRupture);
    this.shoppingService.registerRupture(dataRupture)
      .subscribe(data => {
        console.log('Registro realizado com sucesso.');
    }, err => of(console.log(err)));
  }



}

