import { ChangeDetectorRef, Component, ElementRef, EventEmitter, Input, Output, SimpleChanges, ViewChild } from '@angular/core';
import { CompetencyGradeModel, MyCompetencyGradeModel } from 'src/app/shared/model/competency-grades.model';
import { AppraisalService } from 'src/app/shared/services/appraisal.service';
import { EmployeeService } from 'src/app/shared/services/employee.service';
import { PmsGroupGradeService } from 'src/app/shared/services/pms-group-grade.service';
import { SettingAssessmentService } from 'src/app/shared/services/setting-assessment.service';
import { Part5Detail, Pms, PmsTopic } from 'src/app/shared/model/competency.model';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';
import { Location } from '@angular/common';
export interface Part8Model {
  id: number
  evaluationFactor: string,
  rawScore: number,
  factors: number
  scoreObtainedBoss: number
  scoreObtained: number
  netScoreBoss: number
  netScore: number
}
export interface LevelStarModel {
  evaluationFactor: string,
  rawScore: number,
  factors: number
  scoreObtainedBoss: number
  netScoreBoss: number
}
@Component({
  selector: 'app-pms-kpi',
  templateUrl: './pms-kpi.component.html',
  styleUrls: ['./pms-kpi.component.scss']
})
export class PmsKpiComponent {
  @Input() complete = false
  @Input() canSave = false
  @Input() inforWeight: Map<string, string> = new Map<string, string>()
  data8List: Part8Model[] = [{
    id: 1,
    evaluationFactor: "PART 1 : ประเมินผลการปฏิบัติงานตามนโยบายบริษัท (Corporate KPI)",
    rawScore: 100,
    factors: 0,
    scoreObtainedBoss: 0,
    netScoreBoss: 0,
    scoreObtained: 0,
    netScore: 0,
  }, {
    id: 2,
    evaluationFactor: "PART 2 : ประเมินตัวชี้วัดของหน่วยงาน (Department KPI)",
    rawScore: 100,
    factors: 0,
    scoreObtainedBoss: 0,
    netScoreBoss: 0,
    scoreObtained: 0,
    netScore: 0,
  }, {
    id: 3,
    evaluationFactor: "PART 3 : ประเมินตัวชี้วัดรายบุคคล (Individual KPI)",
    rawScore: 100,
    factors: 0,
    scoreObtainedBoss: 0,
    netScoreBoss: 0,
    scoreObtained: 0,
    netScore: 0,
  }, {
    id: 4,
    evaluationFactor: "PART 4 : ประเมินผลสมรรถนะที่สนับสนุนการปฏิบัติงาน (Competency)",
    rawScore: 100,
    factors: 0,
    scoreObtainedBoss: 0,
    netScoreBoss: 0,
    scoreObtained: 0,
    netScore: 0,
  }, {
    id: 5,
    evaluationFactor: "PART 5 : อัตราการเข้างาน (Time Attendance)",
    rawScore: 100,
    factors: 0,
    scoreObtainedBoss: 0,
    netScoreBoss: 0,
    scoreObtained: 0,
    netScore: 0,
  }, {
    id: 6,
    evaluationFactor: "PART 6 : งานที่ได้รับมอบหมายเพิ่มเติม (Cross Functional Project Assignment)",
    rawScore: 100,
    factors: 0,
    scoreObtainedBoss: 0,
    netScoreBoss: 0,
    scoreObtained: 0,
    netScore: 0,
  }, {
    id: 7,
    evaluationFactor: "PART 7 : กิจกรรมพิเศษ (Special Activities)",
    rawScore: 100,
    factors: 0,
    scoreObtainedBoss: 0,
    netScoreBoss: 0,
    scoreObtained: 0,
    netScore: 0,
  }]
  partShow: string[] = []
  partOpen: Map<string, boolean> = new Map<string, boolean>()
  partScore: Map<string, number> = new Map<string, number>()
  @Input() compentencyFormRemain = 0
  @Input() evaluateeId = ""
  @Input() evaluaterId = ""
  @Input() appraisalPms?: Pms
  @Input() canEdit = false
  @Input() currentStep = ""
  @Input() currentTap = ""
  @Input() currentPart = ""
  @Input() dateIso = ""
  @Output() kpiFormRemain: EventEmitter<any> = new EventEmitter<any>();
  @Output() kpiForm: EventEmitter<any> = new EventEmitter<any>();
  @Output() scorePartBoss: EventEmitter<any> = new EventEmitter<any>();
  @Output() scorePart: EventEmitter<any> = new EventEmitter<any>();
  groupGrade: { loading: boolean, dataList: CompetencyGradeModel[] } = { loading: false, dataList: [] }
  @ViewChild('scrollContainer') scrollContainer!: ElementRef;
  @Output() scrollToMenuId: EventEmitter<any> = new EventEmitter<any>();
  tableHover: Map<string, boolean> = new Map<string, boolean>()
  constructor(private location: Location,
    private appraisalService: AppraisalService,
    private pmsGroupGradeService: PmsGroupGradeService,
    private employeeService: EmployeeService,
    private cdr: ChangeDetectorRef,
    private settingAssessmentService: SettingAssessmentService,
    private route: ActivatedRoute
  ) {
  }
  resetData8List() {
    this.data8List = [{
      id: 1,
      evaluationFactor: "Part 1 : ประเมินผลการปฏิบัติงานตามนโยบายบริษัท (Corporate KPI)",
      rawScore: 100,
      factors: 0,
      scoreObtainedBoss: 0,
      netScoreBoss: 0,
      scoreObtained: 0,
      netScore: 0,
    }, {
      id: 2,
      evaluationFactor: "Part 2 : ประเมินผลการปฏิบัติงานประจำ (Department KPI)",
      rawScore: 100,
      factors: 0,
      scoreObtainedBoss: 0,
      netScoreBoss: 0,
      scoreObtained: 0,
      netScore: 0,
    }, {
      id: 3,
      evaluationFactor: "Part 3 : ประเมินผลการปฏิบัติงานประจำ (Individual KPI)",
      rawScore: 100,
      factors: 0,
      scoreObtainedBoss: 0,
      netScoreBoss: 0,
      scoreObtained: 0,
      netScore: 0,
    }, {
      id: 4,
      evaluationFactor: "Part 4 : ประเมินผลสมรรถนะที่สนับสนุนการปฏิบัติงาน (Competency)",
      rawScore: 100,
      factors: 0,
      scoreObtainedBoss: 0,
      netScoreBoss: 0,
      scoreObtained: 0,
      netScore: 0,
    }, {
      id: 5,
      evaluationFactor: "Part 5 : อัตราการเข้างาน (Time Attendance)",
      rawScore: 100,
      factors: 0,
      scoreObtainedBoss: 0,
      netScoreBoss: 0,
      scoreObtained: 0,
      netScore: 0,
    }, {
      id: 6,
      evaluationFactor: "Part 6 : งานที่ได้รับมอบหมายเพิ่มเติม (Cross Functional Project Assignment)",
      rawScore: 100,
      factors: 0,
      scoreObtainedBoss: 0,
      netScoreBoss: 0,
      scoreObtained: 0,
      netScore: 0,
    }, {
      id: 7,
      evaluationFactor: "Part 7 : กิจกรรมพิเศษ (Special Activities)",
      rawScore: 100,
      factors: 0,
      scoreObtainedBoss: 0,
      netScoreBoss: 0,
      scoreObtained: 0,
      netScore: 0,
    }]
  }
  getTargetDetailValue(item: any): string {
    const targetDetail = ['', 'targetEdetail', 'targetDdetail', 'targetCdetail', 'targetBdetail', 'targetAdetail']
    const index = this.partScore.get(item.groupAssessment1.pmsTopic.pmsTopicId) ?? item.scoreTopicExpectation;
    const key = targetDetail[index ?? 0] as keyof PmsTopic;
    return item.groupAssessment1.pmsTopic[key];
  }
  getTargetDetailValuePart5(item: any): string {
    const targetDetail = ['', 'targetEDetail', 'targetDDetail', 'targetCDetail', 'targetBDetail', 'targetADetail']
    const index = this.partScore.get(item.tdesc) ?? item.pmsWorkingTimeScore;
    const key = targetDetail[index ?? 0] as keyof Part5Detail;
    return item[key];
  }
  ngOnInit(): void {
    this.partOpen.clear()
    this.resetData8List()
    const menuList = Array.from({ length: 7 }, (_, i) => i + 1)
      .filter(i => (this.appraisalPms?.[`part${i}Detail` as keyof Pms] as any)?.length)
      .map(i => `PART ${i}`)
    this.data8List = this.data8List.filter(e => menuList.some(e2 => e.id == +e2.replace('PART ', '')))
    if (this.currentTap == 'Performance') {
      this.partShow = menuList
    } else {
      if (this.data8List.length) {
        this.partShow = ['PART 8', 'PART 9', 'PART 10']
      } else {
        this.partShow = ['PART 9', 'PART 10']
      }
    }
    this.partShow.forEach(x => {
      this.partOpen.set(x, false)
    })
    this.getPmsGroupGradeList()
    this.getAppraisalPmsForm()
    this.allFormRemain()
    this.sendScorePart()
  }
  ngOnChanges(changes: SimpleChanges): void {
    if (changes['currentTap']?.currentValue || changes['appraisalPms']?.currentValue) {
      this.partOpen.clear()
      this.resetData8List()
      const menuList = Array.from({ length: 7 }, (_, i) => i + 1)
        .filter(i => (this.appraisalPms?.[`part${i}Detail` as keyof Pms] as any)?.length)
        .map(i => `PART ${i}`)
      this.data8List = this.data8List.filter(e => menuList.some(e2 => e.id == +e2.replace('PART ', '')))
      if (this.currentTap == 'Performance') {
        this.partShow = menuList
      } else {
        if (this.data8List.length) {
          this.partShow = ['PART 8', 'PART 9', 'PART 10']
        } else {
          this.partShow = ['PART 9', 'PART 10']
        }
      }
      this.partShow.forEach(x => {
        this.partOpen.set(x, false)
      })

      this.getAppraisalPmsForm()
      this.allFormRemain()
      this.sendScorePart()
    }
    if (changes['currentPart']?.currentValue) {
      this.route.paramMap.subscribe((params: ParamMap) => {
        const pathLink = params.get('part')
        if (pathLink?.includes('kpi-sum')) {
          const path = Number(pathLink.split('kpi-sum')[1])
          if (path) {
            this.currentPart = 'PART ' + path
            this.partOpen.set('PART ' + path, true)
            this.scrollToMenu('menu-part-' + path)
          }
        }
      });
    }
  }

