import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
import { ToastrService } from 'ngx-toastr';

export interface DataModel {
    check: boolean,
    code: string,
    period: string,
    year: string,
    startDate: string,
    endDate: string,
    status: string
}

@Component({
    selector: 'app-evaluation-cycle',
    templateUrl: './evaluation-cycle.component.html',
    styleUrls: ['./evaluation-cycle.component.scss']
})
export class EvaluationCycleComponent {
    currentPage = 1
    page = Array.from({ length: 1 }, (_, i) => i + 1);
    search = ""
    numDataListChecked = 0
    isDataListChecked = false
    isDataListCheckedAll = false
    dataList: DataModel[] = [
        {
            check: false,
            code: "Y67P2",
            period: "ช่วงเวลาที่ 2",
            year: "2567",
            startDate: "01-07-2567",
            endDate: "31-12-2567",
            status: "1"
        },
        {
            check: false,
            code: "Y68P1",
            period: "ช่วงเวลาที่ 1",
            year: "2568",
            startDate: "01-01-2568",
            endDate: "30-06-2568",
            status: "2"
        },
        {
            check: false,
            code: "Y67P1",
            period: "ช่วงเวลาที่ 1",
            year: "2567",
            startDate: "01-01-2567",
            endDate: "30-06-2567",
            status: "3"
        },
    ]
    dataSelect: DataModel = {
        check: false,
        code: "",
        period: "",
        year: "",
        startDate: "",
        endDate: "",
        status: "",
    }
    modalStatus: "add" | "edit" = "add"
    constructor(private cdr: ChangeDetectorRef) {
    }

    dataListSelect(data?: DataModel) {
        this.dataSelect = data || {
            check: false,
            code: "",
            period: "",
            year: "",
            startDate: "",
            endDate: "",
            status: "",
        }
        this.cdr.detectChanges()
    }

    dataListFilter() {
        return this.dataList.filter(x => {
            const match = x.code.includes(this.search) || x.period.includes(this.search);
            if (!match) x.check = false;
            return match;
        });
    }

    dataListCheck() {
        const dataCheck = this.dataListFilter();
        this.isDataListChecked = dataCheck.some(x => x.check);
        this.isDataListCheckedAll = dataCheck.length ? dataCheck.every(x => x.check) : false;
        this.numDataListChecked = dataCheck.filter(x => x.check).length;
    }

    dataListCheckAll() {
        const selectAll = this.isDataListCheckedAll;
        this.dataList.forEach(x => x.check = selectAll);
        this.dataListCheck();
    }

    searchChange() {
        this.currentPage = 1;
        const filteredData = this.dataListFilter();
        this.page = Array.from({ length: Math.ceil(filteredData.length / 10) }, (_, i) => i + 1);
        this.dataListCheck();
    }

}