import { ChangeDetectorRef, Component } from '@angular/core';
import { AppraisalSubordinateModel, Masfromevaluationassessment } from 'src/app/shared/model/appraisal-subordinate.model';
import { AppraisalService } from 'src/app/shared/services/appraisal.service';

@Component({
  selector: 'app-supervisor-evaluation',
  templateUrl: './supervisor-evaluation.component.html',
  styleUrls: ['./supervisor-evaluation.component.scss']
})
export class SupervisorEvaluationComponent {
  pathTitle = ['การประเมินผล', 'ประเมินโดยหัวหน้า']
  pageEvalution = ''
  currentDate = new Date()
  subordinate: { loading: false, select?: AppraisalSubordinateModel, dataList: AppraisalSubordinateModel[] } = { loading: false, select: undefined, dataList: [] }
  search = ""
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1)
  formEvaluation = {
    evaluateeId: "",
    evaluaterId: "",
    competencyTypeId: "",
    evaluationRoundId: ""
  }
  constructor(private appraisalService: AppraisalService,
    private cdr: ChangeDetectorRef) {
  }
  ngOnInit(): void {
    this.formEvaluation.evaluaterId = this.decodeJWT(sessionStorage.getItem("accessToken") || '').employeeid
    this.getBossList()
  }
  getBossList() {
    this.appraisalService.getBossList().subscribe({
      next: response => {
        this.subordinate.dataList = JSON.parse(JSON.stringify(response))
        this.cdr.detectChanges()
        if (this.subordinate.dataList.length) {
          this.subordinate.select = JSON.parse(JSON.stringify(this.subordinate.dataList[0]))
          this.cdr.detectChanges()
        }
        this.searchChange()
      }, error: error => {
        this.cdr.detectChanges()
      }
    })
  }
  selectDataList(data?: AppraisalSubordinateModel) {
    this.subordinate.select = JSON.parse(JSON.stringify(data))
    this.cdr.detectChanges()
    this.searchChange()
  }


  subordinateFilter() {
    if (this.subordinate.select) {
      return this.subordinate.select.masfromevaluationassessment.filter(x => {
        return x.apsassessy.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
          x.apsassessy.thFullName.toLowerCase().includes(this.search.toLowerCase()) ||
          x.apsassessy.position.tdesc.toLowerCase().includes(this.search.toLowerCase())
      })
    }
    return []
  }


  searchChange() {
    this.currentPage = 1
    this.page = Array.from({ length: Math.ceil(this.subordinateFilter().length / 10) }, (_, i) => i + 1);
  }
  selectSubordinate(data: Masfromevaluationassessment, competencyTypeId: string, evaluationRoundId?: string) {
    if (data && competencyTypeId && evaluationRoundId) {
      this.formEvaluation.evaluateeId = data.apsassessy.employeeId
      this.formEvaluation.competencyTypeId = competencyTypeId
      this.formEvaluation.evaluationRoundId = evaluationRoundId
      this.cdr.detectChanges()
    }
  }

  decodeJWT(token: string) {
    let base64Url = token.split('.')[1]; // ดึงส่วนที่เป็น Payload
    let base64 = base64Url.replace('-', '+').replace('_', '/'); // แก้ไข base64 ให้ถูกต้อง
    let jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
    return JSON.parse(jsonPayload);
  }
}