  getAppraisalPmsForm() {
    this.data8List.forEach((x, i) => {
      if (x.id == 1 && this.appraisalPms?.part1Percentage) {
        x.factors = this.appraisalPms.part1Percentage
      } else if (x.id == 2 && this.appraisalPms?.part2Percentage) {
        x.factors = this.appraisalPms.part2Percentage
      } else if (x.id == 3 && this.appraisalPms?.part3Percentage) {
        x.factors = this.appraisalPms.part3Percentage
      } else if (x.id == 4 && this.appraisalPms?.part4Percentage) {
        x.factors = this.appraisalPms.part4Percentage
      } else if (x.id == 5 && this.appraisalPms?.part5Percentage) {
        x.factors = this.appraisalPms.part5Percentage
      } else if (x.id == 6 && this.appraisalPms?.part6Percentage) {
        x.factors = this.appraisalPms.part6Percentage
      } else if (x.id == 7 && this.appraisalPms?.part7Percentage) {
        x.factors = this.appraisalPms.part7Percentage
      }
    })
    if (!this.appraisalPms?.part1Detail) {
      this.data8List = this.data8List.filter(item => item.id !== 1)
    }
    if (!this.appraisalPms?.part2Detail) {
      this.data8List = this.data8List.filter(item => item.id !== 2)
    }
    if (!this.appraisalPms?.part3Detail) {
      this.data8List = this.data8List.filter(item => item.id !== 3)
    }
    if (!this.appraisalPms?.part4Detail) {
      this.data8List = this.data8List.filter(item => item.id !== 4)
    }
    if (!this.appraisalPms?.part5Detail) {
      this.data8List = this.data8List.filter(item => item.id !== 5)
    }
    if (!this.appraisalPms?.part6Detail) {
      this.data8List = this.data8List.filter(item => item.id !== 6)
    }
    if (!this.appraisalPms?.part7Detail) {
      this.data8List = this.data8List.filter(item => item.id !== 7)
    }
    this.changePercentage()
    if (this.appraisalPms) {
      switch (this.currentStep) {
        case ("0"): {
          this.appraisalPms.apsassessyDate = this.dateIso
          break
        }
        case ("1"): {
          this.appraisalPms.apsapprove1Date = this.dateIso
          break
        }
        case ("2"): {
          this.appraisalPms.apsapprove2Date = this.dateIso
          break
        }
        case ("3"): {
          this.appraisalPms.apsapprove3Date = this.dateIso
          break
        }
        case ("4"): {
          this.appraisalPms.apsapprove4Date = this.dateIso
          break
        }
        case ("5"): {
          this.appraisalPms.apsapprove5Date = this.dateIso
          break
        }
        default: { return }
      }
    }
    this.cdr.detectChanges()
  }


