import {Location} from '@angular/common';
import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, ElementRef, ViewChild} from '@angular/core';
import {FormBuilder, Validators} from '@angular/forms';
import {MatGridTileHeaderCssMatStyler} from '@angular/material/grid-list';
import {ActivatedRoute, NavigationEnd, Router} from '@angular/router';
import {concat, Observable, throwError} from 'rxjs';
import {catchError, concatMap, debounceTime, filter, map, startWith, switchMap, tap} from 'rxjs/operators';
import {BaseForm} from 'src/app/core/base/base-form';
import {BaseTiny} from 'src/app/core/base/tinymce';
import {DepartmentService} from 'src/app/core/service/settings/department.service';
import {EducationTypesService} from 'src/app/core/service/settings/education-types.service';
import {FacultysService} from 'src/app/core/service/settings/facultys.service';
import {SubjectTypesService} from 'src/app/core/service/settings/subject-types.service';
import {SubjectsService} from 'src/app/core/service/settings/subjects.service';
import {SweetalertService} from 'src/app/core/service/sweetalert/sweetalert';
import {UploadService} from 'src/app/core/service/upload/upload.service';

@Component({
    selector: 'app-setting-exam-form',
    templateUrl: './setting-exam-form.component.html',
    styleUrls: ['./setting-exam-form.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class SettingExamFormComponent extends BaseForm implements OnInit {
    @ViewChild('res', {static: true}) res: ElementRef
    form;
    subjectType$ = new Observable();
    educationType$ = new Observable();
    faculty;
    selectfile;
    subject;
    curSub;
    departmentList: any = [];
    filteredDepartmentList: any = [];
    isUse: boolean
    statusMock = [{id: 1, name: 'ใช้งาน'}, {id: 2, name: 'ยกเลิก'}];

    constructor(
        public fb: FormBuilder,
        private subjectTypeSV: SubjectTypesService,
        private subjectSV: SubjectsService,
        private educationTypeSV: EducationTypesService,
        private facultySV: FacultysService,
        private swSV: SweetalertService,
        public router: Router,
        public activeRoute: ActivatedRoute,
        public location: Location,
        private cdr: ChangeDetectorRef,
        private uploadSV: UploadService,
        private departMentSV: DepartmentService
    ) {
        super(
            router,
            activeRoute,
            fb,
            location
        )
        this.form = this.fb.group({
            status_id: [null, Validators.required],
            created_by: null,
            created_datetime: null,
            updated_by: null,
            updated_datetime: null,
            deleted_by: null,
            deleted_datetime: null,
            subject_uid: null,
            subject_code: [null, Validators.required],
            subject_name_th: [null, Validators.required],
            subject_name_en: [null, [Validators.pattern('^[a-zA-Z0-9_]*$'), Validators.required]],
            education_type_uid: [null, Validators.required],
            subject_type_uid: [null, Validators.required],
            responsible_faculty_uid: [null, Validators.required],
            major_name_th: null,
            major_name_en: null,
            remark: null,
            file_url: null,
            file_name: null,
        })
    }

    ngOnInit(): void {
        this.subjectType$ = this.subjectTypeSV.getAll()
        this.educationType$ = this.educationTypeSV.getAll()
        this.departMentSV.getAll().pipe(
            tap(x => this.departmentList = x)
        ).subscribe()
        this.facultySV.getAll().pipe(tap(x => this.faculty = x)).subscribe()
        this.subjectSV.getAll().pipe(tap(x => this.subject = x)).subscribe()
        switch (this.state) {
            case 'edit':
                this.subjectSV.get(this.id).pipe(
                    tap(x => this.form.patchValue(x)),
                    tap(x => this.curSub = x),
                    tap(x => this.filterDepartment(null, x)),
                    tap(x => this.cdr.detectChanges())
                ).subscribe()
                this.subjectSV.check(this.id).pipe(
                    tap((x: any) => this.isUse = x.is_use),
                ).subscribe()
                break;

            case 'add':
                break;
        }
    }

    setupForm(x) {

    }

    filterDepartment(id, edit?) {
        if (edit) {
            this.filteredDepartmentList = this.departmentList.filter(x => x.faculty_uid == edit.responsible_faculty_uid)
        } else {
            this.form.get('major_name_th').setValue(null)
            this.filteredDepartmentList = this.departmentList.filter(x => x.faculty_uid == id)
        }

    }


    save() {
        const form = this.form.getRawValue()
        const code = this.form.get('subject_code').value
        const data = this.subject.find(x => x.subject_code == code) ? true : false
        const cur = form.subject_code == this.curSub?.subject_code ? true : false
        if (data == false || cur == true) {
            switch (this.state) {
                case 'edit':
                    if (this.isUse == true) {
                        this.swSV.confirm('วิชานี้มีการใช้งานอยู่ต้องการแก้ไขหรือไม่').pipe(
                            filter(x => x.isConfirmed),
                            concatMap(x => {
                                return this.subjectSV.update2(form).pipe(
                                    tap(x => this.swSV.updateSuccess()),
                                    tap(x => this.back()),
                                    catchError(err => {
                                        this.swSV.err()
                                        return throwError(err)
                                    })
                                )
                            })
                        ).subscribe()
                    } else {
                        this.subjectSV.update2(form).pipe(
                            tap(x => this.swSV.updateSuccess()),
                            tap(x => window.history.back()),
                            catchError(err => {
                                this.swSV.errText(err.error.description)
                                return throwError(err)
                            })
                        ).subscribe()
                    }
                    break;

                case 'add':
                    this.subjectSV.add(form).pipe(
                        tap(x => this.swSV.saveSuccess()),
                        tap(x => window.history.back()),
                        catchError(err => {
                            this.swSV.err()
                            return throwError(err)
                        })
                    ).subscribe()
                    break;
            }
        } else {
            this.swSV.errText('รหัสวิชาซ้ำกัน')
        }
    }

    delete() {
        const id = this.form.get('subject_uid').value
        this.swSV.confirm().pipe(
            filter(x => x.isConfirmed),
            concatMap(x => {
                return this.subjectSV.deleteData(id).pipe(
                    tap(x => this.swSV.removeSuccess()),
                    tap(x => this.back()),
                    catchError(err => {
                        this.swSV.errText('เกิดข้อผิดพลาดหรือมีการใช้งานข้อมูลนี้อยู่')
                        return throwError(err)
                    })
                )
            })
        ).subscribe()
    }

    cancel() {
        window.history.back()
    }

    onSelectFile(event) {
        if (event.target.files && event.target.files[0]) {
            this.selectfile = event.target.files[0];
            const formData: FormData = new FormData();
            formData.append('file', this.selectfile, this.selectfile.name);
            console.log(formData);
            this.uploadSV.add(formData).pipe(
                tap((x: any) => this.form.get('file_url').setValue(x[0].file_name)),
                tap((x: any) => this.form.get('file_name').setValue(x[0].name)),
                tap(x => this.cdr.detectChanges()),
            ).subscribe()
        }
    }

    download() {
        window.open(this.form.get('file_url').value)
    }

    display(uid) {
        // console.log(uid)
        // console.log(this.faculty)
        if (uid && this.faculty) return this.faculty.find(x => x.faculty_uid === uid)?.faculty_name_th
        if (uid && !this.faculty) return this.curSub?.responsible_faculty_name_th
    }

}
