import { ViewportScroller } from '@angular/common';
import { ChangeDetectorRef, Component, ElementRef, EventEmitter, Input, OnInit, Output, SimpleChanges, ViewChild } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { Competency, MasfromEvaluationAssessment2List } from 'src/app/shared/model/competency.model';
import { EmployeeModel, MyEmployeeModel } from 'src/app/shared/model/employee.model';
import { SettingAssessmentModel, MySettingAssessmentModel } from 'src/app/shared/model/setting-assessment.model';
import { AppraisalService } from 'src/app/shared/services/appraisal.service';
import { EmployeeService } from 'src/app/shared/services/employee.service';
import { FileService } from 'src/app/shared/services/file.service';
import { SettingAssessmentService } from 'src/app/shared/services/setting-assessment.service';
import Swal from 'sweetalert2';
@Component({
  selector: 'app-pms-competency',
  templateUrl: './pms-competency.component.html',
  styleUrls: ['./pms-competency.component.scss']
})
export class PmsCompetencyComponent {
  @Input() complete = false
  @Input() fCurrentPart = ""
  currentPart = ""
  @Input() canSave = false
  @Input() evaluateeId = ""
  @Input() evaluaterId = ""
  @Input() appraisalCompentencyList: Competency[] = []
  appraisalCompentencyIndex = 0
  @Output() sendReturnPath: EventEmitter<any> = new EventEmitter<any>();
  @Output() compentencyFormRemain: EventEmitter<any> = new EventEmitter<any>();
  @Output() compentencyForm: EventEmitter<any> = new EventEmitter<any>();
  @Output() compentencyWeightTotalBoss: EventEmitter<any> = new EventEmitter<any>();
  @Output() compentencyScoreBoss: EventEmitter<any> = new EventEmitter<any>();
  @Output() compentencyScore: EventEmitter<any> = new EventEmitter<any>();
  @Output() compentencyWeightScoreBoss: EventEmitter<any> = new EventEmitter<any>();
  @Output() compentencyWeightTotal: EventEmitter<any> = new EventEmitter<any>();
  @Output() compentencyWeightScore: EventEmitter<any> = new EventEmitter<any>();
  @Output() compentencyGapBoss: EventEmitter<any> = new EventEmitter<any>();
  @Output() compentencyGap: EventEmitter<any> = new EventEmitter<any>();
  @Output() sendInforWeightBoss: EventEmitter<any> = new EventEmitter<any>();
  @Output() sendInforWeight: EventEmitter<any> = new EventEmitter<any>();
  @Output() sendInforGapBoss: EventEmitter<any> = new EventEmitter<any>();
  @Output() sendInforGap: EventEmitter<any> = new EventEmitter<any>();
  @Input() canEdit = false
  @Input() currentStep = ""
  @Input() dateIso = ""
  @Input() currentTap = ""
  hoveredCode: string | null = null;
  hoveredCode2: string | null = null;

  tableHover: Map<string, boolean> = new Map<string, boolean>()
  setting: { loading: boolean, data: SettingAssessmentModel } = { loading: false, data: new MySettingAssessmentModel() }

  checkSheet: {
    score: string[],
    condition: string[]
  }[] = [{
    score: ["หากได้คะแนน 90 - 100% ถือว่า Gap +1", "หากได้คะแนน 80 - 89% ถือว่า ไม่มี Gap", "หากได้คะแนน 60 - 79% ถือว่า Gap - 1", "หากได้คะแนน 40 - 59% ถือว่า Gap -2", "หากได้คะแนน 0 - 39% ถือว่า Gap - 3"],
    condition: ["1.หากได้คะแนนสูงกว่า 80% แต่มี 3 2 หรือ 1 ด้วย ถือว่า Gap -1", "2.หากได้คะแนนต่ำกว่า 80% แต่มี 4 และ 5 ให้คิด Gap ตาม %", "3.คะแนนต่ำกว่า 80% แต่มี 2 และ 1 ให้คิด Gap ตาม %"],
  }]
  scoreDescriptions = [
    '',
    'ทำได้ต่ำกว่าความคาดหวัง ในระดับถัดลงมา 1 ระดับ จำนวน 1-2 ข้อ',
    'ทำได้ต่ำกว่าความคาดหวัง ในระดับถัดลงมา 1 ระดับ จำนวน 3-5 ข้อ',
    'ได้ตามความคาดหวัง 1-2 ข้อ',
    'ได้ตามความคาดหวัง 3-4 ข้อ',
    'ได้ตามความคาดหวัง 5 ข้อ',
    'ได้เกินความคาดหวัง ในระดับถัดขึ้นไป 1 ระดับ จำนวน 2-3 ข้อ',
    'ได้เกินความคาดหวัง ในระดับถัดขึ้นไป 1 ระดับ จำนวน 4-5 ข้อ'
  ];
  evaluatee: { loading: boolean, data: EmployeeModel } = { loading: false, data: new MyEmployeeModel() }
  biOpen: Map<string, boolean> = new Map<string, boolean>()
  biScore: Map<string, number> = new Map<string, number>()
  @ViewChild('scrollContainer') scrollContainer!: ElementRef;