  getPmsGroupGradeList() {
    this.groupGrade.loading = true
    this.pmsGroupGradeService.getGradeList().subscribe({
      next: response => {
        this.groupGrade.dataList = response.map(x => new MyCompetencyGradeModel(x))
        this.groupGrade.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.groupGrade.loading = false
        this.cdr.detectChanges()
      }
    })
  }


  calRawScore(data?: any) {
    if (data) {
      return data.reduce((sum: number, item: any) => sum + item.weight * 5, 0).toFixed(2);
    }
    return "0.00"
  }
  calWeigth(data?: any) {
    if (data) {
      return data.reduce((sum: number, item: any) => sum + item.weight, 0).toFixed(2);
    }
    return "0.00"
  }
  calExpectationScore(data?: any) {
    if (data) {
      return data.reduce((sum: number, item: any) => sum + item.scoreTopicExpectationBoss, 0).toFixed(2);
    }
    return "0.00"
  }
  calExpectationTotalScore(data?: any) {
    if (data) {
      return data.reduce((sum: number, item: any) => sum + (item.scoreTopicExpectation * item.weight), 0).toFixed(2);
    }
    return "0.00"
  }
  calExpectationTotalScoreBoss(data?: any) {
    if (data) {
      return data.reduce((sum: number, item: any) => sum + (item.scoreTopicExpectationBoss * item.weight), 0).toFixed(2);
    }
    return "0.00"
  }
  calPercentage(A: number, B: number) {
    if (B > 0) {
      return ((A / B) * 100).toFixed(2);
    }
    return "0.00"
  }
  changePercentage() {
    this.data8List.forEach(x => {
      if (x.id == 1 && this.appraisalPms?.part1Detail) {
        x.scoreObtained = +this.calPercentage(this.calExpectationTotalScore(this.appraisalPms?.part1Detail), this.calRawScore(this.appraisalPms?.part1Detail))
        x.scoreObtainedBoss = +this.calPercentage(this.calExpectationTotalScoreBoss(this.appraisalPms?.part1Detail), this.calRawScore(this.appraisalPms?.part1Detail))
        if (this.appraisalPms) {
          this.appraisalPms.part1SumScore = x.scoreObtained
          this.appraisalPms.part1SumScoreBoss = x.scoreObtainedBoss
        }
      } else if (x.id == 2 && this.appraisalPms?.part2Detail) {
        x.scoreObtained = +this.calPercentage(this.calExpectationTotalScore(this.appraisalPms?.part2Detail), this.calRawScore(this.appraisalPms?.part2Detail))
        x.scoreObtainedBoss = +this.calPercentage(this.calExpectationTotalScoreBoss(this.appraisalPms?.part2Detail), this.calRawScore(this.appraisalPms?.part2Detail))
        if (this.appraisalPms) {
          this.appraisalPms.part2SumScore = x.scoreObtained
          this.appraisalPms.part2SumScoreBoss = x.scoreObtainedBoss
        }
      } else if (x.id == 3 && this.appraisalPms?.part3Detail) {
        x.scoreObtained = +this.calPercentage(this.calExpectationTotalScore(this.appraisalPms?.part3Detail), this.calRawScore(this.appraisalPms?.part3Detail))
        x.scoreObtainedBoss = +this.calPercentage(this.calExpectationTotalScoreBoss(this.appraisalPms?.part3Detail), this.calRawScore(this.appraisalPms?.part3Detail))
        if (this.appraisalPms) {
          this.appraisalPms.part3SumScore = x.scoreObtained
          this.appraisalPms.part3SumScoreBoss = x.scoreObtainedBoss
        }
      } else if (x.id == 4 && this.appraisalPms?.part4Detail) {
        x.scoreObtained = +this.calPercentage(this.calExpectationTotalScoreBossPart4(this.appraisalPms?.part4Detail), this.calRawScorePart4(this.appraisalPms?.part4Detail))
        x.scoreObtainedBoss = +this.calPercentage(this.calExpectationTotalScoreBossPart4(this.appraisalPms?.part4Detail), this.calRawScorePart4(this.appraisalPms?.part4Detail))
        if (this.appraisalPms) {
          this.appraisalPms.part4SumScore = x.scoreObtained
          this.appraisalPms.part4SumScoreBoss = x.scoreObtainedBoss
        }
      } else if (x.id == 5 && this.appraisalPms?.part5Detail) {
        x.scoreObtained = +this.calPercentage(this.calExpectationTotalScorePart5(this.appraisalPms?.part5Detail), this.calRawScorePart5(this.appraisalPms?.part5Detail))
        x.scoreObtainedBoss = +this.calPercentage(this.calExpectationTotalScoreBossPart5(this.appraisalPms?.part5Detail), this.calRawScorePart5(this.appraisalPms?.part5Detail))
        if (this.appraisalPms) {
          this.appraisalPms.part5SumScore = x.scoreObtained
          this.appraisalPms.part5SumScoreBoss = x.scoreObtainedBoss
        }
      } else if (x.id == 6 && this.appraisalPms?.part6Detail) {
        x.scoreObtained = +this.calPercentage(this.calExpectationTotalScore(this.appraisalPms?.part6Detail), this.calRawScore(this.appraisalPms?.part6Detail))
        x.scoreObtainedBoss = +this.calPercentage(this.calExpectationTotalScoreBoss(this.appraisalPms?.part6Detail), this.calRawScore(this.appraisalPms?.part6Detail))
        if (this.appraisalPms) {
          this.appraisalPms.part6SumScore = x.scoreObtained
          this.appraisalPms.part6SumScoreBoss = x.scoreObtainedBoss
        }
      } else if (x.id == 7 && this.appraisalPms?.part7Detail) {
        x.scoreObtained = +this.calPercentage(this.calExpectationTotalScore(this.appraisalPms?.part7Detail), this.calRawScore(this.appraisalPms?.part7Detail))
        x.scoreObtainedBoss = +this.calPercentage(this.calExpectationTotalScoreBoss(this.appraisalPms?.part7Detail), this.calRawScore(this.appraisalPms?.part7Detail))
        if (this.appraisalPms) {
          this.appraisalPms.part7SumScore = x.scoreObtained
          this.appraisalPms.part7SumScoreBoss = x.scoreObtainedBoss
        }
      }
      x.netScore = x.factors / 100 * x.scoreObtained
      x.netScoreBoss = x.factors / 100 * x.scoreObtainedBoss
    })
    this.setGradeScore()
  }
  setGradeScore() {
    const gradeScore = this.groupGrade.dataList.find(item => Math.ceil(+this.calNetScoreBoss()) >= item.gradeMinScore && Math.ceil(+this.calNetScoreBoss()) <= item.gradeMaxScore);
    if (this.appraisalPms && gradeScore) {
      this.appraisalPms.gradeScore = gradeScore.gradeDetail
    }
  }

