import {
    Component,
    OnInit,
    ChangeDetectionStrategy,
    ChangeDetectorRef,
    Output,
    EventEmitter,
    Input,
    OnChanges
} from '@angular/core';
import {FormArray, FormBuilder, FormGroup, NG_VALIDATORS, Validators} from '@angular/forms';
import {BaseForm} from '../../../../../../core/base/base-form';
import {SweetalertService} from '../../../../../../core/service/sweetalert/sweetalert';
import {ActivatedRoute, Router} from '@angular/router';
import {Location} from '@angular/common';
import {AcademicSemesterService} from '../../../../../../core/service/settings/academic-semester.service';
import {AcademicYearService} from '../../../../../../core/service/settings/academic-year.service';
import {
    TestingInformationService
} from '../../../../../../core/service/testing-information/testing-information.service';
import {FacultysService} from '../../../../../../core/service/settings/facultys.service';
import {DepartmentService} from '../../../../../../core/service/settings/department.service';
import {SubjectsService} from '../../../../../../core/service/settings/subjects.service';
import {TestingCenterService} from '../../../../../../core/service/TestingCenter/testing-center.service';
import {EducationTypesService} from '../../../../../../core/service/settings/education-types.service';
import {catchError, concatMap, filter, tap} from 'rxjs/operators';
import {TestingFieldService} from '../../../../../../core/service/settings/testing-field.service';
import {UploadService} from '../../../../../../core/service/upload/upload.service';
import {MatDialog} from '@angular/material/dialog';
import {PreviewImageComponent} from '../../preview/preview-image/preview-image.component';
import {CheckAvailableRoomService} from '../../../../../../core/service/testing-register/check-available-room.service';
import {formatDate} from '@angular/common';
import {realCitizenIdValidator} from '../../../../../../shared/validator/real-citizen-id.validator';
import {StudentService} from '../../../../../../core/service/student/student.service';
import {Subject, throwError} from 'rxjs';
import {createQueryStringFromObject} from '../../../../../../shared/util/func';
import {
    TestingSubjectAddDateService
} from '../../../../../../core/service/testing-information/testing-subject-add-date.service';
import {
    ApproveDialogComponent
} from '../../../../../approve-examination/feature/dialog/approve-dialog/approve-dialog.component';
import {
    DialogEnrollmentCounterPaymentComponent
} from '../../dialog/dialog-enrollment-counter-payment/dialog-enrollment-counter-payment.component';
import {
    DialogCheckPaymentCounterComponent
} from '../../dialog/dialog-check-payment-counter/dialog-check-payment-counter.component';
import {
    CheckSubjectAndDateService
} from "../../../../../../core/service/testing-register/check-subject-and-date.service";