  inforWeightBoss: Map<string, string> = new Map<string, string>()
  inforGapBoss: Map<string, string> = new Map<string, string>()
  inforWeight: Map<string, string> = new Map<string, string>()
  inforGap: Map<string, string> = new Map<string, string>()


  @Output() scrollToMenuId: EventEmitter<any> = new EventEmitter<any>();
  constructor(private appraisalService: AppraisalService,
    private employeeService: EmployeeService,
    private cdr: ChangeDetectorRef,
    private viewScroller: ViewportScroller,
    private settingAssessmentService: SettingAssessmentService,
    private fileService: FileService,
    private toastr: ToastrService
  ) {
  }
  ngOnInit(): void {
    if (this.appraisalCompentencyList.length) {
      this.currentPart = this.fCurrentPart == '' ? this.appraisalCompentencyList[0].comType : this.fCurrentPart
    }
    this.getAppraisalCompentencyForm(0)
    this.getSettingList()
    this.getEvaluatee()
  }
  ngOnChanges(changes: SimpleChanges): void {
    if (changes['currentTap']?.currentValue || changes['appraisalCompentencyList']?.currentValue) {
      if (this.appraisalCompentencyList.length) {
        this.currentPart = this.fCurrentPart == '' ? this.appraisalCompentencyList[0].comType : this.fCurrentPart
      }
      this.getAppraisalCompentencyForm(0)
    }
  }