  calFactors() {
    return this.data8List.reduce((sum: number, item: any) => sum + item.factors, 0).toFixed(2);
  }
  calScoreObtained() {
    return this.data8List.reduce((sum: number, item: any) => sum + item.scoreObtained, 0).toFixed(2);
  }

  calScoreObtainedBoss() {
    return this.data8List.reduce((sum: number, item: any) => sum + item.scoreObtained, 0).toFixed(2);
  }
  calNetScoreBoss() {
    if (this.appraisalPms) {
      this.appraisalPms.netScoreBoss = +(this.data8List.reduce((sum: number, item: any) => sum + item.netScore, 0).toFixed(2));
      return this.appraisalPms.netScoreBoss
    }
    return "0.00"
  }
  calNetScore() {
    if (this.appraisalPms) {
      this.appraisalPms.netScore = +(this.data8List.reduce((sum: number, item: any) => sum + item.netScore, 0).toFixed(2));
      return this.appraisalPms.netScore
    }
    return "0.00"
  }

  calAverage(score: number) {
    const roundedScore = score % 1 <= 0.5 ? Math.floor(score) : Math.round(score);
    if (roundedScore >= 90 && roundedScore <= 100) {
      return 5;
    } else if (roundedScore >= 80 && roundedScore <= 89) {
      return 4;
    } else if (roundedScore >= 60 && roundedScore <= 79) {
      return 3;
    } else if (roundedScore >= 40 && roundedScore <= 59) {
      return 2;
    } else if (roundedScore >= 1 && roundedScore <= 39) {
      return 1;
    } else {
      return 0;
    }
  }

