import {
    Component,
    OnInit,
    ChangeDetectionStrategy,
    ChangeDetectorRef,
    ViewChild,
    Output,
    EventEmitter
} from '@angular/core';
import {TestingRegisterService} from '../../../../../core/service/testing-register/testing-register.service';
import {catchError, concatMap, filter, switchMap, tap} from 'rxjs/operators';
import {SweetalertService} from '../../../../../core/service/sweetalert/sweetalert';
import {from, Observable, throwError} from 'rxjs';
import {MatDialog} from '@angular/material/dialog';
import {
    DialogChangeRoomComponent
} from '../../../../candidate-list/candidate-list/presenter/dialog/dialog-change-room/dialog-change-room.component';
import {UserCounterLoginComponent} from '../../presenter/user-counter-login/user-counter-login.component';
import {SharedUsercouterService} from '../../../../../core/service/testing-register/shared-usercouter.service';
import {createQueryStringFromObject} from 'src/app/shared/util/func';
import {RecieptService} from '../../../../../core/service/report/reciept/reciept.service';
import {GetstudentService} from '../../../../../core/service/student/getstudent.service';
import {
    TestingRegisterIsPayService
} from '../../../../../core/service/testing-register/testing-register-is-pay.service';
import {ActivatedRoute} from '@angular/router';
import {RegisterSummaryFormComponent} from '../../presenter/form/register-summary-form/register-summary-form.component';
import Swal, {SweetAlertResult} from 'sweetalert2';
import {TableSummaryComponent} from '../../presenter/table-summary/table-summary/table-summary.component';
import {formatDate} from "@angular/common";
import {
    ReceiptByPaymentCodeService
} from '../../../../../core/service/report/receipt-by-payment-code/receipt-by-payment-code.service';
import {
    TestingRegisterEnrollmentService
} from '../../../../../core/service/enrollment-api/testing-register-enrollment.service';
import {UserCounterLoginService} from '../../../../../core/service/permission/user-counter-login.service';
import {UserCountersService} from '../../../../../core/service/permission/user-counters.service';
import {
    RegisterSummarySummaryComponent
} from '../../presenter/summary/register-summary-summary/register-summary-summary.component';


