import { Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Store } from '@ngrx/store';
import { Subscription } from 'rxjs';
import { AuthService } from 'src/app/auth/services/auth.service';
import { ResultApi } from 'src/app/models/result-api.model';
import { FormValidations } from 'src/app/shared/validators/form-validations';
import { SaleState } from '../../store/models/sale-state.model';

@Component({
  selector: 'app-discount-order',
  templateUrl: './discount-order.component.html',
  styleUrls: ['./discount-order.component.scss']
})
export class DiscountOrderComponent implements OnInit, OnDestroy {

  @Input() orderValue = 0;
  @Input() percent = 0;
  orderWithDiscount = 0;
  discountAuthorization = 0;
  editdiscount = new FormControl();
  subscriptionUser: Subscription;
  SubscriptionAuth: Subscription;
  formDiscount: FormGroup;

  opened = false;
  openedMsgDiscount = false;

  @Output() public submitForm: EventEmitter<any> = new EventEmitter();

  constructor(
    private readonly authService: AuthService,
    private formBuilder: FormBuilder,
    private store: Store<SaleState>) { }


  ngOnInit() {
    this.orderWithDiscount = (this.orderValue * (1 - (this.percent / 100)));
    this.formDiscount = this.formBuilder.group({
      value: [this.orderValue, [Validators.required]],
      discount: [this.percent,
      Validators.compose([Validators.required])],
      discountValue: [(this.orderValue - this.orderWithDiscount),
      Validators.compose([Validators.required])],
      valueWithDiscount: [this.orderWithDiscount, [Validators.required]],
      // formUser: this.formBuilder.group({
      //   email: new FormControl(null, Validators.required),
      //   password: new FormControl(null, Validators.required),
      // }),
      // formGroup: this.formBuilder.group({
      //   userAuth: new FormControl(null, Validators.required),
      // }),
    });
    this.formDiscount.valueChanges.subscribe(f => {
      this.percent = this.formDiscount.get('discount').value;
      this.orderWithDiscount = (this.orderValue * (1 - (this.percent / 100)));
    });
    this.subscriptionUser = this.authService.getDiscount().subscribe(result => {
      if (result.success) {
        this.discountAuthorization = result.data.discountUser;
      } else {
        this.discountAuthorization = 0;
      }
    });
  }

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

  public close() {
    this.opened = false;
    this.openedMsgDiscount = false;
  }

  public closeMsgDiscount() {
    this.openedMsgDiscount = false;
    this.submitForm.emit(this.formDiscount);
  }

  statusform() {
    console.log(this.formDiscount);
  }

  confirmDiscount() {

    this.submitForm.emit(this.formDiscount);
    return;

    let email = this.formDiscount.get('formUser.email').value;

    const emailUpperCase = email.toUpperCase();
    const passwordUpperCase = this.formDiscount.get('formUser.password').value.toUpperCase();

    // if (this.discountAuthorization < this.percent) {
    if (this.formDiscount.controls.formGroup.get('userAuth').value) {
      this.SubscriptionAuth = this.authService.authenticate({
        email: emailUpperCase,
        password: passwordUpperCase
      })
        .subscribe((res: ResultApi) => {
          console.log(res);
          if (res.success) {
            this.discountAuthorization = res.data.discountPercent;
            if (this.discountAuthorization < this.percent) {
              this.openedMsgDiscount = true;
            } else {
              console.log('fechar form');
              this.submitForm.emit(this.formDiscount);
            }
            // this.loadingIcon = '';
          } else {
            // this.loadingIcon = '';
            // this.showErrorMessage(res.message);
          }
        }, err => {
          // this.loadingIcon = '';
          // this.showErrorMessage('Erro ao processar sua requisição,
          // tente novamente e caso persista o erro contacte o departamento de TI.');
        });
    } else {
      this.openedMsgDiscount = true;
    }


    // } else {
    //   this.close();
    // }
  }

  getAuthorization() {
    return false; //this.formDiscount.controls.formGroup.get('userAuth').value;
  }

  validationUser() {
    this.formDiscount.markAllAsTouched();
    // if (this.formDiscount.valid) {
    //   // this.loadingIcon = 'loading';
    //   this.authService.authenticate({
    //     email: this.formDiscount.get('formUser.email').value,
    //     password: this.formDiscount.get('formUser.password').value
    //   })
    //     .subscribe((res: ResultApi) => {
    //       console.log(res);
    //       if (res.success) {
    //         this.discountAuthorization = res.data.discountPercent;
    //         return this.discountAuthorization;
    //         // this.loadingIcon = '';
    //       } else {
    //         // this.loadingIcon = '';
    //         // this.showErrorMessage(res.message);
    //         return this.discountAuthorization;
    //       }
    //     }, err => {
    //       return this.discountAuthorization;
    //       // this.loadingIcon = '';
    //       // this.showErrorMessage('Erro ao processar sua requisição,
    //       // tente novamente e caso persista o erro contacte o departamento de TI.');
    //     });
    //   return this.discountAuthorization;
    // }
  }

}