  calRawScorePart4(data?: any) {
    if (data) {
      return data.reduce((sum: number, item: any) => sum + item.competencyType.weight * 5, 0).toFixed(2);
    }
    return "0.00"
  }

  calWeigthPart4(data?: any) {
    if (data) {
      return data.reduce((sum: number, item: any) => sum + item.competencyType.weight, 0).toFixed(2);
    }
    return "0.00"
  }
  calExpectationScorePart4(data?: any) {
    if (data) {
      return data.reduce((sum: number, item: any) => sum + this.calAverage(this.convertToNumber(this.inforWeight.get(item.competencyType.shortName)
        !== 'null' ? this.inforWeight.get(item.competencyType.shortName) : '0')), 0).toFixed(2);
    }
    return "0.00"
  }
  calExpectationTotalScoreBossPart4(data?: any) {
    if (data) {
      return data.reduce((sum: number, item: any) => sum + (item.competencyType.weight * this.calAverage(this.convertToNumber(this.inforWeight.get(item.competencyType.shortName)
        !== 'null' ? this.inforWeight.get(item.competencyType.shortName) : '0'))), 0).toFixed(2);
    }
    return "0.00"
  }


  calRawScorePart5(data?: any) {
    if (data) {
      return data.reduce((sum: number, item: any) => sum + item.weight * 5, 0).toFixed(2);
    }
    return "0.00"
  }
  calWeigthPart5(data?: any) {
    if (data) {
      return data.reduce((sum: number, item: any) => sum + item.weight, 0).toFixed(2);
    }
    return "0.00"
  }
  calExpectationScorePart5(data?: any) {
    if (data) {
      return data.reduce((sum: number, item: any) => sum + item.pmsWorkingTimeScoreBoss, 0).toFixed(2);
    }
    return "0.00"
  }
  calExpectationTotalScorePart5(data?: any) {
    if (data) {
      return data.reduce((sum: number, item: any) => sum + (item.pmsWorkingTimeScore * item.weight), 0).toFixed(2);
    }
    return "0.00"
  }
  calExpectationTotalScoreBossPart5(data?: any) {
    if (data) {
      return data.reduce((sum: number, item: any) => sum + (item.pmsWorkingTimeScoreBoss * item.weight), 0).toFixed(2);
    }
    return "0.00"
  }
  setScorePart5(item: any, score: number) {
    if (this.canEdit) {
      if (this.evaluaterId == this.evaluateeId) {
        item.pmsWorkingTimeScore = score
        item.pmsWorkingTimeScoreBoss = score
      } else {
        item.pmsWorkingTimeScoreBoss = score
      }
      this.changePercentage()
    }
  }


