import {Component, OnInit, ChangeDetectionStrategy, Inject, ChangeDetectorRef} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
import {SweetalertService} from '../../../../../../core/service/sweetalert/sweetalert';
import {createQueryStringFromObject} from '../../../../../../shared/util/func';
import {Observable, throwError} from 'rxjs';
import {catchError, concatMap, filter, tap} from 'rxjs/operators';
import {EnrollmentCounterPaymentsService} from '../../../../../../core/service/testing-register/enrollment-counter-payments.service';

@Component({
  selector: 'app-dialog-enrollment-counter-payment',
  templateUrl: './dialog-enrollment-counter-payment.component.html',
  styleUrls: ['./dialog-enrollment-counter-payment.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DialogEnrollmentCounterPaymentComponent implements OnInit {
  enrollmentData$ = new Observable()

  query = {
    student_code: null,
    id_card: null,
    payment_code: null,
  };
  constructor(
    private swSV: SweetalertService,
    private enrollentCounterPaymentSV: EnrollmentCounterPaymentsService,
    private cdr: ChangeDetectorRef,
    private dialogRef: MatDialogRef<DialogEnrollmentCounterPaymentComponent>,
    @Inject(MAT_DIALOG_DATA) public data
  ) { }

  ngOnInit(): void {
    console.log(this.data);

  }

  search(){
    const query = createQueryStringFromObject(this.query);
    console.log(query);
    if(query) return this.enrollmentData$ = this.enrollentCounterPaymentSV.search(`?${query}`);
  }

  pay(registerUid){
    this.swSV.confirmText('ยืนยันการรับเงินใช่หรือไม่').pipe(
      filter(x => x.isConfirmed),
      concatMap(x => {
        return this.enrollentCounterPaymentSV.postRecieve(
          registerUid,
          this.data.data.counter_no,
          this.data.data.counter_pin,
          this.data.data.counter_periods[0].period).pipe(
          tap(x => this.swSV.success('รับเงินสำเร็จ')),
          tap(x => {
            const query = createQueryStringFromObject(this.query);
            this.enrollmentData$ = this.enrollentCounterPaymentSV.search(`?${query}`);
          }),
          tap(x => this.cdr.detectChanges()),
          catchError(err => {
            this.swSV.errText(err.error);
            return throwError(err);
          })
        );
      })
    ).subscribe();
  }

}
