import { ChangeDetectorRef, Component } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { FileService } from 'src/app/shared/services/file.service';
interface table {
    currentPage: number,
    page: number[],
    search: string
}
@Component({
    selector: 'app-time-attendance-statistics',
    templateUrl: './time-attendance-statistics.component.html',
    styleUrls: ['./time-attendance-statistics.component.scss']
})
export class TimeAttendanceStatisticsComponent {
    selectedFile: File | null = null;
    selectedFileName: string = 'PleaseSelectFile';
    constructor(private toastr: ToastrService,
        private cdr: ChangeDetectorRef,
        private fileService: FileService) { }


    onFileSelected(event: any) {
        this.selectedFile = event.target.files.length > 0 ? event.target.files[0] : null;
        this.selectedFileName = this.selectedFile?.name || "PleaseSelectFile"
    }
    uploadFile() {
        if (!this.selectedFile) {
            alert('กรุณาเลือกไฟล์ก่อนอัปโหลด')
            return
        }
        const formData = new FormData();
        formData.append('file', this.selectedFile);
        this.fileService.uploadExcel(formData, 'PMS_WORKING_TIME_EMP').subscribe({
            next: response => {
                if (response.success) {
                    this.showAlert(response.message, 'success')
                } else {
                    this.showAlert(response.message, 'error')
                    this.cdr.detectChanges();
                }
            }, error: error => {
                this.showAlert(error.message, 'error')
                this.cdr.detectChanges();
            }
        })
    }
    downloadFile() {
        const fileName = 'IMPORT_PMS_WORKING_TIME_EMP.xlsx'
        this.fileService.downloadTemplate(fileName).subscribe({
            next: response => {
                const url = window.URL.createObjectURL(response);
                const a = document.createElement("a");
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            }, error: error => {
                this.showAlert(error.message, 'error')
            }
        })
    }

    showAlert(text: string, type: 'success' | 'error') {
        this.toastr[type](text, 'แจ้งเตือน', {
            timeOut: 3000,
            positionClass: 'toast-top-right',
        });
    }

}