  numberFixed2(data?: number) {
    if (data) {
      return data.toFixed(2)
    }
    return "0.00"
  }

  setScore(item: any, score: number) {
    if (this.canEdit) {
      if (this.evaluaterId == this.evaluateeId) {
        item.scoreTopicExpectation = score
        item.scoreTopicExpectationBoss = score
      } else {
        item.scoreTopicExpectationBoss = score
      }
      this.changePercentage()
    }
  }

  convertDate(dateInput?: string | Date): string {
    let date = new Date()
    if (dateInput) {
      if (typeof dateInput === 'string') {
        const [year, month, day] = dateInput.split('-').map(Number);
        date = new Date(year, month - 1, day);
      } else {
        date = dateInput
      }
    } else {
      return ''
    }
    return date?.toLocaleDateString('th-TH', { day: 'numeric', month: 'long', year: 'numeric' }) || ''
  }



  toggleAllParts(check: boolean, part?: string) {
    this.partOpen.forEach((_, key) => {
      if (part) {
        if (part == key) {
          this.partOpen.set(key, check)
        } else {
          if (check) {
            this.currentPart = part
            this.partOpen.set(key, false)
          } else {
            this.currentPart = ''
          }
        }
      } else {
        this.partOpen.set(key, check)
        this.currentPart = ''
      }
    })
  }

