import {Component, OnInit, ChangeDetectionStrategy, ViewChild, ChangeDetectorRef} from '@angular/core';
import {formatDate} from '@angular/common';
import {BaseForm} from '../../../../../../core/base/base-form';
import {ActivatedRoute, Router} from '@angular/router';
import {Location} from '@angular/common';
import {FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms';
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 {MatDatepicker, MatDatepickerInputEvent} from '@angular/material/datepicker';
import {MatSort} from '@angular/material/sort';
import {MatPaginator} from '@angular/material/paginator';
import {catchError, tap} from 'rxjs/operators';
import {throwError} from 'rxjs';
import {SweetalertService} from '../../../../../../core/service/sweetalert/sweetalert';

@Component({
    selector: 'app-create-exam-information-form',
    templateUrl: './create-exam-information-form.component.html',
    styleUrls: ['./create-exam-information-form.component.scss'],
    // changeDetection: ChangeDetectionStrategy.OnPush
})
export class CreateExamInformationFormComponent extends BaseForm implements OnInit {
    // MainForm
    setexamform: FormGroup;
    academicSemList: any = [];
    academicYearList: any = [];
    educationTypeLists: any = [];
    testingInfoData;
    // ตัวจัดการวันห้ามสอบ
    @ViewChild('picker7', {static: true}) _picker: MatDatepicker<Date>;
    @ViewChild(MatSort, {static: true}) sort: MatSort;
    @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
    public CLOSE_ON_SELECTED = false;
    public init = new Date();
    public resetModel = new Date(0);
    public model = [
        // new Date('2/8/2022'),
        // new Date('2/9/2022'),
        // new Date('2/11/2022'),
    ];
    today = new Date();
    daywithout = {
        days_without_testing_uid: null,
        date_without_testing: null,
    };
    sectionsFakeFalse = [
        {
            status_id: 1,
            testing_center_period_uid: null,
            print_start_time: null,
            print_end_time: null,
            testing_information_uid: null,
            testing_period_uid: null,
            period_id: 1,
            is_check: false,
            start_time: '09:00'
        },
        {
            status_id: 1,
            testing_center_period_uid: null,
            print_start_time: null,
            print_end_time: null,
            testing_information_uid: null,
            testing_period_uid: null,
            period_id: 2,
            is_check: false,
            start_time: '12:00'
        },
        {
            status_id: 1,
            testing_center_period_uid: null,
            print_start_time: null,
            print_end_time: null,
            testing_information_uid: null,
            testing_period_uid: null,
            period_id: 3,
            is_check: false,
            start_time: '15:00'
        },
        {
            status_id: 1,
            testing_center_period_uid: null,
            print_start_time: null,
            print_end_time: null,
            testing_information_uid: null,
            testing_period_uid: null,
            period_id: 4,
            is_check: false,
            start_time: '18:00'
        }
    ];

    constructor(
        public fb: FormBuilder,
        public formBuilder: FormBuilder,
        public router: Router,
        public activeRoute: ActivatedRoute,
        public location: Location,
        private AcademicSemSV: AcademicSemesterService,
        private AcademicYearSV: AcademicYearService,
        private TestInformationSV: TestingInformationService,
        private swSV: SweetalertService,
        private cdr: ChangeDetectorRef
    ) {
        super(
            router,
            activeRoute,
            fb,
            location
        );
        this.setexamform = this.formBuilder.group({
            status_id: null,
            created_by: null,
            created_datetime: null,
            updated_by: null,
            updated_datetime: null,
            deleted_by: null,
            deleted_datetime: null,
            testing_information_uid: null,
            testing_information_name: [null, Validators.required],
            testing_information_code: null,
            academic_semester_code: [null, Validators.required],
            academic_year_code: [null, Validators.required],
            testing_information_status: null,
            type_of_examinee: [null, Validators.required],
            is_student_code: false,
            first_student_code: '',
            last_student_code: '',
            start_datetime: null,
            end_datetime: null,
            registration_start_datetime: null,
            registration_end_datetime: null,
            testing_start_datetime: null,
            testing_end_datetime: null,
            is_number_of_times_testing: false,
            is_online_register: true,
            number_of_times_testing: null,
            times_the_score_is_calculated: 1,
            is_main: true,
            main_testing_information_uid: null,
            registration_type: 1,
            is_open: null,
            is_upload_document: false,
            is_register_verify: false,
            is_register: false,
            is_counter: false,
            days_without_testings: this.formBuilder.array([
                this.block_days(null)
            ]),
            testing_calendars: this.formBuilder.array([
                this.testing_calendars(null)
            ]),
            testing_subjects: this.formBuilder.array([
                this.testing_subjects()
            ]),
            testing_rooms: this.formBuilder.array([
                this.testing_rooms()
            ]),
            testing_periods: this.formBuilder.array([
                this.testing_periods()
            ])
        });
    }

    block_days(blockdays?) {
        return this.formBuilder.group({
            status_id: null,
            testing_information_uid: blockdays?.testing_information_uid,
            days_without_testing_uid: blockdays?.days_without_testing_uid,
            date_without_testing: blockdays?.date_without_testing,
        });
    }

    testing_calendars(calender?) {
        return this.formBuilder.group({
            status_id: null,
            testing_calendar_uid: calender?.testing_calendar_uid,
            start_datetime: calender?.start_datetime,
            end_datetime: calender?.end_datetime,
            calendar_type_uid: calender?.calendar_type_uid,
            calendar_type_name_th: calender?.calendar_type_name_th,
            testing_information_uid: calender?.testing_information_uid,
        });
    }

    testing_subjects(data?) {
        console.log(data)
        return this.formBuilder.group({
            status_id: null,
            // created_by: null,
            // created_datetime: null,
            // updated_by: null,
            // updated_datetime: null,
            // deleted_by: null,
            // deleted_datetime: null,
            testing_subject_uid: data?.testing_subject_uid,
            subject_uid: data?.subject_uid,
            subject_code: data?.subject_code,
            subject_name_th: data?.subject_name_th,
        });
    }

    testing_periods(data?) {
        return this.formBuilder.group({
            status_id: null,
            is_open: data?.is_open,
            print_start_time: data?.print_start_time,
            print_end_time: data?.print_end_time,
            // created_by: null,
            // created_datetime: null,
            // updated_by: null,
            // updated_datetime: null,
            // deleted_by: null,
            // deleted_datetime: null,
            // deleted_datetime: null,
            is_check: data?.is_check,
            testing_information_uid: data?.testing_information_uid,
            testing_period_uid: data?.testing_period_uid,
            period_id: data?.period_id,
            start_time: [data?.start_time, Validators.required],
        });
    }

    testing_rooms(data?) {
        return this.formBuilder.group({
            testing_room_uid: data?.testing_room_uid,
            testing_center_uid: data?.testing_center_uid,
            // testing_center_name_th: data?.testing_center_name_th,
            branch_uid: data?.branch_uid,
            branch_name_th: data?.branch_name_th,
            testing_field_uid: data?.testing_field_uid,
            testing_information_uid: data?.testing_information_uid,
            testing_field_name_th: data?.testing_field_name_th,
            testing_room_name_th: data?.testing_room_name_th,
            testing_auth_name: data?.testing_auth_name,
            is_random_seat: data?.is_random_seat,
            testing_seats: this.formBuilder.array([
                this.testing_seats(data?.testing_seats)
            ]),
        });
    }

    testing_seats(data?) {
        return this.formBuilder.group({
            status_id: null,
            // created_by: null,
            // created_datetime: null,
            // updated_by: null,
            // updated_datetime: null,
            // deleted_by: null,
            // deleted_datetime: null,
            no_of_seats: data?.no_of_seats,
            row_name: data?.row_name,
            testing_seat_uid: data?.testing_seat_uid,
            testing_center_row_uid: data?.testing_center_row_uid,
            is_specify_subject: data?.is_specify_subject,
            testing_room_uid: data?.testing_room_uid,
            testing_seat_subjects: this.formBuilder.array([
                this.testing_seat_subjects(data?.testing_seat_subjects)
            ]),
        });
    }

    testing_seat_subjects(data?) {
        return this.formBuilder.group({
            status_id: null,
            testing_seat_subject_uid: data?.testing_seat_subject_uid,
            subject_uid: data?.subject_uid,
            subject_code: data?.subject_code,
            subject_name_th: data?.subject_name_th,
            start_seat_no: data?.start_seat_no,
            end_seat_no: data?.end_seat_no,
            testing_seat_uid: data?.testing_seat_uid,
        });
    }


    ngOnInit(): void {
        const form = this.setexamform.get('testing_calendars') as FormArray;
        const form2 = this.setexamform.get('testing_subjects') as FormArray;
        const form3 = this.setexamform.get('testing_rooms') as FormArray;
        const form4 = this.setexamform.get('testing_periods') as FormArray;
        const form5 = this.setexamform.get('days_without_testings') as FormArray;
        this.AcademicSemSV.getAll().subscribe(
            result => {
                this.academicSemList = result;
            }
        );
        this.AcademicYearSV.getAll().subscribe(
            result => {
                this.academicYearList = result;
            }
        );
        this.TestInformationSV.getDatatype().pipe(
            tap(x => this.educationTypeLists = x),
            tap(x => this.cdr.detectChanges())
        ).subscribe()
        switch (this.state) {
            case 'edit':
                this.TestInformationSV.get(this.id).pipe(
                    tap(x => this.testingInfoData = x),
                    tap(x => console.log(this.testingInfoData)),
                    tap(x => {
                        form.clear();
                        form2.clear();
                        form3.clear();
                        form4.clear();
                        form5.clear();
                    }),
                    tap(x => {
                        const data: any = x;
                        this.setexamform.patchValue(data);
                        if (data.number_of_times_testing === null) {
                            this.setexamform.get('is_number_of_times_testing').setValue(false);
                        }
                    }),
                    tap(x => this.add3Edit(x)),
                    tap(x => this.addCalendaEdit(x)),
                    tap(x => this.addPeriodEdit(x)),
                    tap(x => this.addSubject(x)),
                    tap(x => this.addEditBlockadd(x)),
                    tap(x => this.cdr.detectChanges())
                ).subscribe();
                break;
            case 'add':
                form.clear();
                form2.clear();
                form3.clear();
                form4.clear();
                for (let i = 0; i < this.sectionsFakeFalse.length; i++) {
                    form4.push(this.testing_periods(this.sectionsFakeFalse[i]));
                }
                form5.clear();
                break;
        }
    }

    add3Edit(data) {
        const form = this.setexamform.get('testing_rooms') as FormArray;
        for (let i = 0; i < data.testing_rooms.length; i++) {
            form.push(this.testing_rooms(data.testing_rooms[i]));
            const formArray = form.controls[i].get('testing_seats') as FormArray;
            const FormArraySeat = form.controls[i].get('testing_seat_subjects') as FormArray;
            formArray.clear();
            for (let j = 0; j < data.testing_rooms[i].testing_seats.length; j++) {
                formArray.push(this.testing_seats(data.testing_rooms[i].testing_seats[j]));
                const formArraySeatSubject = formArray.controls[j].get('testing_seat_subjects') as FormArray;
                formArraySeatSubject.clear();
                for (let k = 0; k < data.testing_rooms[i].testing_seats[j].testing_seat_subjects.length; k++) {
                    formArraySeatSubject.push(this.testing_seat_subjects(data.testing_rooms[i].testing_seats[j].testing_seat_subjects[k]));
                }
            }
        }
    }

    addCalendaEdit(x) {
        const form2 = this.setexamform.get('testing_calendars') as FormArray;
        for (let i = 0; i < x.testing_calendars.length; i++) {
            x.testing_calendars[i].end_datetime = formatDate(x.testing_calendars[i].end_datetime, 'yyyy-MM-dd', 'en-US');
            x.testing_calendars[i].start_datetime = formatDate(x.testing_calendars[i].start_datetime, 'yyyy-MM-dd', 'en-US');
            form2.push(this.testing_calendars(x.testing_calendars[i]));
        }
    }

    addPeriodEdit(x) {
        const form = this.setexamform.get('testing_periods') as FormArray;
        for (let i = 0; i < x.testing_periods.length; i++) {
            const foundIndex = this.sectionsFakeFalse.findIndex(v => v.period_id === x.testing_periods[i].period_id);
            this.sectionsFakeFalse[foundIndex].is_check = true;
            this.sectionsFakeFalse[foundIndex].start_time = (x.testing_periods[i].start_time).substring(0, 5);
            if (this.state === 'edit') {
                this.sectionsFakeFalse[foundIndex].print_start_time = x.testing_periods[i].print_start_time;
                this.sectionsFakeFalse[foundIndex].print_end_time = x.testing_periods[i].print_end_time;
                this.sectionsFakeFalse[foundIndex].testing_period_uid = x.testing_periods[i].testing_period_uid;
                this.sectionsFakeFalse[foundIndex].testing_information_uid = x.testing_periods[i].testing_information_uid;
            }
        }

        // for (let i = 0; i < x.testing_periods.length; i++) {
        //   x.testing_periods[i].is_check = true
        //   form.push(this.testing_periods(x.testing_periods[i]));
        // }

        for (let i = 0; i < this.sectionsFakeFalse.length; i++) {
            form.push(this.testing_periods(this.sectionsFakeFalse[i]));
        }
    }

    addEditBlockadd(x) {
        const form = this.setexamform.get('days_without_testings') as FormArray;
        for (let i = 0; i < x.days_without_testings.length; i++) {
            x.days_without_testings[i].date_without_testing = formatDate(x.days_without_testings[i].date_without_testing, 'yyyy-MM-dd', 'en-US')
            form.push(this.block_days(x.days_without_testings[i]));
            this.model.push(x.days_without_testings[i].date_without_testing);
        }
    }

    addSubject(x) {
        const form = this.setexamform.get('testing_subjects') as FormArray;
        for (let i = 0; i < x.testing_subjects.length; i++) {
            form.push(this.testing_subjects(x.testing_subjects[i]));
        }
    }

    public dateClass = (date: Date) => {
        if (this._findDate(date) !== -1) {
            return ['selected'];
        }
        return [];
    }

    public dateChanged(event: MatDatepickerInputEvent<Date>): void {
        const formblockdays = this.setexamform.get('days_without_testings') as FormArray;
        if (event.value) {
            const date = event.value;
            const index = this._findDate(date);
            if (index === -1) {
                this.model.push(date);
                this.updateBlockdate(date);
            } else {
                this.model.splice(index, 1);
                formblockdays.removeAt(index);
            }

            this.resetModel = new Date(0);
            if (!this.CLOSE_ON_SELECTED) {
                const closeFn = this._picker.close;
                this._picker.close = () => {
                };
                this._picker['_popupComponentRef'].instance._calendar.monthView._createWeekCells()
                setTimeout(() => {
                    this._picker.close = closeFn;
                });
            }
        }
    }

    public remove(date: Date): void {
        const formblockdays = this.setexamform.get('days_without_testings') as FormArray;
        const index = this._findDate(date);
        formblockdays.removeAt(index)
        this.model.splice(index, 1);
    }

    private _findDate(date: Date): number {
        return this.model.map((m) => +m).indexOf(+date);
    }

    clearNumberTestFiledandScore() {
        if (this.setexamform.get('is_number_of_times_testing').value === false) {
            this.setexamform.get('number_of_times_testing').setValue(null);
            this.setexamform.get('times_the_score_is_calculated').setValue(1);
        }
    }

    updateBlockdate(date) {
        const formblockdays = this.setexamform.get('days_without_testings') as FormArray;
        switch (this.state) {
            case 'edit':
                this.daywithout.date_without_testing = formatDate(date, 'yyyy-MM-dd', 'en-US');
                formblockdays.push(this.block_days(this.daywithout));
                break;
            case 'add':
                // this.daywithout.id_day = null;
                this.daywithout.date_without_testing = formatDate(date, 'yyyy-MM-dd', 'en-US');
                formblockdays.push(this.block_days(this.daywithout));
                break;
        }
    }

    save() {
        switch (this.state) {
            case 'edit':
                this.swSV.loadingStart('กำลังบันทึกรอบสอบ');
                const form1 = this.setexamform.getRawValue();
                form1.testing_periods = form1.testing_periods.filter((member) => {
                    return member.is_check === true;
                });
                if (form1.first_student_code != null) {
                    form1.first_student_code = form1.first_student_code.toString();
                }
                if (form1.number_of_times_testing != null) {
                    form1.number_of_times_testing = form1.number_of_times_testing.toString();
                }
                if (form1.last_student_code != null) {
                    form1.last_student_code = form1.last_student_code.toString();
                }
                this.TestInformationSV.update2(form1).pipe(
                    tap(x => this.swSV.close()),
                    tap(x => this.swSV.updateSuccess()),
                    tap(x => window.history.back()),
                    catchError(err => {
                        this.swSV.err();
                        return throwError(err);
                    })
                ).subscribe();
                break;

            case 'add':
                this.swSV.loadingStart('กำลังบันทึกรอบสอบ');
                const form = this.setexamform.getRawValue();
                form.testing_periods = form.testing_periods.filter((member) => {
                    return member.is_check === true;
                });
                if (form.first_student_code != null) {
                    form.first_student_code = form.first_student_code.toString();
                }
                if (form.number_of_times_testing != null) {
                    form.number_of_times_testing = form.number_of_times_testing.toString();
                }
                if (form.last_student_code != null) {
                    form.last_student_code = form.last_student_code.toString();
                }
                // tslint:disable-next-line:max-line-length
                if (form.testing_start_datetime == null || form.testing_end_datetime == null || form.registration_start_datetime == null || form.registration_end_datetime == null) {
                    return this.swSV.errText('กรุณาใส่วันที่');
                }
                this.TestInformationSV.add(form).pipe(
                    tap(x => this.swSV.close()),
                    tap(x => this.swSV.saveSuccess()),
                    tap(x => window.history.back()),
                    catchError(err => {
                        this.swSV.err();
                        return throwError(err);
                    })
                ).subscribe();
                break;
        }
    }

    back() {
        this.location.back()
    }

    onChangeHour(form, data) {
        console.log()
    }

}
