import { ChangeDetectorRef, Component } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { EventgrpModel, MyEventgrpModel } from 'src/app/shared/model/eventgrp.model';
import { EventgrpService } from 'src/app/shared/services/eventgrp.service';
import { FileService } from 'src/app/shared/services/file.service';
@Component({
    selector: 'app-day-type-registry',
    templateUrl: './day-type-registry.component.html',
    styleUrls: ['./day-type-registry.component.scss']
})
export class DayTypeRegistryComponent {
    pathTitle = ['menu.Organization', 'menu.LeaveType', 'LeaveInfo']
    currentPage = 1
    selectedItems: string[] = [];
    search = ""
    selectedFile: File | null = null;
    selectedFileName: string = 'selectedFileName';
    modalStatus: 'add' | 'edit' | 'delete' | 'deleteGroup' = 'add'
    page = Array.from({ length: 1 }, (_, i) => i + 1);
    numDataListChecked = 0
    isDataListChecked = false
    isDataListCheckedAll = false


    eventgrp: { loading: boolean, select: EventgrpModel, dataList: { check: boolean, data: EventgrpModel }[] } = { loading: false, select: new MyEventgrpModel(), dataList: [] }
    constructor(
        private toastr: ToastrService,
        private cdr: ChangeDetectorRef,
        private fileService: FileService,
        private eventgrpService: EventgrpService
    ) { }
    ngOnInit(): void {
        this.getEventgrpList()
    }

    onFileSelected(event: any) {
        this.selectedFile = event.target.files.length > 0 ? event.target.files[0] : null;
        this.selectedFileName = this.selectedFile?.name || "กรุณาเลือกไฟล์"
    }

    uploadFile() {
        if (!this.selectedFile) {
            alert('กรุณาเลือกไฟล์ก่อนอัปโหลด')
            return
        }
        const formData = new FormData();
        formData.append('file', this.selectedFile);
        this.eventgrp.loading = true
        this.fileService.uploadExcel(formData, 'MEVENTGRP').subscribe({
            next: response => {
                if (response.success) {
                    this.showAlert(response.message, 'success')
                    this.getEventgrpList()
                } else {
                    this.showAlert(response.message, 'error')
                    this.eventgrp.loading = false
                    this.cdr.detectChanges();
                }
            }, error: error => {
                this.showAlert(error.message, 'error')
                this.eventgrp.loading = false
                this.cdr.detectChanges();
            }
        })
    }

    downloadFile() {
        const fileName = 'IMPORT_EVENTGRP.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')
            }
        })

    }
    getEventgrpList() {
        this.eventgrp.loading = true
        this.eventgrpService.getList().subscribe({
            next: response => {
                this.eventgrp.dataList = response.map(x => ({ check: false, data: new MyEventgrpModel(x) }))
                this.eventgrp.loading = false
                this.isDataListCheckedAll = false
                this.dataListCheckAll()
                this.searchChange()
                this.cdr.detectChanges();
            }, error: error => {
                this.eventgrp.loading = false
                this.cdr.detectChanges()
            }
        })
    }
    searchChange() {
        this.currentPage = 1
        this.page = Array.from({ length: Math.ceil(this.eventgrpListFilter().length / 10) }, (_, i) => i + 1);
        this.dataListCheck()
    }
    eventgrpListFilter() {
        return this.eventgrp.dataList.filter(x => {
            const data = x.data
            const match = data.eventgrpId.toLowerCase().includes(this.search.toLowerCase()) || data.tdesc.toLowerCase().includes(this.search.toLowerCase()) || data.edesc.toLowerCase().includes(this.search.toLowerCase());
            return match;
        });
    }

    setData(data?: EventgrpModel) {
        this.eventgrp.select = new MyEventgrpModel(data)
    }

    addEventgrp() {
        this.eventgrp.loading = true
        this.eventgrpService.post(new MyEventgrpModel(this.eventgrp.select)).subscribe({
            next: response => {
                if (response.success) {
                    this.showAlert(response.message, 'success')
                    this.getEventgrpList()
                } else {
                    this.showAlert(response.message, 'error')
                    this.eventgrp.loading = false
                    this.cdr.detectChanges()
                }
            }, error: error => {
                this.showAlert(error.message, 'error')
                this.eventgrp.loading = false
                this.cdr.detectChanges()
            }
        })
    }
    deleteEventgrp() {
        let body: EventgrpModel[] = []
        if (this.eventgrp.select.eventgrpId) {
            body = [new MyEventgrpModel(this.eventgrp.select)]
        } else {
            body = this.eventgrp.dataList.filter(x => x.check).map(x => new MyEventgrpModel(x.data))
        }
        this.eventgrp.loading = true
        this.eventgrpService.delete(body).subscribe({
            next: response => {
                if (response.success) {
                    this.showAlert(response.message, 'success')
                    this.getEventgrpList()
                } else {
                    this.showAlert(response.message, 'error')
                    this.eventgrp.loading = false
                    this.cdr.detectChanges()
                }
            }, error: error => {
                this.showAlert(error.message, 'error')
                this.eventgrp.loading = false
                this.cdr.detectChanges()
            }
        })
    }
    showAlert(text: string, type: 'success' | 'error') {
        this.toastr[type](text, 'แจ้งเตือน', {
            timeOut: 3000,
            positionClass: 'toast-top-right',
        });
    }

    dataListCheckAll() {
        const selectAll = this.isDataListCheckedAll;
        this.eventgrpListFilter().forEach(x => x.check = selectAll);
        this.dataListCheck();
    }
    dataListCheck() {
        const dataCheck = this.eventgrpListFilter();
        this.isDataListCheckedAll = dataCheck.length ? dataCheck.every(x => x.check) : false;
        this.numDataListChecked = this.eventgrp.dataList.filter(x => x.check).length;
        this.isDataListChecked = Boolean(this.numDataListChecked)
    }


    clearEventgrp(modalStatus: string) {
        if (modalStatus == 'add') {
            this.eventgrp.select = new MyEventgrpModel()
        } else if (modalStatus == 'edit') {
            this.eventgrp.select = new MyEventgrpModel({ eventgrpId: this.eventgrp.select.eventgrpId })
        }
    }
}