  part1Remain() {
    if (this.appraisalPms?.part1Detail) {
      const remain = this.appraisalPms.part1Detail.filter(x =>
        x.scoreTopicExpectation == null && x.scoreTopicExpectationBoss == null
      ).length
      return remain
    }
    return 2
  }

  part2Remain() {
    if (this.appraisalPms?.part2Detail) {
      const remain = this.appraisalPms.part2Detail.filter(x =>
        x.scoreTopicExpectation == null && x.scoreTopicExpectationBoss == null
      ).length
      return remain
    }
    return 0
  }

  part3Remain() {
    if (this.appraisalPms?.part3Detail) {
      const remain = this.appraisalPms.part3Detail.filter(x =>
        x.scoreTopicExpectation == null && x.scoreTopicExpectationBoss == null
      ).length
      return remain
    }
    return 0
  }

  part5Remain() {
    if (this.appraisalPms?.part5Detail) {
      const remain = this.appraisalPms.part5Detail.filter(x =>
        x.pmsWorkingTimeScore == 0 && x.pmsWorkingTimeScoreBoss == 0
      ).length
      return remain
    }
    return 0
  }

  part6Remain() {
    if (this.appraisalPms?.part6Detail) {
      const remain = this.appraisalPms.part6Detail.filter(x =>
        x.scoreTopicExpectation == null && x.scoreTopicExpectationBoss == null
      ).length
      return remain
    }
    return 0
  }

