import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, Input, Output, EventEmitter, OnChanges } from '@angular/core';
import { Router } from '@angular/router';
import { throwError } from 'rxjs';
import { tap, catchError, filter, concatMap, switchMap } from 'rxjs/operators';
import { BaseList } from 'src/app/core/base/base-list';
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 { UserService } from 'src/app/core/service/user/user.service';
import { createQueryStringFromObject } from 'src/app/shared/util/func';

@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() candidateType: any = [];
    @Output() search = new EventEmitter()
    @Output() delete = new EventEmitter()
    query = {
        student_code: null,
        full_name: null,
        examinee_card: null
    }
    selectfile;
    data;
    confirmData;
    constructor(
        private studentUploadSV: StudentUploadService,
        private uploadSV: UploadService,
        private swSV: SweetalertService,
        private cdr: ChangeDetectorRef,
        private studentSV: StudentService,
        private router: Router,
        private userSV: UserService
    ) {
        super()
     }

    ngOnInit(): void {
    }

    ngOnChanges(){
        if(this.studentList) this.studentList = this.updateMatTable(this.studentList? this.studentList:[])
    }

    onSearch(){
        const query = createQueryStringFromObject(this.query)
        this.search.emit(query)
    }

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

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

    upload(){
        const formData: FormData = new FormData();
        formData.append('file', this.selectfile, this.selectfile.name);
        this.studentUploadSV.uploadDocument(formData).pipe(
            filter((x:any) => x.status == 'success'),
            tap(x => this.swSV.saveSuccess('นำเข้าสำเร็จ')),
            tap(x => this.studentList = this.updateMatTable(x.message)),
            tap(x => this.cdr.detectChanges()),
            catchError(err => {
                this.swSV.errText('มีข้อผิดพลาดในการนำเข้า')
                return throwError(err)
            })
        ).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()
    }

    edit(x){
        this.router.navigate(['check-student-info/edit',x])
    }

    remove(id){
        this.delete.emit(id)
    }

}