  getEvaluatee() {
    this.evaluatee.loading = true
    this.employeeService.getWorkingById(this.evaluateeId).subscribe({
      next: response => {
        this.evaluatee.data = new MyEmployeeModel(response)
        this.evaluatee.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.evaluatee.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  getSettingList() {
    this.setting.loading = true
    this.settingAssessmentService.get().subscribe({
      next: response => {
        this.setting.data = new MySettingAssessmentModel(response)
        this.setting.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.setting.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  getAppraisalCompentencyForm(index: number) {
    if (this.appraisalCompentencyList.length) {
      this.appraisalCompentencyIndex = index
      if (this.fCurrentPart) {
        this.currentPart = this.fCurrentPart
        this.fCurrentPart = ''
      } else {
        this.currentPart = this.appraisalCompentencyList[this.appraisalCompentencyIndex].comType
      }
      this.biOpen.clear()
      this.appraisalCompentencyFilter().forEach((x, i) => {
        this.biOpen.set(x.groupAssessment1.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.competencyTopic.competencyTopicId, false)
        const isLast = i === this.appraisalCompentencyFilter().length - 1;
        if (isLast) {
          this.biOpen.set("สรุป", false)
        }
      })
      this.cdr.detectChanges()
      switch (this.currentStep) {
        case ("0"): {
          this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].apsassessyDate = this.dateIso
          break
        }
        case ("1"): {
          this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].apsapprove1Date = this.dateIso
          break
        }
        case ("2"): {
          this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].apsapprove2Date = this.dateIso
          break
        }
        case ("3"): {
          this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].apsapprove3Date = this.dateIso
          break
        }
        case ("4"): {
          this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].apsapprove4Date = this.dateIso
          break
        }
        case ("5"): {
          this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].apsapprove5Date = this.dateIso
          break
        }
        default: { return }
      }
      this.calweightScore()
      this.cdr.detectChanges()
    }
  }
  appraisalCompentencyFilter() {
    return this.appraisalCompentencyList[this.appraisalCompentencyIndex]?.masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List || []
  }

  calweightScore() {
    if (this.evaluaterId != this.evaluateeId || this.currentStep != '0') {
      if (this.appraisalCompentencyList[this.appraisalCompentencyIndex]?.masfromEvaluationAssessment1List[0]) {
        this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore1 = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter((y: any) => y.competencyBehavioral.scoreTopicExpectation == 1).length).reduce((acc: any, num: any) => acc + num, 0)
        this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore2 = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter((y: any) => y.competencyBehavioral.scoreTopicExpectation == 2).length).reduce((acc: any, num: any) => acc + num, 0)
        this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore3 = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter((y: any) => y.competencyBehavioral.scoreTopicExpectation == 3).length).reduce((acc: any, num: any) => acc + num, 0)
        this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore4 = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter((y: any) => y.competencyBehavioral.scoreTopicExpectation == 4).length).reduce((acc: any, num: any) => acc + num, 0)
        this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore5 = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter((y: any) => y.competencyBehavioral.scoreTopicExpectation == 5).length).reduce((acc: any, num: any) => acc + num, 0)
        this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore6 = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter((y: any) => y.competencyBehavioral.scoreTopicExpectation == 6).length).reduce((acc: any, num: any) => acc + num, 0)
        this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore7 = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter((y: any) => y.competencyBehavioral.scoreTopicExpectation == 7).length).reduce((acc: any, num: any) => acc + num, 0)
      }
    }
    if (this.appraisalCompentencyList[this.appraisalCompentencyIndex]?.masfromEvaluationAssessment1List[0]) {
      this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore1Boss = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter((y: any) => y.competencyBehavioral.scoreTopicExpectationBoss == 1).length).reduce((acc: any, num: any) => acc + num, 0)
      this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore2Boss = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter((y: any) => y.competencyBehavioral.scoreTopicExpectationBoss == 2).length).reduce((acc: any, num: any) => acc + num, 0)
      this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore3Boss = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter((y: any) => y.competencyBehavioral.scoreTopicExpectationBoss == 3).length).reduce((acc: any, num: any) => acc + num, 0)
      this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore4Boss = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter((y: any) => y.competencyBehavioral.scoreTopicExpectationBoss == 4).length).reduce((acc: any, num: any) => acc + num, 0)
      this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore5Boss = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter((y: any) => y.competencyBehavioral.scoreTopicExpectationBoss == 5).length).reduce((acc: any, num: any) => acc + num, 0)
      this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore6Boss = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter((y: any) => y.competencyBehavioral.scoreTopicExpectationBoss == 6).length).reduce((acc: any, num: any) => acc + num, 0)
      this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore7Boss = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter((y: any) => y.competencyBehavioral.scoreTopicExpectationBoss == 7).length).reduce((acc: any, num: any) => acc + num, 0)
      this.calWeightTotal()
    }
    this.cdr.detectChanges()
  }
  calWeightScoreBoss(weightScore: number) {
    if (this.appraisalCompentencyList[this.appraisalCompentencyIndex]?.masfromEvaluationAssessment1List[0]) {
      switch (weightScore) {
        case (1): {
          return this.showNumber((this.setting.data.settingScore1) * this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore1Boss)
        }
        case (2): {
          return this.showNumber((this.setting.data.settingScore2) * this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore2Boss)
        }
        case (3): {
          return this.showNumber((this.setting.data.settingScore3) * this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore3Boss)
        }
        case (4): {
          return this.showNumber((this.setting.data.settingScore4) * this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore4Boss)
        }
        case (5): {
          return this.showNumber((this.setting.data.settingScore5) * this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore5Boss)
        }
        case (6): {
          return this.showNumber((this.setting.data.settingScore6) * this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore6Boss)
        }
        case (7): {
          return this.showNumber((this.setting.data.settingScore7) * this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore7Boss)
        }
        default: { return }
      }
    }
    return
  }
  calWeightScore(weightScore: number) {
    if (this.appraisalCompentencyList[this.appraisalCompentencyIndex]?.masfromEvaluationAssessment1List[0]) {
      switch (weightScore) {
        case (1): {
          return this.showNumber((this.setting.data.settingScore1) * this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore1)
        }
        case (2): {
          return this.showNumber((this.setting.data.settingScore2) * this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore2)
        }
        case (3): {
          return this.showNumber((this.setting.data.settingScore3) * this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore3)
        }
        case (4): {
          return this.showNumber((this.setting.data.settingScore4) * this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore4)
        }
        case (5): {
          return this.showNumber((this.setting.data.settingScore5) * this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore5)
        }
        case (6): {
          return this.showNumber((this.setting.data.settingScore6) * this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore6)
        }
        case (7): {
          return this.showNumber((this.setting.data.settingScore7) * this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightScore7)
        }
        default: { return }
      }
    }
    return
  }
  calWeightTotal() {
    if (this.appraisalCompentencyList[this.appraisalCompentencyIndex]?.masfromEvaluationAssessment1List[0]) {
      this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightedTotalBoss = 0
      this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightedTotalBoss = +(((this.calWeightScoreBoss(1) ?? 0) + (this.calWeightScoreBoss(2) ?? 0) + (this.calWeightScoreBoss(3) ?? 0) + (this.calWeightScoreBoss(4) ?? 0) + (this.calWeightScoreBoss(5) ?? 0) + (this.calWeightScoreBoss(6) ?? 0) + (this.calWeightScoreBoss(7) ?? 0)).toFixed(2))
      this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightedTotal = 0
      this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightedTotal = +(((this.calWeightScore(1) ?? 0) + (this.calWeightScore(2) ?? 0) + (this.calWeightScore(3) ?? 0) + (this.calWeightScore(4) ?? 0) + (this.calWeightScore(5) ?? 0) + (this.calWeightScore(6) ?? 0) + (this.calWeightScore(7) ?? 0)).toFixed(2))
      this.cdr.detectChanges()
      this.calAverageScore()
    }
  }
  calAverageScore() {
    if (this.appraisalCompentencyList[this.appraisalCompentencyIndex]?.masfromEvaluationAssessment1List[0]) {
      const length = this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map((x: any) => x.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.length).reduce((acc: any, num: any) => acc + num, 0)
      const max = Math.max(...[+(this.setting.data.settingScore7),
      + (this.setting.data.settingScore6),
      + (this.setting.data.settingScore5),
      +(this.setting.data.settingScore4),
      +(this.setting.data.settingScore3),
      +(this.setting.data.settingScore2),
      +(this.setting.data.settingScore1)])
      const total = length * max
      if (total) {
        this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].averageScoreBoss = 0
        this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].averageScoreBoss = this.showNumber((this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightedTotalBoss * 100) / total)
        this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].averageScore = 0
        this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].averageScore = this.showNumber((this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightedTotal * 100) / total)
        this.cdr.detectChanges()
      }
    }
  }
  calAverage(score: number | string) {
    const roundedScore = this.showNumber(score) % 1 <= 0.5 ? Math.floor(this.showNumber(score)) : Math.round(this.showNumber(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 {
      return "1";
    }
  }
  calGap(score: number | string, index?: string) {
    const compentency = this.appraisalCompentencyList[index ? +(index) : this.appraisalCompentencyIndex]?.masfromEvaluationAssessment1List[0]
    let scoreGab = ''
    if (compentency) {
      const roundedScore = this.showNumber(score) % 1 <= 0.5 ? Math.floor(this.showNumber(score)) : Math.round(this.showNumber(score));
      if (roundedScore >= 90 && roundedScore <= 100) {
        if (compentency.weightScore1Boss || compentency.weightScore2Boss || compentency.weightScore3Boss) {
          scoreGab = '-1'
          if (this.evaluateeId == this.evaluaterId) {
            compentency.scoreGab = scoreGab
          }
          compentency.scoreGabBoss = scoreGab
          return scoreGab;
        }
        scoreGab = '+1'
        if (this.evaluateeId == this.evaluaterId) {
          compentency.scoreGab = scoreGab
        }
        compentency.scoreGabBoss = scoreGab
        return scoreGab;
      } else if (roundedScore >= 80 && roundedScore <= 89) {
        if (compentency.weightScore1Boss || compentency.weightScore2Boss || compentency.weightScore3Boss) {
          scoreGab = '-1'
          if (this.evaluateeId == this.evaluaterId) {
            compentency.scoreGab = scoreGab
          }
          compentency.scoreGabBoss = scoreGab
          return scoreGab;
        }
        scoreGab = '0'
        if (this.evaluateeId == this.evaluaterId) {
          compentency.scoreGab = scoreGab
        }
        compentency.scoreGabBoss = scoreGab
        return scoreGab;
      } else if (roundedScore >= 60 && roundedScore <= 79) {
        scoreGab = '-1'
        if (this.evaluateeId == this.evaluaterId) {
          compentency.scoreGab = scoreGab
        }
        compentency.scoreGabBoss = scoreGab
        return scoreGab;
      } else if (roundedScore >= 40 && roundedScore <= 59) {
        scoreGab = '-2'
        if (this.evaluateeId == this.evaluaterId) {
          compentency.scoreGab = scoreGab
        }
        compentency.scoreGabBoss = scoreGab
        return scoreGab;
      } else {
        scoreGab = '-3'
        if (this.evaluateeId == this.evaluaterId) {
          compentency.scoreGab = scoreGab
        }
        compentency.scoreGabBoss = scoreGab
        return scoreGab;
      }
    }
    return
  }
  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' }) || ''
  }
  showNumber(text: number | string) {
    const num = Number(text);
    return isNaN(num) ? 0 : +(+num.toFixed(2));
  }
  returnPath() {
    this.sendReturnPath.emit()
  }

  inFormRemain(data: MasfromEvaluationAssessment2List) {
    const remain = data.groupAssessment1.competencyIndicatorsCourses1Mini.behavioralIndicatorsList.filter(x => x.competencyBehavioral.scoreTopicExpectationBoss == 0).length
    return remain
  }
  formRemain(index: number) {
    const remain = this.appraisalCompentencyList[index]?.masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map(data =>
      this.inFormRemain(data)
    ).filter(data => data != 0).length
    this.allFormRemain()
    this.allWeightGap()
    return remain
  }
  allFormRemain() {
    const remain = this.appraisalCompentencyList.map((_, i) =>
      this.appraisalCompentencyList[i]?.masfromEvaluationAssessment1List[0].masfromEvaluationAssessment2List.map(data =>
        this.inFormRemain(data)
      ).filter(data => data != 0).length
    ).filter(data => data != 0).length
    const score = [1, 2, 3, 4, 5, 6, 7]
    this.compentencyScoreBoss.emit(score.map(x => this.calWeightScoreBoss(x)))
    this.compentencyWeightTotalBoss.emit(this.showNumber(this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightedTotalBoss))
    this.compentencyWeightScoreBoss.emit(this.showNumber(this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].averageScoreBoss))
    this.compentencyGapBoss.emit(this.calGap(this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].averageScoreBoss))
    this.compentencyForm.emit(this.appraisalCompentencyList)
    this.compentencyFormRemain.emit(remain)

    this.compentencyScore.emit(score.map(x => this.calWeightScore(x)))
    this.compentencyWeightTotal.emit(this.showNumber(this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].weightedTotal))
    this.compentencyWeightScore.emit(this.showNumber(this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].averageScore))
    this.compentencyGap.emit(this.calGap(this.appraisalCompentencyList[this.appraisalCompentencyIndex].masfromEvaluationAssessment1List[0].averageScore))
  }
  allWeightGap() {
    this.appraisalCompentencyList.forEach((x, i) => {
      this.inforWeightBoss.set(x.comType, x.masfromEvaluationAssessment1List[0].averageScoreBoss + '')
      this.inforGapBoss.set(x.comType, this.calGap(x.masfromEvaluationAssessment1List[0].averageScoreBoss, (i + '')) ?? '')
      this.inforWeight.set(x.comType, x.masfromEvaluationAssessment1List[0].averageScore + '')
      this.inforGap.set(x.comType, this.calGap(x.masfromEvaluationAssessment1List[0].averageScore, (i + '')) ?? '')
    })
    this.sendInforWeightBoss.emit(this.inforWeightBoss)
    this.sendInforGapBoss.emit(this.inforGapBoss)
    this.sendInforWeight.emit(this.inforWeight)
    this.sendInforGap.emit(this.inforGap)
  }

  allBiOpen(status: boolean, part?: string) {
    this.biOpen.forEach((_, key) => {
      if (part) {
        if (part == key) {
          this.biOpen.set(key, status)
        } else {
          if (status) {
            this.biOpen.set(key, false)
          }
        }
      } else {
        this.biOpen.set(key, status)
      }
    })
  }

  scrollToMenu(index: number) {
    this.scrollToMenuId.emit('menu-' + index);
  }
  downloadFile(event: MouseEvent, competencyFiles: string) {
    event.stopPropagation(); // กันไม่ให้ event bubble ไปถึงปุ่มหลัก
    this.fileService.downloadFiles(competencyFiles).subscribe({
      next: response => {
        const url = window.URL.createObjectURL(response);
        const a = document.createElement("a");
        a.href = url;
        a.download = competencyFiles;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        this.cdr.detectChanges()
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.cdr.detectChanges()
      }
    })
  }

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