@Component({
    selector: 'app-register-summary-form',
    templateUrl: './register-summary-form.component.html',
    styleUrls: ['./register-summary-form.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class RegisterSummaryFormComponent extends BaseForm implements OnInit, OnChanges {
    isStudentSpecial = false;
    isupdateForm = false;
    @Output() candidateTypeName = new EventEmitter();
    today = formatDate(new Date(), 'yyyy-MM-dd', 'en-US');
    @Input() updateDataForm;
    @Input() isMoney = false;
    @Input() isHidebutton = false;
    isLimit = null;
    isLimitData;
    isSubTestInfor = null;

    constructor(
        public fb: FormBuilder,
        private swSV: SweetalertService,
        public router: Router,
        public activeRoute: ActivatedRoute,
        public location: Location,
        public dialog: MatDialog,
        private cdr: ChangeDetectorRef,
        private academicsemSV: AcademicSemesterService,
        private academicYearSV: AcademicYearService,
        private testinginformationSV: TestingInformationService,
        private testingsubjectadddateSV: TestingSubjectAddDateService,
        private testingFieldSV: TestingFieldService,
        private studentSV: StudentService,
        private facultySV: FacultysService,
        private departmentSV: DepartmentService,
        private subjectSV: SubjectsService,
        private testcenterSV: TestingCenterService,
        private educationtypeSV: EducationTypesService,
        private uploadSV: UploadService,
        private checkAvRoomSV: CheckAvailableRoomService,
        private checkSubandDateSV: CheckSubjectAndDateService,
    ) {
        super(
            router,
            activeRoute,
            fb,
            location
        );
        this.form = this.fb.group({
            // status_id: null,
            // created_by: null,
            // created_datetime: null,
            // updated_by: null,
            // updated_datetime: null,
            // deleted_by: null,
            // deleted_datetime: null,
            testing_register_uid: null,
            photo1_url: null,
            photo1_name: null,
            photo2_url: null,
            photo2_name: null,
            // examinee_card: [null, [Validators.required, realCitizenIdValidator]],
            // examinee_card: [null, Validators.required],
            student_code: [null, Validators.required],
            check_student_code: null,
            examinee_full_name: [null, Validators.required],
            faculty_uid: null,
            department_name: null,
            agency_name: null,
            candidate_type_uid: [null, Validators.required],
            examinee_mobile: null,
            counter_no: null,
            counter_pin: null,
            counter_period: null,
            testing_fee: '',
            testing_information_uid: [null, Validators.required],
            payment_uid: 0,
            user_name: null,
            is_cancel: false,
            testing_subject_selecteds: this.fb.array([
                this.testing_subject_selecteds()
            ]),
        });
    }

    form;
    LimitPeriodData = [];
    imageSrc2: string;
    imageSrc1: string;
    selectfile;
    AcademicSemLists;
    AcademicYearLists;
    AcademicYearCode;
    AcademicSemCode;
    TestInformationID;
    subTestInformtionID;
    TestingInformationLists: any = [];
    newMaintestinginformationuID;
    FacultyLists: any = [];
    DepartmentLists: any = [];
    TestcenterLists: any = [];
    TestFieldLists: any = [];
    TestRoomLists: any = [];
    SubjectLists: any = [];
    EducationTypeLists: any = [];
    PeriodLists: any = [];
    PeriodListsNews: any = [];
    Daterange = {
        testing_start_datetime: null,
        testing_end_datetime: null,
    };
    chooseID = {
        idTest: null,
        startrangedayTest: null,
        endrangedayTest: null,
        isLimit: null,
        idSub: null,
        startrangedaySub: null,
        endrangedaySub: null,
    };
    queryForChecklimit = {
        testing_information_uid: null,
        subject_uid: null,
        testing_date: null,
        subject_code: null,
        testing_subject_uid: null,
    };
    Lists;
    daywithout2 = [];
    @Input() userData: any = [];
    @Input() studentData: any = [];
    @Output() onConfirm = new EventEmitter<any>();
    @Output() delete = new EventEmitter();
    myFilter = (d: Date): boolean => {
        if (this.daywithout2.length != 0) {
            const time = d.getTime();
            return !this.daywithout2.find(x => x.getTime() === time);
        } else {
            return !this.daywithout2.find(x => x.getTime() === null);
        }

    }

    testing_subject_selecteds() {
        return this.fb.group({
            testing_subject_selected_uid: null,
            testing_register_uid: null,
            testing_center_uid: [null, Validators.required],
            is_main: true,
            subject_uid: [null, Validators.required],
            subject_code: [null, Validators.required],
            testing_datetime: [null, Validators.required],
            period_id: [null, Validators.required],
            branch_uid: [null, Validators.required],
            testing_field_uid: [null, Validators.required],
            testing_seat: null,
            is_cancel: false
        });
    }

    ngOnInit(): void {
        // console.log(this.studentData);
        // this.form.disable();
        this.academicsemSV.getAll().subscribe(
            result => {
                this.AcademicSemLists = result;
                this.cdr.detectChanges();
            }
        );
        this.academicYearSV.getAll().subscribe(
            result => {
                this.AcademicYearLists = result;
                this.cdr.detectChanges();
            }
        );
        this.facultySV.getAll().subscribe(
            result => {
                this.FacultyLists = result;
                this.cdr.detectChanges();
            }
        );
        this.testinginformationSV.getDatatype().subscribe(
            result => {
                const data: any = result;
                data.splice(data.findIndex(e => e.candidate_type_name_th === 'นักศึกษา'), 1);
                this.EducationTypeLists = data;
                this.cdr.detectChanges();
            }
        );
    }

    ngOnChanges() {
        if (this.userData !== '') {
            console.log(this.userData);
            this.form.get('counter_no').setValue(this.userData.counter_no);
            this.form.get('counter_pin').setValue(this.userData.counter_pin);
            this.form.get('counter_period').setValue(this.userData.counter_periods[0].period);
        }
        console.log(this.studentData);
        if (this.studentData != null) {
            this.setInformationbyStudentData(this.studentData.allow_register);
            this.form.get('student_code').setValue(this.studentData.student_code);
            this.form.get('examinee_full_name').setValue(this.studentData.student_name_th);
            this.form.get('examinee_mobile').setValue(this.studentData.mobile_no);
            this.form.get('department_name').setValue(this.studentData.major_name_th);
        }
        this.cdr.detectChanges();
    }

    add(index) {
        const form = this.form.get('testing_subject_selecteds') as FormArray;
        const TestInforUid = this.form.get('testing_information_uid').value;
        // const FormarraySelect = form.at(index).value;
        // const indexSec = this.sectionsFake.findIndex((x) => {
        //   return x.period_id === FormarraySelect.period_id;
        // });
        // this.sectionsFake[indexSec].is_check = false;
        this.testinginformationSV.get(this.chooseID.idTest).pipe(
            tap(x => {
                const subjectlist: any = x;
                this.TestcenterLists.push(subjectlist.testing_rooms.reduce((unique, o) => {
                    if (!unique.some(obj => obj.branch_uid === o.branch_uid)) {
                        unique.push(o);
                    }
                    return unique;
                }, []))
                this.TestFieldLists.push(subjectlist.testing_rooms.reduce((unique, o) => {
                    if (!unique.some(obj => obj.testing_field_uid === o.testing_field_uid)) {
                        unique.push(o);
                    }
                    return unique;
                }, []))
            }),
        ).subscribe();

        form.push(this.testing_subject_selecteds());
    }

    removeArray(i) {
        const form = this.form.get('testing_subject_selecteds') as FormArray;
        const Form = this.form.getRawValue();
        const Formarray2 = form.at(i) as FormGroup;
        const FormarraySelect = form.at(i).value;
        console.log(FormarraySelect)
        if (FormarraySelect.subject_uid != null) {
            const foundIndex = this.SubjectLists.findIndex(x => x.subject_uid === FormarraySelect.subject_uid);
            this.SubjectLists[foundIndex].status_id = true
            const filteredList = this.PeriodLists;
            this.PeriodListsNews[i] = filteredList;
            const array = this.PeriodListsNews;
            const firstIndex = i;
        }
        this.testinginformationSV.get(this.chooseID.idTest).pipe(
            tap(x => {
                const data: any = x;
                this.TestcenterLists[i] = data.testing_rooms.reduce((unique, o) => {
                    if (!unique.some(obj => obj.branch_uid === o.branch_uid)) {
                        unique.push(o);
                    }
                    return unique;
                }, []);
                this.TestFieldLists[i] = data.testing_rooms.reduce((unique, o) => {
                    if (!unique.some(obj => obj.testing_field_uid === o.testing_field_uid)) {
                        unique.push(o);
                    }
                    return unique;
                }, []);
            }),
        ).subscribe();
        form.removeAt(i);
        this.cdr.detectChanges();
    }

    onDelete(id) {
        this.delete.emit(id);
    }

    confirm(status) {
        switch (status) {
            case true: {
                console.log('confirm');
                this.isHidebutton = true;
                // this.onConfirm.emit({'this.form','any'});
                this.onConfirm.emit({form: this.form.getRawValue(), status});
                break;
            }
            case false: {
                this.isHidebutton = false;
                this.cdr.detectChanges()
                console.log('cancel');
                break;
            }
            case 'reset': {
                this.form.reset();
                if (this.userData !== '') {
                    console.log(this.userData);
                    this.isHidebutton = false;
                    this.form.get('counter_no').setValue(this.userData.counter_no);
                    this.form.get('counter_pin').setValue(this.userData.counter_pin);
                    this.form.get('counter_period').setValue(this.userData.counter_periods[0].period);
                    const form = this.form.get('testing_subject_selecteds') as FormArray;
                    this.imageSrc1 = null;
                    this.imageSrc2 = null;
                    form.clear();
                    form.push(this.testing_subject_selecteds())
                    this.TestcenterLists = [];
                    this.TestFieldLists = [];
                    this.SubjectLists = [];
                    this.cdr.detectChanges()
                } else {
                    this.swSV.error('กรุณาล็อคอินใหม่');
                }
                // this.form.get('user_name').setValue(this.userData.user_name);
                this.isHidebutton = false;
                this.cdr.detectChanges();
                break;
            }
            case 'update': {
                console.log('update');
                this.isHidebutton = true;
                this.onConfirm.emit({form: this.form.getRawValue(), status});
                break;
            }
            default: {
                console.log('FAIL');
                break;
            }
        }
    }

    updateForm(FormResult) {
        this.form.get('testing_register_uid').setValue(FormResult.testing_register_uid);
        const PresentForm = this.form.getRawValue();
        const Formarray = this.form.get('testing_subject_selecteds') as FormArray;
        let NewForm = [];
        NewForm = FormResult.testing_subject_selecteds.filter(x => {
            return !!PresentForm.testing_subject_selecteds.map((y, index) => {
                if (x.subject_uid === y.subject_uid) {
                    x.formindex = index
                    y.testing_subject_selected_uid = x.testing_subject_selected_uid;
                    y.testing_seat = x.testing_seat;
                    x.testing_register_uid = FormResult.testing_register_uid;
                    return x;
                }
            });
        });
        if (NewForm.length != 0) {
            for (let i = 0; i < NewForm.length; i++) {
                Formarray.at(NewForm[i].formindex).get('testing_subject_selected_uid').setValue(NewForm[i].testing_subject_selected_uid);
                Formarray.at(NewForm[i].formindex).get('testing_register_uid').setValue(NewForm[i].testing_register_uid);
                Formarray.at(NewForm[i].formindex).get('testing_seat').setValue(NewForm[i].testing_seat);
            }
        }
    }

    setDepartment(data) {
        this.departmentSV.query(`?faculty_uid=${data}`).subscribe(
            result => {
                this.DepartmentLists = result;
            }
        );
    }

    setYearSem(data) {
        // console.log(data);
        // console.log(this.studentData);
        this.SubjectLists = [];
        this.TestcenterLists = [];
        this.TestFieldLists = [];
        this.PeriodListsNews = [];
        this.PeriodLists = [];
        this.daywithout2 = [];
        this.TestInformationID = data;
        let subMain: any = [];
        this.newMaintestinginformationuID = null;
        const form = this.form.get('testing_subject_selecteds') as FormArray;
        form.clear()
        form.push(this.testing_subject_selecteds());
        this.testinginformationSV.get(data).pipe(
            tap(x => {
                // for (let i = 0; i < form.getRawValue().length; i++) {
                //   form.at(i).get('branch_uid').setValue(null);
                //   form.at(i).get('testing_field_uid').setValue(null);
                // }
                console.log('เตรียม PeriodLists')
                const data: any = x;
                this.PeriodLists = data.testing_periods;
                for (let i = 0; i < this.PeriodLists.length; i++) {
                    this.PeriodLists[i].status_id = true;
                }
            }),
            tap(x => {
                console.log('เตรียม PeriodListsNews')
                let ArrayTest = [];
                const data: any = x;
                for (let i = 0; i < data.testing_subjects.length; i++) {
                    this.PeriodListsNews.push(this.PeriodLists);
                    // Array1 = [...Array1 , ...this.PeriodLists]
                }
                // const myClonedArray  = Object.assign([], ArrayTest);
            }),
            tap(x => {
                console.log('เตรียม วันห้ามสอบ')
                const data: any = x;
                if (data.days_without_testings.length !== 0) {
                    // this.daywithout2 = [];
                    for (let i = 0; i < data.days_without_testings.length; i++) {
                        const newDate = formatDate(data.days_without_testings[i].date_without_testing, 'M/d/yy', 'en-US');
                        const FilterDate = new Date(newDate);
                        this.daywithout2.push(FilterDate);
                        console.log(this.daywithout2);
                        this.cdr.detectChanges();
                    }
                }
            }),
            tap(x => {
                // เช็คว่าโครงการที่เลือกอันนี้เป็นรอบสอบหลัก หรือ รอบสอบขยาย
                console.log('เช็คว่าโครงการที่เลือกอันนี้เป็นรอบสอบหลัก หรือ รอบสอบขยาย')
                const subjectlist: any = x;
                if (subjectlist.main_testing_information_uid === null) {
                    this.chooseID.idTest = subjectlist.testing_information_uid;
                    this.chooseID.startrangedayTest = this.formatDate(subjectlist.testing_start_datetime);
                    this.chooseID.endrangedayTest = this.formatDate(subjectlist.testing_end_datetime);
                    this.SubjectLists = subjectlist.testing_subjects;
                    for (let i = 0; i < this.SubjectLists.length; i++) {
                        this.SubjectLists[i].status_id = true;
                    }
                    this.Daterange.testing_start_datetime = this.formatDate(subjectlist.testing_start_datetime);
                    this.Daterange.testing_end_datetime = this.formatDate(subjectlist.testing_end_datetime);
                    this.cdr.detectChanges();
                    this.AcademicYearCode = subjectlist;
                }
            }),
            tap(x => {
                // เช็คว่าโครงการที่เลือกอันนี้เป็นรอบสอบหลัก หรือ รอบสอบขยาย
                console.log('เตรียมสถานที่สอบ')

                const subjectlist: any = x;
                // นำข้อมูล สถานที่สอบมาใส่ใน Fill
                // this.TestcenterLists = subjectlist.testing_rooms;
                // this.TestcenterLists.push(subjectlist.testing_rooms);
                // this.TestFieldLists = subjectlist.testing_rooms.reduce((unique, o) => {
                //   if (!unique.some(obj => obj.testing_field_uid === o.testing_field_uid)) {
                //     console.log(o)
                //     unique.push(o);
                //   }
                //   return unique;
                // }, []);
                if (this.TestcenterLists.length == 0) {
                    this.TestcenterLists.push(subjectlist.testing_rooms.reduce((unique, o) => {
                        if (!unique.some(obj => obj.branch_uid === o.branch_uid)) {
                            unique.push(o);
                        }
                        return unique;
                    }, []))
                }
                // if (this.TestFieldLists.length == 0){
                //   this.TestFieldLists.push(subjectlist.testing_rooms.reduce((unique, o) => {
                //     if (!unique.some(obj => obj.testing_field_uid === o.testing_field_uid)) {
                //       unique.push(o);
                //     }
                //     return unique;
                //   }, []))
                // }
                // this.TestRoomLists = subjectlist.testing_rooms;
                // this.TestRoomLists.push(subjectlist.testing_rooms);
                // this.TestcenterLists = this.TestcenterLists.reduce((unique, o) => {
                //   if (!unique.some(obj => obj.branch_uid === o.branch_uid)) {
                //     unique.push(o);
                //   }
                //   return unique;
                // }, []);

            }),
            tap(x => {
                console.log(6)

                // นำข้อมูล Student ที่ Import มาขัดตามวิชาที่อนุญาต
                if (this.studentData !== null) {
                    this.SubjectLists = this.SubjectLists.filter(item1 =>
                        !!this.studentData.allow_register.find(item2 => item1.subject_code === item2.subject_code)
                    );
                }
                if (this.SubjectLists.length === 1) {
                    form.patchValue([
                        {subject_uid: this.SubjectLists[0].subject_uid,},
                    ]);
                }
            }),
            tap(x => {
                console.log(7)
                // นำข้อมูล Student ที่ Import มาขัดตามวิชาที่อนุญาต
                if (this.studentData !== null) {
                    this.SubjectLists = this.SubjectLists.filter(item1 =>
                        !!this.studentData.allow_register.find(item2 => item1.subject_code === item2.subject_code)
                    );
                }
                if (this.SubjectLists.length === 1) {
                    form.patchValue([
                        {subject_uid: this.SubjectLists[0].subject_uid,},
                    ]);
                }
            }),
            tap(x => {
                // Check มีรอบสอบที่เลือกมีรอบสอบขยายหรือเปล่า
                console.log(8)
                this.testinginformationSV.getCheckmaintrue(data).subscribe(
                    result => {
                        subMain = result;
                        this.newMaintestinginformationuID = subMain[0];
                        // มีรอบสอบขยาย
                        if (subMain.length !== 0) {
                            this.chooseID.idSub = subMain[0].testing_information_uid;
                            this.chooseID.startrangedaySub = this.formatDate(subMain[0].testing_start_datetime);
                            this.chooseID.endrangedaySub = this.formatDate(subMain[0].testing_end_datetime);
                            this.Daterange.testing_end_datetime = this.chooseID.endrangedaySub;
                            this.cdr.detectChanges();
                        }
                    }
                );
            }),
        ).subscribe();
        this.cdr.detectChanges();
    }

    filterbystudentData(subjectlist) {
        const filterSubject = this.studentData.allow_register;
        console.log(filterSubject);
        console.log(subjectlist);
        return subjectlist.filter(x => filterSubject.some(y => y.subject_code === x.subject_code));
        // return subjectfiltered;
    }

    setregisterdataForm(data) {
        console.log(data);
        console.log(this.TestcenterLists);
        this.testcenterSV.get(data).subscribe(
            result => {
                console.log(result);
                this.PeriodLists = result;
                // this.testingFieldSV.getAll().subscribe(
                //   result => {
                //     console.log(result);
                //     this.TestFieldLists = result;
                //     this.cdr.detectChanges();
                //   }
                // );
            }
        );
    }

    setSection(data, index) {
        const Form = this.form.getRawValue();
        const Formarray = this.form.get('testing_subject_selecteds') as FormArray;
        const Formarray2 = Formarray.at(index) as FormGroup;
        const FormarraySelect = Formarray.at(index).value;
        FormarraySelect.testing_information_uid = Form.testing_information_uid;
        FormarraySelect.testing_datetime = this.formatDate(FormarraySelect.testing_datetime);
        this.checkAvRoomSV.add(FormarraySelect).subscribe(
            result => {
                Formarray2.get('testing_center_uid').setValue(result[0].testing_center_uid);
                this.swSV.success('ค้นหาห้องพบ');
            },
            error => {
                this.swSV.errTextandSub('ห้องสอบเต็ม', 'กรุณาเลือกวันสอบหรือ Section อื่น');

            }
        );
    }

    setInformationbyStudentData(data) {
        this.TestingInformationLists = this.TestingInformationLists.filter(item1 =>
            !!data.find(item2 => item1.academic_year_code === item2.academic_year)
        );
    }

    checkavailableroom(index: any) {
        let DoFloat = null;
        const Form = this.form.getRawValue();
        const Formarray = this.form.get('testing_subject_selecteds') as FormArray;
        const Formarray2 = Formarray.at(index) as FormGroup;
        const FormarraySelect = Formarray2.getRawValue();
        if (Form.testing_information_uid != null) {
            DoFloat = this.checkSameDayandPeriod(index);
            console.log(DoFloat);
            if (DoFloat === true) {
                if (FormarraySelect.testing_datetime == null) {
                    console.log('กรุณาเลือกวันที่1')

                    return this.swSV.error('กรุณาเลือกวันที่');
                } else {
                    if (FormarraySelect.period_id != null) {
                        if (FormarraySelect.is_main === true) {
                            FormarraySelect.testing_information_uid = this.chooseID.idTest;
                        } else {
                            FormarraySelect.testing_information_uid = this.chooseID.idSub;
                        }
                        FormarraySelect.testing_datetime = this.formatDate(FormarraySelect.testing_datetime);
                        console.log(FormarraySelect);
                        if (FormarraySelect.testing_datetime !== null) {
                            this.checkAvRoomSV.add(FormarraySelect).subscribe(
                                result => {
                                    const responData: any = result;
                                    if (responData.length !== 0) {
                                        Formarray2.get('testing_center_uid').setValue(responData[0].testing_center_uid);
                                        // this.swSV.success('ค้นหาห้องพบ').pi;
                                        this.swSV.successThen('ค้นหาห้องพบ').pipe(
                                            filter(x => x.isConfirmed),
                                            concatMap(async (x) => {
                                                this.checkSubandDateSV.add(this.form.getRawValue()).pipe(
                                                    catchError(err => {
                                                        console.log('ERR')
                                                        console.log(err)
                                                        this.swSV.errText(err.error);
                                                        const foundIndex = this.SubjectLists.findIndex(x => x.subject_uid === FormarraySelect.subject_uid);
                                                        this.SubjectLists[foundIndex].status_id = true
                                                        const backupIsmain = Formarray2.get('is_main').value;
                                                        Formarray2.reset();
                                                        Formarray2.get('is_main').setValue(backupIsmain);
                                                        return throwError(err);
                                                    })
                                                ).subscribe();
                                                // this.swSV.success('AFA')
                                            })
                                        ).subscribe();
                                    } else {
                                        Formarray2.get('period_id').setValue(null);
                                        this.swSV.errTextandSub('ห้องสอบเต็ม', 'กรุณาเลือกวันสอบหรือ Section อื่น');

                                    }
                                },
                                error => {
                                    console.log(error)
                                    this.swSV.errTextandSub('ห้องสอบเต็ม', 'กรุณาเลือกวันสอบหรือ Section อื่น');
                                }
                            );
                        } else {
                            console.log('กรุณาเลือกวันที่2')

                            return this.swSV.errorBig('กรุณาเลือกวันที่');
                        }
                    }
                }
            } else {
                Formarray2.get('period_id').setValue(null);
                return this.swSV.errorBig('มีวันที่สอบกับSection ซ้ำกัน');

            }
        }

    }

    checkSameDayandPeriod(index) {
        const Formarray = this.form.get('testing_subject_selecteds') as FormArray;
        const Data = Formarray.getRawValue();
        let arr = Formarray.getRawValue();
        arr = arr.filter(x => {
            if (x.testing_datetime !== null && x.period_id !== null) {
                return x
            }
        })
        return this.checkDuplicate2(arr);
    }

    checkDuplicate2(arr) {
        const isDupicate = arr.map((value) => {
            if (value.testing_datetime != null && value.period_id != null) {
                return value.testing_datetime.getTime() + value.period_id;
            }
        }).some((value, index, array) => {
            return array.indexOf(value) !== array.lastIndexOf(value);
        });
        return !isDupicate;
    }

    checkDuplicate(arr) {
        const checkDuplicate = (array) => {
            return array
                .map((value) => {
                    console.log(value)

                    // console.log("value: ", value.testing_datetime.getTime() + value.period_id);
                    if (value.testing_datetime != null && value.period_id != null) {
                        console.log(value.testing_datetime.getTime() + value.period_id)

                        return value.testing_datetime.getTime() + value.period_id;
                    } else {
                        console.log(value)
                        return 'FAIL'
                    }
                })
                .some((value, index, array) => {
                    // console.log("value: ", value);
                    // console.log("Array: ", array);
                    // console.log("A: ", array.indexOf(value));
                    // console.log("B: ", array.lastIndexOf(value));
                    return array.indexOf(value) !== array.lastIndexOf(value);
                });
        };
        // console.log("checkDuplicate: ", checkDuplicate(arr));
        console.log('checkDuplicate: ', checkDuplicate(arr));
        return !checkDuplicate;
    }


    switchTestInfor(data, index) {
        const Formarray = this.form.get('testing_subject_selecteds') as FormArray;
        const Formarray2 = Formarray.at(index) as FormGroup;
        const FormarraySelect = Formarray2.getRawValue();
        console.log(Formarray2.getRawValue());
        console.log(this.chooseID);

    }

    // เช็คว่ามีการ Limit Period หรือเปล่า
    checkIsLimit(date, index) {
        const Form = this.form.getRawValue();
        const Formarray = this.form.get('testing_subject_selecteds') as FormArray;
        const Formarray2 = Formarray.at(index) as FormGroup;
        const SubjectCode = Formarray2.get('subject_code').value;
        const testInforUid = Form.testing_information_uid;
        const result = new Subject<any>();
        this.testingsubjectadddateSV.FindLimitPeriod(testInforUid, date, SubjectCode).subscribe(
            res => {
                if (res) {
                    const data: any = res
                    if (data.length !== 0) {
                        this.isLimit = true
                    } else {
                        this.isLimit = false
                        this.PeriodListsNews[index] = this.PeriodLists
                    }
                    result.next(res)
                }
            }
        );
        return result.asObservable();
    }

    compareIsLimitandIsChoose(index, dateselect) {
        let newArray = [];
        const firstIndex = index;
        const Formarray = this.form.get('testing_subject_selecteds') as FormArray;
        // console.log(this.PeriodListsNews[index][0].status_id)
        // มีวิชาที่จำกัด
        if (this.isLimit && this.chooseID.idSub !== null) {
            console.log('มีวิชาที่จำกัดแต่มีรอบสอบขยาย');
            if (this.chooseID.idSub !== null) {
                const d1 = this.chooseID.startrangedayTest.split('-');
                const d2 = this.chooseID.endrangedayTest.split('-');
                const s1 = this.chooseID.startrangedaySub.split('-');
                const s2 = this.chooseID.endrangedaySub.split('-');
                const c = dateselect.split('-');
                const from = new Date(d1[0], parseInt(d1[1]) - 1, d1[2]);  // -1 because months are from 0 to 11
                const to = new Date(d2[0], parseInt(d2[1]) - 1, d2[2]);
                const fromsub = new Date(s1[0], parseInt(s1[1]) - 1, s1[2]);  // -1 because months are from 0 to 11
                const tosub = new Date(s2[0], parseInt(s2[1]) - 1, s2[2]);
                const check = new Date(c[0], parseInt(c[1]) - 1, c[2]);
                console.log(check > from && check < to);
                console.log(check > fromsub && check < tosub);
                // ไม่อยู่ในช่วงขยาย
                if (check >= from && check <= to) {
                    console.log(check >= from && check <= to);
                } else if (check >= fromsub && check <= tosub) {
                    console.log(check >= fromsub && check <= tosub);
                    this.testinginformationSV.getAll().subscribe(
                        result => {
                            this.TestingInformationLists = result;
                            this.TestingInformationLists = this.TestingInformationLists.filter((x) => {
                                return x.is_main === false;
                            });
                        }
                    );

                    this.testinginformationSV.get(this.chooseID.idSub).pipe(
                        tap(x => {
                            Formarray.at(index).get('is_main').setValue(false);
                            Formarray.at(index).get('branch_uid').setValue(null);
                            Formarray.at(index).get('testing_field_uid').setValue(null);
                        }),
                        tap(x => {
                            const Testinfordata: any = x;
                            // this.TestcenterLists[index] = Testinfordata.testing_rooms
                            this.TestcenterLists[index] = Testinfordata.testing_rooms.reduce((unique, o) => {
                                if (!unique.some(obj => obj.branch_uid === o.branch_uid)) {
                                    unique.push(o);
                                }
                                return unique;
                            }, [])
                            this.TestFieldLists[index] = Testinfordata.testing_rooms.reduce((unique, o) => {
                                if (!unique.some(obj => obj.branch_uid === o.branch_uid)) {
                                    unique.push(o);
                                }
                                return unique;
                            }, [])
                            this.cdr.detectChanges()

                        })
                    ).subscribe();
                    this.form.get('testing_information_uid').setValue(this.chooseID.idSub);
                    this.cdr.detectChanges();
                }
            }
            if (this.isLimit) {
                const filteredList = this.PeriodLists.filter(item1 =>
                    !!this.isLimitData[0].period.find(item2 => item1.period_id === item2)
                );
                this.PeriodListsNews[index] = filteredList;
            }


        } else if (!this.isLimit && this.chooseID.idSub !== null) {
            console.log('ไม่มีวิชาที่จำกัดแต่มีรอบสอบขยาย');
            if (this.chooseID.idSub !== null) {
                const d1 = this.chooseID.startrangedayTest.split('-');
                const d2 = this.chooseID.endrangedayTest.split('-');
                const s1 = this.chooseID.startrangedaySub.split('-');
                const s2 = this.chooseID.endrangedaySub.split('-');
                const c = dateselect.split('-');
                const from = new Date(d1[0], parseInt(d1[1]) - 1, d1[2]);  // -1 because months are from 0 to 11
                const to = new Date(d2[0], parseInt(d2[1]) - 1, d2[2]);
                const fromsub = new Date(s1[0], parseInt(s1[1]) - 1, s1[2]);  // -1 because months are from 0 to 11
                const tosub = new Date(s2[0], parseInt(s2[1]) - 1, s2[2]);
                const check = new Date(c[0], parseInt(c[1]) - 1, c[2]);
                console.log(check > from && check < to);
                console.log(check > fromsub && check < tosub);
                // ไม่อยู่ในช่วงขยาย
                if (check >= from && check <= to) {
                    console.log(check >= from && check <= to);
                } else if (check >= fromsub && check <= tosub) {
                    console.log(check >= fromsub && check <= tosub);
                    this.testinginformationSV.getAll().subscribe(
                        result => {
                            this.TestingInformationLists = result;
                            this.TestingInformationLists = this.TestingInformationLists.filter((x) => {
                                return x.is_main === false;
                            });
                        }
                    );
                    this.testinginformationSV.get(this.chooseID.idSub).pipe(
                        tap(x => {
                            Formarray.at(index).get('is_main').setValue(false);
                            Formarray.at(index).get('branch_uid').setValue(null);
                            Formarray.at(index).get('testing_field_uid').setValue(null);
                        }),
                        tap(x => {
                            const Testinfordata: any = x;
                            // this.TestcenterLists[index] = Testinfordata.testing_rooms
                            this.TestcenterLists[index] = Testinfordata.testing_rooms.reduce((unique, o) => {
                                if (!unique.some(obj => obj.branch_uid === o.branch_uid)) {
                                    unique.push(o);
                                }
                                return unique;
                            }, [])
                            this.TestFieldLists[index] = Testinfordata.testing_rooms.reduce((unique, o) => {
                                if (!unique.some(obj => obj.branch_uid === o.branch_uid)) {
                                    unique.push(o);
                                }
                                return unique;
                            }, [])
                            this.cdr.detectChanges()

                        })
                    ).subscribe()
                    this.form.get('testing_information_uid').setValue(this.chooseID.idSub);
                    this.cdr.detectChanges()
                }
            }
            console.log(this.isLimitData[0]);
            if (this.isLimit) {
                const filteredList = this.PeriodLists.filter(item1 =>
                    !!this.isLimitData[0].period.find(item2 => item1.period_id === item2)
                );
                this.PeriodListsNews[index] = filteredList;
            }
            this.cdr.detectChanges()
        } else if (this.isLimit && !this.chooseID.idSub !== null) {
            console.log('มีวิชาที่จำกัดและไม่มีรอบสอบขยาย');
            const ArrayindexNotFound = [];
            const filteredList = this.PeriodLists.filter(item1 =>
                !!this.isLimitData[0].period.find(item2 => item1.period_id === item2)
            );
            this.PeriodListsNews[index] = filteredList;
            this.cdr.detectChanges()
        }
    }

    async newChooseDate(date, index) {
        if (this.form.get('testing_information_uid').value != null) {
            console.log(date, index);

            const Form = this.form.getRawValue();
            const Formarray = this.form.get('testing_subject_selecteds') as FormArray;
            const Formarray2 = Formarray.at(index) as FormGroup;
            console.log(Formarray2)
            console.log(Formarray2.get('subject_uid').value);
            if (Formarray2.get('testing_datetime').value != null && Formarray2.get('period_id').value != null) {
                Formarray2.get('period_id').setValue(null);
            }
            const subjectcode = Formarray2.get('subject_code').value;
            this.isLimitData = null;
            const isDateSelect = this.formatDate(date);
            await this.checkIsLimit(isDateSelect, index).subscribe(
                res => {
                    this.isLimitData = res
                    // let isFoundSubject = false;
                    // isFoundSubject = this.isLimitData.some((member) => {
                    //   return member.subject_code === subjectcode;
                    // })
                    // console.log(isFoundSubject)
                    this.compareIsLimitandIsChoose(index, isDateSelect)
                }
            );
            // await this.compareIsLimitandIsChoose()
        }


    }

    chooseidDate(data, index) {
        const Form = this.form.getRawValue();
        const Formarray = this.form.get('testing_subject_selecteds') as FormArray;
        const Formarray2 = Formarray.at(index) as FormGroup;
        const SubjectCode = Formarray2.get('subject_code').value;
        const FormarraySelect = Formarray2.getRawValue();
        console.log(FormarraySelect);
        console.log(data);
        const testInforUid = Form.testing_information_uid;
        data = this.formatDate(data);
        // this.queryForChecklimit.testing_date = data
        // this.queryForChecklimit.testing_information_uid = testInforUid
        // const query = this.createQueryStringFromObject(this.queryForChecklimit)
        const queryPeriodLimitFound: any = [];
        // this.testingsubjectadddateSV.FindLimitPeriod(testInforUid, data).pipe(
        //   tap(x => {
        //     queryPeriodLimitFound = x;
        //     console.log(x);
        //     if (queryPeriodLimitFound.length !== 0){
        //       isLimit = true;
        //     }
        //   })
        // ).subscribe();
        const dateSubjectadd = this.testingsubjectadddateSV.FindLimitPeriod(testInforUid, data, SubjectCode).toPromise();
        console.log(dateSubjectadd);
        console.log(queryPeriodLimitFound);

        // ตรวจสอบวันที่ว่าอยู่ในรอบขยายหรือเปล่า
        if (this.chooseID.idSub !== null) {
            const d1 = this.chooseID.startrangedayTest.split('-');
            const d2 = this.chooseID.endrangedayTest.split('-');
            const s1 = this.chooseID.startrangedaySub.split('-');
            const s2 = this.chooseID.endrangedaySub.split('-');
            const c = data.split('-');
            const from = new Date(d1[0], parseInt(d1[1]) - 1, d1[2]);  // -1 because months are from 0 to 11
            const to = new Date(d2[0], parseInt(d2[1]) - 1, d2[2]);
            const fromsub = new Date(s1[0], parseInt(s1[1]) - 1, s1[2]);  // -1 because months are from 0 to 11
            const tosub = new Date(s2[0], parseInt(s2[1]) - 1, s2[2]);
            const check = new Date(c[0], parseInt(c[1]) - 1, c[2]);
            console.log(check > from && check < to);
            console.log(check > fromsub && check < tosub);
            // ไม่อยู่ในช่วงขยาย
            if (check >= from && check <= to) {
                console.log(check >= from && check <= to);
                // this.form.get('testing_information_uid').setValue(this.chooseID.idTest);
                // this.testinginformationSV.getAll().subscribe(
                //   result => {
                //     this.TestingInformationLists = result;
                //     this.TestingInformationLists = this.TestingInformationLists.filter((x) => {
                //       return x.is_main === true;
                //     });
                //   }
                // );
                // อยู่ในช่วงขยาย
            } else if (check >= fromsub && check <= tosub) {
                console.log(check >= fromsub && check <= tosub);
                this.testinginformationSV.getAll().subscribe(
                    result => {
                        this.TestingInformationLists = result;
                        this.TestingInformationLists = this.TestingInformationLists.filter((x) => {
                            return x.is_main === false;
                        });
                    }
                );
                this.form.get('testing_information_uid').setValue(this.chooseID.idSub);
            }
        }
        if (FormarraySelect.period_id != null) {
            Formarray2.get('period_id').setValue(null);
        }
    }

    chcekPeriodLimit(date, testingInforUid, SubjectUid) {
        this.queryForChecklimit.testing_date = date;
        this.queryForChecklimit.testing_information_uid = testingInforUid;
        this.queryForChecklimit.subject_uid = SubjectUid;
        const query = this.createQueryStringFromObject(this.queryForChecklimit);
        this.testingsubjectadddateSV.search(`?${query}`).pipe(
            tap(x => {
                console.log(x);
            })
        ).subscribe();
    }

    openPreview(id: any): void {
        // let obj = this.buffer2
        console.log(id);
        const dialogRef = this.dialog.open(PreviewImageComponent, {
            panelClass: 'custom-dialog-container',
            width: '70%',
            height: '70%',
            data: id

        });

    }

    onFileChanged(event, photoChoose) {
        const file = event.target.files[0];
        if (photoChoose === 1) {
            if (event.target.files && event.target.files[0]) {
                this.selectfile = event.target.files[0];
                const formData: FormData = new FormData();
                formData.append('filecard', this.selectfile, this.selectfile.name);
                this.uploadSV.add(formData).pipe(
                    tap((x: any) => this.form.get('photo1_url').setValue(x[0].file_name)),
                    tap((x: any) => this.imageSrc1 = x[0].file_name),
                    tap((x: any) => this.form.get('photo1_name').setValue(x[0].name)),
                    tap(x => this.cdr.detectChanges()),
                ).subscribe();
            }
        } else if (photoChoose === 2) {
            if (event.target.files && event.target.files[0]) {
                this.selectfile = event.target.files[0];
                const formData: FormData = new FormData();
                formData.append('fileConfirm', this.selectfile, this.selectfile.name);
                this.uploadSV.add(formData).pipe(
                    tap((x: any) => this.form.get('photo2_url').setValue(x[0].file_name)),
                    tap((x: any) => this.imageSrc2 = x[0].file_name),
                    tap((x: any) => this.form.get('photo2_name').setValue(x[0].name)),
                    tap(x => this.cdr.detectChanges()),
                ).subscribe();
            }
        }
    }

    DeleteImage(photoChoose) {
        if (photoChoose === 1) {
            this.form.get('photo1_url').setValue(null)
            this.imageSrc1 = null;
            this.form.get('photo1_name').setValue(null)
        } else if (photoChoose === 2) {
            this.form.get('photo2_url').setValue(null)
            this.imageSrc2 = null;
            this.form.get('photo2_name').setValue(null)
        }
    }

    onUpload() {
        // upload code goes here
    }

    clearChooseID() {
        this.chooseID = {
            idTest: null,
            startrangedayTest: null,
            endrangedayTest: null,
            isLimit: null,
            idSub: null,
            startrangedaySub: null,
            endrangedaySub: null,
        };
    }

    setInformation(data) {
        this.clearChooseID();
        let search = '';
        if (data === '6dff8faf-0b30-4fb1-8274-42df8debe8a0') {
            search = 'นักศึกษา';
        } else if (data === 'd056ba6d-5a15-4df6-ade0-c9e8c239d1b1') {
            search = 'บุคคลทั่วไป';
        } else if (data === '5fc44678-8f36-41f6-b0e5-0901ea2231b4') {
            search = 'นักศึกษาโครงการพิเศษ';
        }
        this.candidateTypeName.emit(search);
        // const Detail  = this.userData.details;
        // this.confirm('reset');
        this.testinginformationSV.querytypeofexamineeUid(data).subscribe(
            res => {
                this.TestingInformationLists = res;
                this.TestingInformationLists = this.TestingInformationLists.filter((x) => {
                    return x.is_main === true;
                });
                // if (Detail.length != 0){
                //   this.TestingInformationLists = this.TestingInformationLists.filter((el) => {
                //     return Detail.some((f) => {
                //       return f.testing_information_uid === el.testing_information_uid;
                //     });
                //   });
                // }
                this.form.get('check_student_code').reset();
                this.form.get('testing_information_uid').reset();
                this.form.get('photo1_name').reset();
                this.form.get('photo2_name').reset();
                this.form.get('student_code').reset();
                this.form.get('examinee_full_name').reset();
                this.form.get('faculty_uid').reset();
                this.form.get('department_name').reset();
                this.form.get('agency_name').reset();
                this.form.get('examinee_mobile').reset();
                this.form.get('agency_name').reset();
                const form = this.form.get('testing_subject_selecteds') as FormArray;
                this.imageSrc1 = null;
                this.imageSrc2 = null;
                form.clear();
                form.push(this.testing_subject_selecteds());
                this.cdr.detectChanges();
            }
        );
    }

    filterSubject(subjectId, index) {
        const form = this.form.get('testing_subject_selecteds') as FormArray;
        const Formarray2 = form.at(index) as FormGroup;
        this.subjectSV.get(subjectId).pipe(
            tap(x => {
                const data: any = x;
                Formarray2.get('subject_code').setValue(data.subject_code);
            })
        ).subscribe();
        const subjectUidArray = [];
        for (let i = 0; i < form.getRawValue().length; i++) {
            if (form.at(i).get('subject_uid').value != null) {
                subjectUidArray.push(form.at(i).get('subject_uid').value)
            }
        }
        if (subjectUidArray.length !== 0) {
            let NewSubjectLists = this.SubjectLists.map((x) => {
                x.status_id = true
                return x
            });
            console.log(NewSubjectLists);
            for (let i = 0; i < subjectUidArray.length; i++) {
                NewSubjectLists = this.SubjectLists.map((x) => {
                    if (x.subject_uid === subjectUidArray[i])
                        x.status_id = false
                    return x
                });
            }
            this.SubjectLists = NewSubjectLists;
        }

        // const filteredList = this.SubjectLists
        //   .filter((x) => {
        //     return !!subjectUidArray.find(y => x.subject_uid === y)
        // }).map((x) => {
        //     console.log(x)
        //     x.status_id = false;
        //     return x
        //   }
        // );
        // console.log(filteredList);

        // Formarray2.get('subject_code') =
        // cost subjectSelect =

        // const foundIndex = this.SubjectLists.findIndex(x => x.subject_uid === subjectId);
        // this.SubjectLists[foundIndex].status_id = false;
    }

    checkStudent() {
        const testInforUID = this.form.get('testing_information_uid').value;
        const studentCode = this.form.get('check_student_code').value;
        if (studentCode !== null) {
            this.testinginformationSV.get(this.TestInformationID).pipe(
                tap(x => console.log(x)),
                tap((x: any) => this.SubjectLists = x.testing_subjects),
                catchError(err => {
                    this.swSV.err();
                    return throwError(err);
                })
            ).subscribe(
                result => {
                    this.studentSV.checkStudentCode(studentCode, testInforUID).pipe(
                        tap((x: any) => this.AfterFoundcheckStudent(x)),
                        tap((x: any) => this.swSV.success('พบข้อมูล')),
                        catchError(err => {
                            this.swSV.errText('ไม่พบข้อมูล');
                            return throwError(err);
                        })
                    ).subscribe();
                }
            );
        } else {
            return this.swSV.errText('กรุณาใส่รหัสนักศึกษา');
        }
    }

    AfterFoundcheckStudent(data) {
        this.form.get('student_code').setValue(data.student_code);
        this.form.get('examinee_full_name').setValue(data.student_name_th);
        this.SubjectLists = this.SubjectLists.filter((el) => {
            return data.subjects.some((f) => {
                return f.subject_code === el.subject_code;
            });
        });
        this.SubjectLists = this.SubjectLists
            .map((x) => {
                x.status_id = true;
                return x;
            });
        this.cdr.detectChanges();

    }

    openDialogCheckPayment() {
        const dialog = this.dialog.open(DialogEnrollmentCounterPaymentComponent, {
            width: '50%',
            data: {
                data: this.userData,
            }
        });
    }

    openDialogCheckReprint() {
        const dialog = this.dialog.open(DialogCheckPaymentCounterComponent, {
            width: '50%',
            data: {
                data: this.userData,
            }
        });
    }


    formatDate(date) {
        let d = new Date(date),
            month = '' + (d.getMonth() + 1),
            day = '' + d.getDate(),
            year = d.getFullYear();

        if (month.length < 2) {
            month = '0' + month;
        }
        if (day.length < 2) {
            day = '0' + day;
        }

        return [year, month, day].join('-');
    }

    createQueryStringFromObject(object: any) {
        let queryStr = '';

        for (const key in object) {
            if (object[key]) {
                queryStr += `${key}=${object[key]}&`;
            }
        }
        const lastIndex = queryStr.lastIndexOf('&');
        queryStr = queryStr.slice(0, lastIndex);
        return queryStr;
    }

    findInvalidControls() {
        const invalid = [];
        const controls = this.form.controls;
        for (const name in controls) {
            if (controls[name].invalid) {
                invalid.push(name);
            }
        }
        console.log(invalid)
        return invalid;
    }

    filterTestingFiled(data, index) {
        const formArray = this.form.get('testing_subject_selecteds') as FormArray;
        formArray.at(index).get('testing_field_uid').setValue(null);
        if (formArray.at(index).get('testing_datetime').value != null) {
            if (this.chooseID.idSub != null) {
                const dateselect = formArray.at(index).get('testing_datetime').value;
                const s1 = this.chooseID.startrangedaySub.split('-');
                const s2 = this.chooseID.endrangedaySub.split('-');
                const c = dateselect.split('-');
                const fromsub = new Date(s1[0], parseInt(s1[1]) - 1, s1[2]);  // -1 because months are from 0 to 11
                const tosub = new Date(s2[0], parseInt(s2[1]) - 1, s2[2]);
                const check = new Date(c[0], parseInt(c[1]) - 1, c[2]);
                // อยู่ในช่วง
                if (check >= fromsub && check <= tosub) {
                    this.testinginformationSV.get(this.chooseID.idTest).pipe(
                        tap(x => {
                            const Testinfordata: any = x;
                            this.TestFieldLists[index] = Testinfordata.testing_rooms
                                .filter((member) => member.branch_uid === data)
                                .reduce((unique, o) => {
                                    if (!unique.some(obj => obj.branch_uid === o.branch_uid)) {
                                        unique.push(o);
                                    }
                                    return unique;
                                }, []);
                            this.cdr.detectChanges()

                        })
                    ).subscribe();
                } else {
                    this.testinginformationSV.get(this.chooseID.idSub).pipe(
                        tap(x => {
                            const Testinfordata: any = x;
                            this.TestFieldLists[index] = Testinfordata.testing_rooms
                                .filter((member) => member.branch_uid === data)
                                .reduce((unique, o) => {
                                    if (!unique.some(obj => obj.branch_uid === o.branch_uid)) {
                                        unique.push(o);
                                    }
                                    return unique;
                                }, []);
                            console.log(this.TestFieldLists[index]);
                            this.cdr.detectChanges();

                        })
                    ).subscribe();
                }


            }

        } else {
            this.testinginformationSV.get(this.chooseID.idTest).pipe(
                tap(x => {
                    const Testinfordata: any = x;
                    this.TestFieldLists[index] = Testinfordata.testing_rooms
                        .filter((member) => member.branch_uid === data)
                        .reduce((unique, o) => {
                            if (!unique.some(obj => obj.branch_uid === o.branch_uid)) {
                                unique.push(o);
                            }
                            return unique;
                        }, []);
                    this.cdr.detectChanges()

                })
            ).subscribe();
        }
    }

}
