import { SelectionModel } from '@angular/cdk/collections';
import { I } from '@angular/cdk/keycodes';
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, Input, Output, EventEmitter, OnChanges, ViewChild, ElementRef } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { of, throwError } from 'rxjs';
import { tap, catchError, filter, concatMap, switchMap } from 'rxjs/operators';
import { BaseList } from 'src/app/core/base/base-list';
import { RuStudentService } from 'src/app/core/service/ru-student/ru-student.service';
import { DeleteImportStudentService } from 'src/app/core/service/student/delete-import-student.service';
import { StudentGenerateRegisterService } from 'src/app/core/service/student/student-generate-register.service';
import { StudentUploadService } from 'src/app/core/service/student/student-upload.service';
import { StudentService } from 'src/app/core/service/student/student.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { UploadService } from 'src/app/core/service/upload/upload.service';
import { createQueryStringFromObject } from 'src/app/shared/util/func';
import { TemplateDialogComponent } from '../template-dialog/template-dialog.component';
import { UploadDialogComponent } from '../upload-dialog/upload-dialog.component';

@Component({
    selector: 'app-list',
    templateUrl: './list.component.html',
    styleUrls: ['./list.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ListComponent extends BaseList implements OnInit,OnChanges {
    @Input() studentList: any = [];
    @Input() infoData;
    @ViewChild('et') et: ElementRef
    @Output() search = new EventEmitter()
    @Output() searchRu = new EventEmitter()
    selection = new SelectionModel<any>(true, []);
    query = {
        student_code: null,
        student_name_th: null,
        testing_information_uid: null
    }
    studentType;
    selectfile;
    data;
    confirmData;
    isEt : boolean = false
    isEtUploaded: boolean = false
    isRuStudent: boolean = false
    constructor(
        private studentUploadSV: StudentUploadService,
        private uploadSV: UploadService,
        private swSV: SweetalertService,
        private cdr: ChangeDetectorRef,
        private studentSV: StudentService,
        private dialog: MatDialog,
        private ruStudentUploadSV: RuStudentService,
        private studentGenerateRegisterSV: StudentGenerateRegisterService,
        private deleteImportStudentSV: DeleteImportStudentService
    ) {
        super()
     }

    ngOnInit(): void {

    }

    ngOnChanges(){
        if(this.studentList){
            this.studentList = this.updateMatTable(this.studentList? this.studentList:[])
        }
        if(this.infoData){
            if(this.infoData.type_of_examinee.includes('โครงการพิเศษ')){
                this.studentType = 3
            } else if (this.infoData.type_of_examinee.includes('บุคคลทั่วไป')){
                this.studentType = 2
            } else {
                this.studentType = 1
            }
            if(this.infoData.registration_type == 1) this.isRuStudent = true
        }
    }

    onSearch(){
        this.query.testing_information_uid = this.infoData.testing_information_uid
        const query = createQueryStringFromObject(this.query)
        if(this.studentType == 1){
            this.searchRu.emit(query)
        }else{
            this.search.emit(query)
        }
    }

    clear(){
        this.query = {
            student_code: null,
            student_name_th: null,
            testing_information_uid: null
        }
        this.studentList = this.updateMatTable([])
    }
    onSelectFile(event) {
        if (event.target.files && event.target.files[0]) {
            this.selectfile = event.target.files[0];
            this.uploadEtdc()
        }
    }

    uploadEtdc(){
        this.swSV.loadingStart('กำลังอัปโหลดไฟล์')
        const formData: FormData = new FormData();
        formData.append('file', this.selectfile, this.selectfile.name);
        this.ruStudentUploadSV.registerUpload(this.infoData.testing_information_code,formData).pipe(
            tap(x => this.swSV.close()),
            tap(x => this.swSV.saveSuccess('นำเข้าสำเร็จ')),
            tap(x => this.isEtUploaded = true),
            tap(x => this.studentList = this.updateMatTable(x)),
            catchError(err => {
                this.swSV.close()
                this.swSV.errText(err.error)
                return throwError(err)
            })
        ).subscribe()
    }

    save(){
        this.studentGenerateRegisterSV.register(this.infoData.testing_information_uid,this.studentList.data).pipe(
            tap(x => this.swSV.saveSuccess()),
            tap(x => window.history.back()),
            catchError(err => {
                this.swSV.errText(err.error)
                return throwError(err)
            })
        ).subscribe()
    }

    saveRuStudent(isGenerateSeat){
        this.swSV.loadingStart()
        this.studentGenerateRegisterSV.registerSeat(this.infoData.testing_information_uid,isGenerateSeat,this.studentList.data).pipe(
            tap(x => this.swSV.close()),
            tap(x => this.swSV.saveSuccess()),
            tap(x => window.history.back()),
            catchError(err => {
                this.swSV.close()
                this.swSV.errText(err.error)
                return throwError(err)
            })
        ).subscribe()
    }

    uploadFile(event,x){
        if (event.target.files && event.target.files[0]) {
            this.selectfile = event.target.files[0];
            this.uploadPicture(x)
        }
    }

    uploadDialog(){
        const obj = {
            testing_information : this.infoData,
            student_type : this.studentType
        }
        const dialogRef = this.dialog.open(UploadDialogComponent, {
            width: '500px',
            data: obj,
        });

        dialogRef.afterClosed().pipe(
            filter(x => x),
            tap(x => this.isEt = true),
            concatMap(x => {
                if(x.data && this.studentType != 1){
                    this.swSV.saveSuccess('นำเข้าสำเร็จ')
                    this.studentList = this.updateMatTable(x.data)
                    return of()
                }
                if(this.studentType == 1){
                    return this.swSV.save('นำเข้าสำเร็จแล้ว','อัปโหลดไฟล์ ET_STDC').pipe(
                        filter(x => x.isConfirmed),
                        tap(x => this.et.nativeElement.click())
                    )
                }
            }),
            tap(x => this.cdr.detectChanges()),
        ).subscribe()
    }

    uploadPicture(form){
        const formData: FormData = new FormData();
        formData.append('file', this.selectfile, this.selectfile.name);
        this.uploadSV.add(formData).pipe(
            tap((x:any) => form.photo_url = x[0].file_name),
            concatMap(x => this.studentSV.update2(form)),
            tap(x => this.cdr.detectChanges()),
            catchError(err => {
                this.swSV.errText('มีข้อผิดพลาดในการอัปโหลด')
                return throwError(err)
            })
        ).subscribe()
    }

    view(x){
        window.open(x)
    }

    deletePicture(form){
        this.swSV.confirm().pipe(
                filter(x => x.isConfirmed),
                tap(x => form.photo_url = null),
                switchMap(x => {
                    return this.studentSV.update2(form).pipe(
                        tap(x => this.swSV.removeSuccess()),
                        tap(x => this.cdr.detectChanges())
                    )
                })
        ).subscribe()
    }

    template(){
        if(this.studentType == 1){

        }else{
            const obj = {
                testing_information : this.infoData,
                student_type : this.studentType
            }
            const dialogRef = this.dialog.open(TemplateDialogComponent, {
                width: '600px',
                data: obj,
            });
        }
    }

    getDate(day,month,year){
        const new_year = +year+2500
        return new Date(new_year-543, month-1, day)
    }

    isAllSelected() {
        const numSelected = this.selection.selected.length;
        const numRows = this.studentList?.data.length;
        return numSelected === numRows;
    }

    /** Selects all rows if they are not all selected; otherwise clear selection. */
    masterToggle() {
        if (this.isAllSelected()) {
            this.selection.clear();
            return;
        }

        this.selection.select(...this.studentList?.data);
    }

    /** The label for the checkbox on the passed row */
    checkboxLabel(row?): string {
        if (!row) {
            return `${this.isAllSelected() ? 'deselect' : 'select'} all`;
        }
        return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row.position + 1}`;
    }

    remove(){
        if(this.infoData.registration_type == 1){
            const studentLists = [...this.selection.selected].map(x => x.student_code)
            this.swSV.confirm().pipe(
                filter(x => x.isConfirmed),
                switchMap(x => {
                    return this.deleteImportStudentSV.deleteImportType1(this.infoData.testing_information_uid,studentLists).pipe(
                        tap(x => this.swSV.removeSuccess('ลบข้อมูลสำเร็จ')),
                        tap(x => this.onSearch()),
                        catchError(err => {
                            this.swSV.errText(err.error)
                            return throwError(err)
                        })
                    )
                })
            ).subscribe()
        }
        if(this.infoData.registration_type == 2){
            const studentLists = [...this.selection.selected].map(x => x.student_uid)
            this.swSV.confirm().pipe(
                filter(x => x.isConfirmed),
                switchMap(x => {
                    return this.deleteImportStudentSV.deleteImportType2(studentLists).pipe(
                        tap(x => this.swSV.removeSuccess('ลบข้อมูลสำเร็จ')),
                        tap(x => this.onSearch()),
                        catchError(err => {
                            this.swSV.errText(err.error)
                            return throwError(err)
                        })
                    )
                })
            ).subscribe()
        }
    }
}
