import { ChangeDetectorRef, Component } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { ComEvaluationFactorsDetailModel, ComEvaluationFactorsModel, MyComEvaluationFactorsDetailModel, MyComEvaluationFactorsModel, MyCompetencyTypeModel } from 'src/app/shared/model/com-ealuation-factors.model';
import { ComEvaluationFactorsService } from 'src/app/shared/services/com-evaluation-factors.service';
@Component({
    selector: 'app-competency-define-evaluation-factors',
    templateUrl: './competency-define-evaluation-factors.component.html',
    styleUrls: ['./competency-define-evaluation-factors.component.scss']
})
export class CompetencyDefineEvaluationFactorsComponent {
    currentPage = 1
    page = Array.from({ length: 1 }, (_, i) => i + 1);
    search = ""
    comEvaluationFactors: { loading: boolean, dataList: ComEvaluationFactorsModel[] } = { loading: false, dataList: [] }
    comEvaluationFactorsTableHeader: string[] = ['JobLevel(JL)']
    constructor(private comEvaluationFactorsService: ComEvaluationFactorsService,
        private toastr: ToastrService,
        private cdr: ChangeDetectorRef
    ) { }
    ngOnInit(): void {
        this.getComEvaluationFactorsList()
    }
    getComEvaluationFactorsList() {
        this.comEvaluationFactors.loading = true
        this.comEvaluationFactorsTableHeader = ['JobLevel(JL)']
        this.comEvaluationFactorsService.getList().subscribe({
            next: response => {
                this.comEvaluationFactors.dataList = response.map(x => new MyComEvaluationFactorsModel(x))
                this.comEvaluationFactors.loading = false
                const maxItem = this.comEvaluationFactors.dataList.reduce((max, item) =>
                    item.comEvaluationFactorsList.length > max.comEvaluationFactorsList.length ? item : max,
                    this.comEvaluationFactors.dataList[0]
                );
                const comTypeIds = maxItem?.comEvaluationFactorsList.map(x => x.competencyType.competencyTypeId) || [];
                this.comEvaluationFactorsTableHeader = this.comEvaluationFactorsTableHeader.concat(maxItem?.comEvaluationFactorsList.map(x => x.competencyType.tdesc) || []).concat(['รวม'])
                this.comEvaluationFactors.dataList.forEach(x => {
                    while (x.comEvaluationFactorsList.length < 5) {
                        const usedTypes = x.comEvaluationFactorsList.map(y => y.competencyType.competencyTypeId);
                        const remainingTypes = comTypeIds.filter(type => !usedTypes.includes(type));
                        if (remainingTypes.length === 0) { break }
                        const competencyTypeId = remainingTypes[0];
                        x.comEvaluationFactorsList.push(
                            new MyComEvaluationFactorsDetailModel({ competencyType: new MyCompetencyTypeModel({ competencyTypeId }) })
                        )
                    }
                    x.comEvaluationFactorsList.sort((a, b) => +(a.competencyType.competencyTypeId) - +(b.competencyType.competencyTypeId))
                })
                this.searchChange()
                this.cdr.detectChanges()
            }, error: error => {
                this.comEvaluationFactors.loading = false
                this.cdr.detectChanges()
            }
        })
    }
    saveComEvaluationFactors() {
        this.comEvaluationFactors.loading = true
        const body = this.comEvaluationFactors.dataList.map(x => new MyComEvaluationFactorsModel({
            ...x,
            comEvaluationFactorsList: x.comEvaluationFactorsList.map(y => new MyComEvaluationFactorsDetailModel({
                ...y,
                comScore: +(y.comScore)
            }))
        }))
        this.comEvaluationFactorsService.post(body).subscribe({
            next: response => {
                if (response.success) {
                    this.showAlert(response.message, 'success')
                    this.getComEvaluationFactorsList()
                } else {
                    this.showAlert(response.message, 'error')
                    this.comEvaluationFactors.loading = false
                    this.cdr.detectChanges()
                }
            }, error: error => {
                this.showAlert(error.message, 'error')
                this.comEvaluationFactors.loading = false
                this.cdr.detectChanges()
            }
        })
    }
    clear() {
        this.comEvaluationFactors.dataList = this.comEvaluationFactors.dataList.map(x => new MyComEvaluationFactorsModel({
            ...x,
            comEvaluationFactorsList: x.comEvaluationFactorsList.map(y => new MyComEvaluationFactorsDetailModel({
                ...y,
                comScore: 0
            }))
        }))
    }
    calPmsEaluationFactors1Total(data: ComEvaluationFactorsDetailModel[]) {
        return data.reduce((sum, num) => sum + +(num.comScore), 0);
    }

    dataListFilter() {
        return this.comEvaluationFactors.dataList.filter(x => x.jl.plId.toLowerCase().includes(this.search.toLowerCase()))
    }

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

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

}
