import { ChangeDetectorRef, Component } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { MyPmsEvaluationFactorsModel, PmsEvaluationFactorsModel } from 'src/app/shared/model/pms-evaluation-factors.model';
import { MyPmsEvaluationFactors1Model, PmsEvaluationFactors1Model } from 'src/app/shared/model/pms-evaluation-factors1.model';
import { MyPmstypeModel } from 'src/app/shared/model/pmstype.model';
import { PmsEvaluationFactorsService } from 'src/app/shared/services/pms-evaluation-factors.service';

@Component({
    selector: 'app-define-evaluation-factors',
    templateUrl: './define-evaluation-factors.component.html',
    styleUrls: ['./define-evaluation-factors.component.scss']
})
export class DefineEvaluationFactorsComponent {
    currentPage = 1
    page = Array.from({ length: 1 }, (_, i) => i + 1);
    search = ""
    pmsEvaluationFactors: { loading: boolean, dataList: PmsEvaluationFactorsModel[] } = { loading: false, dataList: [] }
    pmsEvaluationFactorsTableHeader: string[] = ['JobLevelJL']
    constructor(private pmsEvaluationFactorsService: PmsEvaluationFactorsService,
        private toastr: ToastrService,
        private cdr: ChangeDetectorRef
    ) { }
    ngOnInit(): void {
        this.getPmsEvaluationFactorsList()
    }
    getPmsEvaluationFactorsList() {
        this.pmsEvaluationFactors.loading = true
        this.pmsEvaluationFactorsTableHeader = ['JobLevelJL']
        this.pmsEvaluationFactorsService.getList().subscribe({
            next: response => {
                this.pmsEvaluationFactors.dataList = response.map(x => new MyPmsEvaluationFactorsModel(x))
                this.pmsEvaluationFactors.loading = false
                const maxItem = this.pmsEvaluationFactors.dataList.reduce((max, item) =>
                    item.pmsEvaluationFactors1ModelList.length > max.pmsEvaluationFactors1ModelList.length ? item : max,
                    this.pmsEvaluationFactors.dataList[0]
                );
                const pmsTypeIds = maxItem?.pmsEvaluationFactors1ModelList.map(x => x.pmsType.pmsTypeId) || [];
                this.pmsEvaluationFactorsTableHeader = this.pmsEvaluationFactorsTableHeader.concat(maxItem?.pmsEvaluationFactors1ModelList.map(x => x.pmsType.tdesc) || []).concat(['Total'])
                this.pmsEvaluationFactors.dataList.forEach(x => {
                    while (x.pmsEvaluationFactors1ModelList.length < 5) {
                        const usedTypes = x.pmsEvaluationFactors1ModelList.map(y => y.pmsType.pmsTypeId);
                        const remainingTypes = pmsTypeIds.filter(type => !usedTypes.includes(type));
                        if (remainingTypes.length === 0) { break }
                        const pmsTypeId = remainingTypes[0];
                        x.pmsEvaluationFactors1ModelList.push(
                            new MyPmsEvaluationFactors1Model({ pmsType: new MyPmstypeModel({ pmsTypeId }) })
                        )
                    }
                    x.pmsEvaluationFactors1ModelList.sort((a, b) => +(a.pmsType.pmsTypeId) - +(b.pmsType.pmsTypeId))
                })
                this.searchChange()
                this.cdr.detectChanges()
            }, error: error => {
                this.pmsEvaluationFactors.loading = false
                this.cdr.detectChanges()
            }
        })
    }
    savePmsEvaluationFactors() {
        this.pmsEvaluationFactors.loading = true
        const body = this.pmsEvaluationFactors.dataList.map(x => new MyPmsEvaluationFactorsModel({
            ...x,
            pmsEvaluationFactors1ModelList: x.pmsEvaluationFactors1ModelList.map(y => new MyPmsEvaluationFactors1Model({
                ...y,
                pmsScore: +(y.pmsScore)
            }))
        }))
        this.pmsEvaluationFactorsService.post(body).subscribe({
            next: response => {
                if (response.success) {
                    this.showAlert(response.message, 'success')
                    this.getPmsEvaluationFactorsList()
                } else {
                    this.showAlert(response.message, 'error')
                    this.pmsEvaluationFactors.loading = false
                    this.cdr.detectChanges()
                }
            }, error: error => {
                this.showAlert(error.message, 'error')
                this.pmsEvaluationFactors.loading = false
                this.cdr.detectChanges()
            }
        })
    }
    clear() {
        this.pmsEvaluationFactors.dataList = this.pmsEvaluationFactors.dataList.map(x => new MyPmsEvaluationFactorsModel({
            ...x,
            pmsEvaluationFactors1ModelList: x.pmsEvaluationFactors1ModelList.map(y => new MyPmsEvaluationFactors1Model({
                ...y,
                pmsScore: 0
            }))
        }))
    }
    calPmsEvaluationFactors1Total(data: PmsEvaluationFactors1Model[]) {
        return data.reduce((sum, num) => sum + +(num.pmsScore), 0);
    }

    dataListFilter() {
        return this.pmsEvaluationFactors.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',
        })
    }

}
