import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {TestingRecieptService} from '../../../../../core/service/testing-register/testing-reciept.service';
import {Observable} from 'rxjs';
import {
    TestingRegisterEnrollmentService
} from "../../../../../core/service/enrollment-api/testing-register-enrollment.service";
import {SweetalertService} from "../../../../../core/service/sweetalert/sweetalert";
import {concatMap, filter, map, tap} from "rxjs/operators";
import {TestingInformationService} from "../../../../../core/service/testing-information/testing-information.service";

@Component({
    selector: 'app-manage-receipt',
    templateUrl: './manage-receipt.container.html',
    styleUrls: ['./manage-receipt.container.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ManageReceiptContainer implements OnInit {
    recieptsList$ = new Observable();
    testingInformationList$ = new Observable();

    constructor(
        private testingrecieptsSV: TestingRecieptService,
        private testingInformationSV: TestingInformationService,
        private testingregisterEnrollSV: TestingRegisterEnrollmentService,
        private swSV: SweetalertService,
        private cdr: ChangeDetectorRef
    ) {
    }

    ngOnInit(): void {
        this.testingInformationList$ = this.testingInformationSV.getAll();
        // this.testingInformationSV.getAll().pipe(
        //     tap(x => {
        //         this.testingInformationList = x.map((res: any) => {
        //             res.nameandcode = `${res.testing_information_code} ${res.testing_information_name} `;
        //             return res
        //         })
        //     }),
        //     tap(x => this.cdr.detectChanges())
        // ).subscribe();
        this.testingInformationList$ = this.testingInformationSV.getAll().pipe(
            map((x: any) => {
                return x = x.map(x => {
                    return {
                        ...x,
                        nameandcode: `${x.testing_information_code} ${x.testing_information_name} `
                    }
                })
            }),
        )
    }

    search(query) {
        if (query) return this.recieptsList$ = this.testingrecieptsSV.getByPaymentCode(`?${query}`);
        if (!query) return this.recieptsList$ = this.testingrecieptsSV.getAll();
    }

    CancelPay(id) {
        this.swSV.confirmText('ต้องการยกเลิกใบเสร็จนี้หรือไม่').pipe(
            filter(x => x.isConfirmed),
            concatMap(x => {
                return this.testingregisterEnrollSV.cancleAdmin(id).pipe(
                    tap(x => this.swSV.success('ยกเลิกเรียบร้อย')),
                    tap(x => this.recieptsList$ = this.testingrecieptsSV.getAll()),
                    tap(x => this.cdr.detectChanges())
                );
            })
        ).subscribe();
    }

}