@Component({
    selector: 'app-register-summary',
    templateUrl: './register-summary.container.html',
    styleUrls: ['./register-summary.container.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class RegisterSummaryContainer implements OnInit {
    @ViewChild(RegisterSummaryFormComponent)
    childForm: RegisterSummaryFormComponent;
    @ViewChild(RegisterSummarySummaryComponent)
    childForm2: RegisterSummarySummaryComponent;
    @ViewChild(TableSummaryComponent)
    childForm3: TableSummaryComponent;
    @Output() isPrint = false;
    @Output() isCancel = false;
    @Output() isMoney = false;
    CandidateTypeName;
    @Output() isHidebutton = false;
    @Output() isPaymentBill = false;
    @Output() onNewRegister = new EventEmitter();
    registerList$ = new Observable();
    userData$ = null;
    studentData$: any = null;
    summaryData$ = null;
    ResetEvent;

    constructor(
        private reportPaymentcode: ReceiptByPaymentCodeService,
        private registerSV: TestingRegisterService,
        private userCounterSV: UserCountersService,
        private testingIsPaySV: TestingRegisterIsPayService,
        private testingregisterEnrollSV: TestingRegisterEnrollmentService,
        private reportRecieptSV: RecieptService,
        private swSV: SweetalertService,
        private activeRoute: ActivatedRoute,
        private tesingregisterSV: TestingRegisterService,
        public sharedCouterSV: SharedUsercouterService,
        private dialog: MatDialog,
        private cdr: ChangeDetectorRef,
        private getStudentSV: GetstudentService,
    ) {
    }

    ngOnInit(): void {
        const Logindata = this.sharedCouterSV.data;
        if (Logindata == null) {
            this.dialoglogin();
        } else {
            this.userData$ = Logindata;
            console.log(Logindata)
            console.log(this.userData$)
            this.registerList$ = this.userCounterSV.getCounterSummary(this.userData$.counter_no, this.userData$.counter_uid, this.userData$.counter_periods[0].period);
            this.cdr.detectChanges();
        }
    }

    emitEventToChild() {
        this.ResetEvent.next();
    }

    dialoglogin() {
        const dialogRef = this.dialog.open(UserCounterLoginComponent, {
            disableClose: true,
            width: '500px',
            height: '250px',
        });
        dialogRef.afterClosed().subscribe(
            result => {
                this.sharedCouterSV.data = result;
                this.userData$ = result;
                this.cdr.detectChanges();
            }
        );
    }

    checkDate(dateOpen, dateClose) {
        const dateFrom: any = formatDate(dateOpen, 'mm/dd/yyyy', 'en-US');
        const dateTo: any = formatDate(dateClose, 'mm/dd/yyyy', 'en-US');
        const dateCheck: any = formatDate(new Date(), 'mm/dd/yyyy', 'en-US');
        var d1 = dateFrom.split("/");
        var d2 = dateTo.split("/");
        var c = dateCheck.split("/");
        var from = new Date(d1[2], parseInt(d1[1]) - 1, d1[0]);  // -1 because months are from 0 to 11
        var to = new Date(d2[2], parseInt(d2[1]) - 1, d2[0]);
        var check = new Date(c[2], parseInt(c[1]) - 1, c[0]);
        return check > from && check < to;
    }


    setCanditdatetypeName(data) {
        this.CandidateTypeName = data;
    }

    confirm(data) {
        const recieveData = data.form;

        switch (data.status) {
            case true: {
                this.registerSV.add(recieveData).pipe(
                    tap(x => this.swSV.saveSuccess()),
                    // tap(x => this.childForm.isHidebutton = true),
                    catchError(err => {
                        this.childForm.confirm(false)
                        this.swSV.error(err.error);
                        return throwError(err);
                    })
                ).subscribe(
                    result => {
                        console.log(result);
                        this.summaryData$ = result;
                        this.childForm.updateForm(result);
                        console.log(this.summaryData$);
                        this.cdr.detectChanges();
                    }
                );
                break;
            }
            case 'update': {
                this.registerSV.update2(recieveData).pipe(
                    tap(x => this.swSV.updateSuccess()),
                    tap(x => this.registerSV.get(recieveData.testing_register_uid).pipe(
                        tap(y => this.cdr.detectChanges()),
                    ).subscribe(
                    )),
                    // tap(x => this.childForm.isHidebutton = true),
                    catchError(err => {
                        this.childForm.confirm(false);
                        this.swSV.error(err.error);
                        return throwError(err);
                    })
                ).subscribe(
                    result => {
                        console.log(result);
                        this.summaryData$ = result;
                        this.childForm.updateForm(result);
                        this.cdr.detectChanges();
                    }
                );
                break;
            }
        }
    }


    recieveMoney(type) {
        console.log(this.summaryData$);
        const registerUid = this.summaryData$.testing_register_uid;
        switch (type) {
            case 'cash':
                Swal.fire({
                    icon: 'warning',
                    title: 'ยืนยันการรับเงินนี้ไหม?',
                    showDenyButton: true,
                    heightAuto: false,
                    confirmButtonText: 'ตกลง',
                    denyButtonText: `ยกเลิก`,
                }).then((result) => {
                    if (result.isConfirmed) {
                        this.testingIsPaySV.recievedMoney(registerUid).pipe(
                            tap(x => this.isPrint = true),
                            // tap(x => this.isCancel = true),
                            tap(x => this.isMoney = true),
                            tap(x => console.log(x)),
                            tap(x => {
                                const data: any = x
                                this.summaryData$.payment_code = data.payment_code
                            }),
                            tap(x => this.isPaymentBill = true),
                            tap(x => this.cdr.detectChanges()),
                        ).subscribe();
                        Swal.fire({
                            icon: 'success',
                            title: 'รับเงินเรียบร้อยแล้ว',
                            timer: 1000,
                            heightAuto: false
                        }).then(result => {
                            this.childForm2.updateSummary();
                            // Swal.fire({
                            //   icon: 'warning',
                            //   showDenyButton: true,
                            //   heightAuto: false,
                            //   confirmButtonText: 'สมัครผู้สมัครใหม่',
                            //   denyButtonText: `ดูใบเสร็จ`,
                            // }).then((result) => {
                            //   if (result.isConfirmed) {
                            //     // this.testingIsPaySV.recievedMoney(registerUid).pipe(
                            //     //   tap(x => this.childForm.confirm('reset')),
                            //     //   tap(x => this.summaryData$ = null),
                            //     //   tap(x => this.isPrint = true),
                            //     //   tap(x =>
                            //     //     Swal.fire('พร้อมสมัครคนถัดไป', '', 'success')
                            //     //   ),
                            //     //   tap(x => this.cdr.detectChanges()),
                            //     // ).subscribe();
                            //     this.childForm.confirm('reset')
                            //     this.summaryData$ = null
                            //     this.isPaymentBill = true
                            //     this.cdr.detectChanges()
                            //   } else if (result.isDenied) {
                            //     this.print();
                            //     this.summaryData$ = null
                            //     // this.childForm.confirm('reset')
                            //   }
                            // });
                            // this.print();
                            // this.isPaymentBill = true
                            // this.summaryData$ = null
                            // this.childForm.confirm('reset')
                        })
                    }
                })
                // code block
                break;
            case 'credit':
                Swal.fire({
                    icon: 'warning',
                    title: 'ยืนยันการชำระผ่าน Credit-Card',
                    showDenyButton: true,
                    heightAuto: false,
                    confirmButtonText: 'ตกลง',
                    denyButtonText: `ยกเลิก`,
                }).then((result) => {
                    if (result.isConfirmed) {
                        Swal.fire({
                            icon: 'warning',
                            title: 'ช่องทางการชำระเงินนี้ยังไม่พร้อมใช้งาน',
                            timer: 1000,
                            heightAuto: false
                        }).then(result => {
                            // this.isPaymentBill = true;
                            // this.isPrint = true;
                            // this.isMoney = true;
                            // this.childForm2.updateSummary();
                            this.cdr.detectChanges()
                        })
                    }
                })
                break;
            case 'paypal':
                Swal.fire({
                    icon: 'warning',
                    title: 'ยืนยันการชำระผ่าน Paypal',
                    showDenyButton: true,
                    heightAuto: false,
                    confirmButtonText: 'ตกลง',
                    denyButtonText: `ยกเลิก`,
                }).then((result) => {
                    if (result.isConfirmed) {
                        Swal.fire({
                            icon: 'warning',
                            title: 'ช่องทางการชำระเงินนี้ยังไม่พร้อมใช้งาน',
                            timer: 1000,
                            heightAuto: false
                        }).then(result => {
                            // this.isPaymentBill = true;
                            // this.isPrint = true;
                            // this.isMoney = true;
                            // this.childForm2.updateSummary();
                            this.cdr.detectChanges()
                        })
                    }
                })
                break;
        }

    }

    newRegister() {
        this.summaryData$ = null;
        this.isPrint = false;
        this.isCancel = false;
        this.isMoney = false;
        this.isPaymentBill = false;
        this.isHidebutton = false;
        this.childForm.confirm('reset')
        this.cdr.detectChanges();
    }

    cancelMoney() {
        const registerUid = this.summaryData$.testing_register_uid;
        Swal.fire({
            icon: 'warning',
            title: 'ยืนยันการยกเลิกรายการนี้?',
            showDenyButton: true,
            heightAuto: false,
            confirmButtonText: 'ตกลง',
            denyButtonText: `ยกเลิก`,
        }).then((result) => {
            if (result.isConfirmed) {
                this.testingregisterEnrollSV.deleteAdmin(registerUid).pipe(
                    tap(x => this.isPrint = true),
                    tap(x => this.isCancel = false),
                    tap(x => this.cdr.detectChanges()),
                ).subscribe();
                Swal.fire({
                    icon: 'success',
                    title: 'ยกเลิกเรียบร้อย',
                    timer: 1000,
                    heightAuto: false
                }).then(result => {
                    this.childForm2.updateSummary();
                    this.summaryData$ = null;
                    this.isPaymentBill = false
                    this.childForm.confirm('reset')
                })
            }
        })
    }

    print() {
        console.log(this.summaryData$);
        const registerUid = this.summaryData$.testing_register_uid;
        const paymentcode = this.summaryData$.payment_code;
        // paymentcode = paymentcode.replace(/^..../g, '');
        // this.reportRecieptSV.getPdfReport(registerUid).subscribe(res => {
        //   const fileURL = URL.createObjectURL(res);
        //   window.open(fileURL, '_blank');
        // });
        this.reportPaymentcode.getPdfReport(paymentcode).subscribe(res => {
            const fileURL = URL.createObjectURL(res);
            window.open(fileURL, '_blank');
        });
    }

    printreal() {
        console.log(this.summaryData$);
        const registerUid = this.summaryData$.testing_register_uid;
        const paymentcode = this.summaryData$.payment_code;
        // paymentcode = paymentcode.replace(/^..../g, '');
        this.reportPaymentcode.getPdfReportReceiptForAll(registerUid).subscribe(res => {
            const fileURL = URL.createObjectURL(res);
            window.open(fileURL, '_blank');
        });
        // this.reportPaymentcode.getPdfReport(paymentcode).subscribe(res => {
        //   const fileURL = URL.createObjectURL(res);
        //   window.open(fileURL, '_blank');
        // });
    }

    search(query) {
        console.log(query);
        // this.getStudentSV.get(query).subscribe(
        //   result => {
        //     this.studentData$ = result;
        //     this.cdr.detectChanges();
        //   },
        //       error => {
        //     this.swSV.error('ไม่พบข้อมูล');
        //       }
        // );
        this.studentData$ =
            {
                student_name_th: 'นางสาวรุ่งอรุณ สว่าง',
                student_name_en: 'MISS RUNGARUN SAWANG',
                mobile_no: '0610656832',
                student_code: query,
                faculty_name_th: 'คณะมนุษยศาสตร์',
                major_name_th: 'ภาษาอังกฤษ',
                allow_register: [
                    {
                        subject_name_th: 'ความรู้ความสามารถทั่วไป 2',
                        subject_name_en: 'string',
                        subject_code: 'GK002',
                        credit: 1
                    },
                    {
                        subject_name_th: 'ความรู้ความสามารถทั่วไป 1',
                        subject_name_en: 'string',
                        subject_code: 'GK001',
                        credit: 1
                    }
                ]
            };
        this.cdr.detectChanges();
    }

    ResetRegister() {
        this.childForm.confirm('reset');
    }

    logoutcouter() {
        Swal.fire({
            icon: 'warning',
            title: `ยืนยันการออกเค้าเตอร์ ${this.userData$.counter_pin}`,
            showDenyButton: true,
            heightAuto: false,
            confirmButtonText: 'ตกลง',
            denyButtonText: `ยกเลิก`,
        }).then((result) => {
            if (result.isConfirmed) {
                this.userCounterSV.logout(this.userData$.counter_pin).pipe(
                    tap(x => this.isCancel = false),
                    tap(x => this.isPrint = true),
                    tap(x => this.cdr.detectChanges()),
                ).subscribe();
                Swal.fire({
                    icon: 'success',
                    title: 'ออกเค้าเตอร์เรียบร้อย',
                    timer: 1000,
                    heightAuto: false
                }).then(result => {
                    this.sharedCouterSV.data = null;
                    this.userData$ = null;
                    this.childForm.confirm('reset');
                    this.cdr.detectChanges()
                });
            }
        });
        // this.userData$ = null;
        // this.childForm.confirm('reset');
        // this.cdr.detectChanges();
    }

}