  part7Remain() {
    if (this.appraisalPms?.part7Detail) {
      const remain = this.appraisalPms.part7Detail.filter(x =>
        x.scoreTopicExpectation == null && x.scoreTopicExpectationBoss == null
      ).length
      return remain
    }
    return 0
  }
  allFormRemain() {
    const parts = [
      { detail: this.appraisalPms?.part1Detail, fn: () => this.part1Remain() },
      { detail: this.appraisalPms?.part2Detail, fn: () => this.part2Remain() },
      { detail: this.appraisalPms?.part3Detail, fn: () => this.part3Remain() },
      { detail: this.appraisalPms?.part4Detail, fn: () => this.compentencyFormRemain },
      { detail: this.appraisalPms?.part5Detail, fn: () => this.part5Remain() },
      { detail: this.appraisalPms?.part6Detail, fn: () => this.part6Remain() },
      { detail: this.appraisalPms?.part7Detail, fn: () => this.part7Remain() },
    ]
    const remainList = parts.filter(p => p.detail?.length).map(p => p.fn())
    const remain = remainList.filter(data => data != 0).length
    this.kpiForm.emit(this.appraisalPms)
    this.kpiFormRemain.emit(remain)
  }

  remainList() {
    const remainMap: Record<string, () => number> = {
      'PART 1': () => this.part1Remain(),
      'PART 2': () => this.part2Remain(),
      'PART 3': () => this.part3Remain(),
      'PART 4': () => this.compentencyFormRemain,
      'PART 5': () => this.part5Remain(),
      'PART 6': () => this.part6Remain(),
      'PART 7': () => this.part7Remain(),
    }
    const remain = this.partShow.map(part => remainMap[part]?.() ?? 0)
    return remain
  }

  sendScorePart() {
    if (this.appraisalPms) {
      const gradeScore = this.groupGrade.dataList.find(item => Math.ceil(+this.calNetScoreBoss()) >= item.gradeMinScore && Math.ceil(+this.calNetScoreBoss()) <= item.gradeMaxScore);
      const scoreBoss = this.data8List.map((x, i) => ({ text: x.evaluationFactor.match(/Part\s*\d+/)?.[0].toUpperCase(), score: this.numberFixed2(x.netScoreBoss) }))
        .concat([{ text: "NetScore", score: this.calNetScoreBoss() + '' }, { text: "Grade", score: gradeScore?.gradeDetail || '' }])
      const score = this.data8List.map((x, i) => ({ text: x.evaluationFactor.match(/Part\s*\d+/)?.[0].toUpperCase(), score: this.numberFixed2(x.netScore) }))
        .concat([{ text: "NetScore", score: this.calNetScore() + '' }, { text: "Grade", score: gradeScore?.gradeDetail || '' }])
      this.scorePartBoss.emit(scoreBoss)
      this.scorePart.emit(score)
    }
  }

  scrollToMenu(id: string) {
    this.scrollToMenuId.emit(id);
  }

  convertToNumber(value: any): number {
    if (value === null || value === undefined) {
      return 0;
    }

    // ถ้า value เป็น string ที่เป็นตัวเลขล้วน เช่น "123", "45.6"
    if (typeof value === 'string' && !isNaN(Number(value.trim()))) {
      return Number(value);
    }

    // ถ้าเป็น number อยู่แล้ว
    if (typeof value === 'number') {
      return value;
    }

    // ถ้าอย่างอื่นที่ไม่ใช่ตัวเลข
    return 0;
  }
}
