import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { Store } from '@ngrx/store';
import { ActionsLayout } from '@progress/kendo-angular-dialog';
import { Observable, Subscription } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { AuthService } from 'src/app/auth/services/auth.service';
import { ResultApi } from 'src/app/models/result-api.model';
import { UserAuth } from 'src/app/models/user-auth.model';
import { User } from 'src/app/models/user.model';
import { UpdatePriceItemAction } from '../../store/actions/shopping.action';
import { SaleState } from '../../store/models/sale-state.model';
import { ShoppingItem } from '../../store/models/shopping-item';

@Component({
  selector: 'app-discount-item-sales',
  templateUrl: './discount-item-sales.component.html',
  styleUrls: ['./discount-item-sales.component.scss']
})
export class DiscountItemSalesComponent implements OnInit {
  @Input() opened = false;
  @Input() shoppingItem: ShoppingItem;
  @Input() title = 'Confirma';
  @Input() textButtonConfirmation = 'Ok';
  @Input() textButtonCancel = 'Cancelar';
  @Output() resultEvent = new EventEmitter<boolean>();

  updating$: Observable<boolean>;
  public actionsLayout: ActionsLayout = 'normal';
  public formDiscountItem: FormGroup;
  userSubscription: Subscription;
  percentSeller: number;
  percentAuth: number;

  openedAuthUser = false;

  openedDialog = false;
  public loadingIcon = '';
  numeric: number;

  public onDialogClose(): void {
    this.resultEvent.emit(false);
    this.openedDialog = false;
  }

  public open(): void {
    this.opened = true;
  }

  public closeDialog() {
    this.openedDialog = false;
    this.resultEvent.emit(false);
  }

  constructor(
    private fb: FormBuilder,
    private authService: AuthService,
    private store: Store<SaleState>,) {

    this.formDiscountItem = this.fb.group({
      description: [''],
      listPrice: [this.numeric],
      discount: [this.numeric],
      discountValue: [this.numeric],
      salePrice: [this.numeric],
    });
  }

  ngOnInit(): void {
    console.log(this.shoppingItem.smallDescription);
    this.formDiscountItem.patchValue({
      description: this.shoppingItem.smallDescription,
      listPrice: this.shoppingItem.listPrice,
      discount: this.shoppingItem.discount,
      discountValue: this.shoppingItem.discountValue,
      salePrice: this.shoppingItem.price,
    });

    this.userSubscription = this.authService.getDiscount().subscribe(result => {
      this.percentSeller = result.data.discountUser;
      this.percentSeller = 0;
    });
    this.updating$ = this.store.select(store => store.shopping.updating);

  }

  calcDiscountValue() {
    const percent = this.formDiscountItem.get('discount').value;
    const discountValue = Number.parseFloat((this.shoppingItem.listPrice * (percent / 100)).toFixed(2));
    const salePrice = Number.parseFloat((this.shoppingItem.listPrice - discountValue).toFixed(2));
    this.formDiscountItem.patchValue({
      discountValue,
      salePrice,
    });
  }

  calcPercentDiscount() {
    const discountValue = this.formDiscountItem.get('discountValue').value;
    const percent = Number.parseFloat((discountValue / this.shoppingItem.listPrice).toFixed(2)) * 100;
    const salePrice = Number.parseFloat((this.shoppingItem.listPrice - discountValue).toFixed(2));
    this.formDiscountItem.patchValue({
      discount: percent,
      discountValue,
      salePrice,
    });
  }

  async confirmDiscount() {
    let discount = Number.parseFloat(this.formDiscountItem.get('discount').value);
    console.log('discount', discount);
    const discountValue = Number.parseFloat(this.formDiscountItem.get('discountValue').value);
    const salePrice = Number.parseFloat((this.shoppingItem.listPrice - discountValue).toFixed(2));

    // if (this.percentSeller < discount) {
    //   this.openedAuthUser = true;
    //   return;
    // }

    if (discountValue <= 0.01) {
      discount = 0;
    }

    console.log('shoppingItem', JSON.stringify(this.shoppingItem));
    const updateItem = { ...this.shoppingItem };
    updateItem.discount = discount;
    updateItem.discountValue = discountValue;
    updateItem.price = salePrice;
    updateItem.userDiscount = this.authService.getUser();
    this.store.dispatch(new UpdatePriceItemAction(updateItem));
    this.resultEvent.emit(true);
  }

  async returnAuthUser(userAuth: any) {
    this.openedAuthUser = false;
    const discount = Number.parseFloat(this.formDiscountItem.get('discount').value);
    const discountValue = Number.parseFloat(this.formDiscountItem.get('discountValue').value);
    const salePrice = Number.parseFloat((this.shoppingItem.listPrice - discountValue).toFixed(2));
    const user: UserAuth = JSON.parse(JSON.stringify(userAuth));
    if (user.id > 0) {
      this.authService.getDiscount(userAuth.id).subscribe(result => {
        this.percentAuth = result.data.discountUser;
        console.log('Desconto: ' + result.data.discountUser + ' - Desconto do pedido : ' + discount);
        if (this.percentAuth >= discount) {
          const updateItem = Object.assign({}, this.shoppingItem);
          updateItem.discount = discount;
          updateItem.discountValue = discountValue;
          updateItem.price = salePrice;
          updateItem.userDiscount = userAuth.id;
          this.store.dispatch(new UpdatePriceItemAction(updateItem));
          this.resultEvent.emit(true);
        } else {
          console.log('Não localizou o id.');
        }
      });
    }
  }

}
