import { LoadCustomerAction } from './../../store/actions/customer-sale.action';
import { AfterViewInit, Component, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output, ViewChild } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { Store } from '@ngrx/store';
import { DialogCloseResult, DialogService } from '@progress/kendo-angular-dialog';
import { TextBoxComponent } from '@progress/kendo-angular-inputs';
import { Subscription } from 'rxjs';
import { AuthService } from 'src/app/auth/services/auth.service';
import { ResultApi } from 'src/app/models/result-api.model';
import { MessageFailureComponent } from 'src/app/shared/menssages/message-failure/message-failure.component';
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',
  templateUrl: './discount-item.component.html',
  styleUrls: ['./discount-item.component.scss']
})
export class DiscountItemComponent implements OnInit, OnDestroy, AfterViewInit {

  @Input() shoppingItem: ShoppingItem;
  @Output() public submitForm: EventEmitter<any> = new EventEmitter();
  @ViewChild('password') textbox: TextBoxComponent;
  public width = '100%';
  public height = '430px';
  public pageable = true;
  subscriptionUser: Subscription;
  subscriptionAuth: Subscription;
  discountAuth = 0;
  userDiscount = 0;
  userAuthOk = false;

  public form: FormGroup = new FormGroup({
    listPrice: new FormControl(),
    salePrice: new FormControl(),
    discount: new FormControl(),
    discountValue: new FormControl(),
    userAuth: new FormControl(),
  });

  public formAuthorization: FormGroup = new FormGroup({
    username: new FormControl(),
    password: new FormControl(),
  });

  constructor(private readonly authService: AuthService,
              private dialogService: DialogService,
              // private ngZone: NgZone,
              private store: Store<SaleState>) { }


  ngOnDestroy(): void {
    if (this.subscriptionUser) {
      this.subscriptionUser.unsubscribe();
    }
    if (this.subscriptionAuth) {
      this.subscriptionAuth.unsubscribe();
    }
  }

  ngAfterViewInit(): void {
  }

  maskPassword() {
    this.textbox.input.nativeElement.type = 'password';
  }

  ngOnInit(): void {
    this.subscriptionUser = this.authService
      .getDiscount()
      .subscribe(result => {
        if (result.success) {
          this.discountAuth = result.data.discountUser;
          this.userDiscount = result.data.id;
        } else {
          this.discountAuth = 0;
        }
      }, (err) => {
        this.discountAuth = 0;
      });

    this.form.patchValue({
      listPrice: this.shoppingItem.listPrice,
      salePrice: this.shoppingItem.price,
      discount: this.shoppingItem.discount,
      discountValue: 0,
    });
  }

  getAuthorization(): boolean {
    return this.form.get('userAuth').value;
  }

  onChangeDiscount(discount: any) {
    console.log(this.textbox);
    const listPrice = this.shoppingItem.listPrice;
    const salePrice = parseFloat((listPrice * (1 - (discount / 100))).toFixed(2));
    this.form.patchValue({ salePrice });
  }

  onChangePrice(price: any) {
    const listPrice = this.shoppingItem.listPrice;
    const discount = parseFloat((((listPrice - price) / listPrice) * 100).toFixed(4));
    this.form.patchValue({ discount });
  }

  showMessage(title: string, message: string) {
    const dialogRef = this.dialogService
      .open({
        title,
        content: MessageFailureComponent,
        actions: [{ text: 'OK', primary: true }],
        width: 400,
        height: 250,
        minWidth: 250,
      });

    const messageInfo = dialogRef.content.instance;
    messageInfo.message = message;
    dialogRef.result.subscribe();

    dialogRef.result.subscribe((result) => {
      if (result instanceof DialogCloseResult) {
        console.log('close');
        dialogRef.close();
      } else {
        console.log('action', result);
        dialogRef.close();
      }
    });
  }

  async saveDiscount() {
    const discount = this.form.get('discount').value;
    const listPrice = this.form.get('listPrice').value;
    const salePrice = this.form.get('salePrice').value;
    if (discount <= this.discountAuth) {
      this.sendDiscount(discount, salePrice);
      return;
    }
    if (salePrice > listPrice) {
      this.showMessage('Desconto para produto', 'Preço de venda não pode ser maior que preço de tabela.');
      return;
    }
    if (discount > this.discountAuth && !this.getAuthorization()) {
      this.showMessage('Desconto para produto', 'Desconto acima do desconto autorizado!');
      return;
    }
    if (discount > this.discountAuth && this.getAuthorization()) {

      this.subscriptionAuth = this.authService.authenticate({
        email: this.formAuthorization.get('username').value,
        password: this.formAuthorization.get('password').value
      })
        .subscribe((res: ResultApi) => {
          if (res.success) {
            console.log(res.data);
            this.discountAuth = res.data.discountPercent;
            this.userDiscount = res.data.id;
            if (discount > this.discountAuth) {
              this.showMessage('Desconto para produto', 'Desconto acima do desconto autorizado!');
            } else {
              console.log('Percentual autorizado!');
              this.sendDiscount(discount, salePrice);
              console.log('Desconto aplicado');
              this.submitForm.emit(this);
            }
          } else {
            this.showMessage('Erro ao autorizar desconto', res.message);
          }
        }, err => {
          // this.loadingIcon = '';
          console.log(err);
          this.showMessage('Erro ao autorizar desconto', err.error.message);
        });
    }
  }

  sendDiscount(discount: number, salePrice: number) {
    console.log('Atualizando o preço de venda do prdouto');
    const updateItem: ShoppingItem = {
      deliveryType: this.shoppingItem.deliveryType,
      invoiceStore: this.authService.getStore(),
      description: this.shoppingItem.description,
      discount,
      discountValue: (this.shoppingItem.listPrice - salePrice),
      id: this.shoppingItem.id,
      idCart: this.shoppingItem.idCart,
      idProduct: this.shoppingItem.idProduct,
      image: this.shoppingItem.image,
      listPrice: this.shoppingItem.listPrice,
      price: salePrice,
      productType: this.shoppingItem.productType,
      quantity: this.shoppingItem.quantity,
      seller: this.shoppingItem.seller,
      stockStore: this.shoppingItem.stockStore,
      userDiscount: this.userDiscount,
      promotion: this.shoppingItem.promotion,
      mutiple: this.shoppingItem.mutiple,
      auxDescription: this.shoppingItem.auxDescription,
      smallDescription: this.shoppingItem.smallDescription,
      brand: this.shoppingItem.brand,
      ean: this.shoppingItem.ean,
      percentUpQuantity: this.shoppingItem.percentUpQuantity,
      upQuantity: this.shoppingItem.upQuantity,
      base: this.shoppingItem.base,
      letter: this.shoppingItem.letter,
      line: this.shoppingItem.line,
      color: this.shoppingItem.color,
      can: this.shoppingItem.can,
    };
    this.store.dispatch(new UpdatePriceItemAction(updateItem));
  }

  public close() {
    this.submitForm.emit(this);
  }

}
