import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { AppraisalRoundModel, MyAppraisalRoundModel } from 'src/app/shared/model/appraisal-aps.model';
import { AppraisalModel, MyAppraisalModel } from 'src/app/shared/model/appraisal.model';
import { EvaluationCycleModel, MyEvaluationCycleModel } from 'src/app/shared/model/evaluation-cycle.model';
import { EvaluationModal } from 'src/app/shared/model/evaluation-form.modal';
import { masfromEvaluationAssessment1List, PmsMasfromEvaluationFullModel } from 'src/app/shared/model/pms-masfrom-evaluation-list.model';
import { MyPmsMasfromEvaluationModel, PmsMasfromEvaluationModel } from 'src/app/shared/model/pms-masfrom-evaluation.model';
import { PmsEvaluationAssessmentService } from 'src/app/shared/services/pms-evaluation-assessment.service';
import { PmsMasfromEvaluationCycleService } from 'src/app/shared/services/pms-masfrom-evaluation.service';
import { PmstopicService } from 'src/app/shared/services/pmstopic.service';


@Component({
  selector: 'app-edit-evaluation-form',
  templateUrl: './edit-evaluation-form.component.html',
  styleUrls: ['./edit-evaluation-form.component.scss']
})
export class EditEvaluationFormComponent {
  @Input() pathTitle = ['การประเมินจัดการประสิทธิภาพ', 'รอบการประเมิน', 'กำหนดฟอร์มเอกสาร', 'เเก้ไขฟอร์มตามรอบการประเมิน'];
  @Output() sendPathTitle: EventEmitter<string[]> = new EventEmitter<string[]>();
  @Output() sendGroupShow: EventEmitter<string> = new EventEmitter<string>();
  @Input() evaluationRoundId = ''
  @Input() apsyear = ''

  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  pageSize = 10
  search = ""

  assessmentList: PmsMasfromEvaluationFullModel[] = []

  evaluationRound: PmsMasfromEvaluationModel = new MyPmsMasfromEvaluationModel()

  isChecked: boolean = false;

  apsassessy = ""
  empassessmentList?: EvaluationModal
  searchEmp = ""

  empassessmentRoundList: masfromEvaluationAssessment1List[] = []
  empassessmentRoundListCheckbox: { checkbox: boolean, item: masfromEvaluationAssessment1List }[] = []
  currentPageRound = 1
  pageRound = Array.from({ length: 1 }, (_, i) => i + 1);
  pageSizeRound = 10

  searchRound = ""
  selectEmp?: PmsMasfromEvaluationFullModel
  numDataListChecked = 0
  msg = ""
  typeForm = ""

  selectData?: masfromEvaluationAssessment1List

  loading = false

  indicatorsList: masfromEvaluationAssessment1List[] = []
  indicatorsListShow: masfromEvaluationAssessment1List[] = []
  searchIndicator = ""
  currentPageIndicator = 1
  pageIndicator = Array.from({ length: 1 }, (_, i) => i + 1);
  pageSizeIndicator = 10
  competencyTopicIds: string[] = []
  constructor(private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private pmsMasfromEvaluationCycleService: PmsMasfromEvaluationCycleService,
    private pmsEvaluationAssessmentService: PmsEvaluationAssessmentService,
    private pmstopicService: PmstopicService
  ) {

  }

  ngOnInit(): void {

  }
  ngOnChanges(): void {
    setTimeout(() => {
      document.getElementById('form-pm-emp')?.classList.add("hidden")
      document.getElementById('form-assessment')?.classList.add("hidden")
      document.getElementById('modal-alert')?.classList.add("hidden")
    }, 10);
    if (this.evaluationRoundId && this.apsyear) {
      this.getAssessmentId();
      this.getAssessmentList();
    }
  }
  //############################# เเก้ไขเเบบฟอร์มตามรอบการประเมิน modal แรก #############################
  getAssessmentId() {
    this.pmsMasfromEvaluationCycleService.getById(this.evaluationRoundId!).subscribe({
      next: response => {
        this.evaluationRound = response
        this.cdr.detectChanges();
      },
      error: err => {
        console.error('Error fetching evaluation cycles:', err);
      }
    });

  }
  getAssessmentList() {
    this.pmsEvaluationAssessmentService.getById(this.evaluationRoundId!, this.apsyear).subscribe({
      next: response => {
        this.assessmentList = response
        this.searchChange()
        this.cdr.detectChanges();
      },
      error: err => {
        console.error('Error fetching evaluation cycles:', err);
      }
    });
  }
  assessmentListFilter() {
    return this.assessmentList.filter(x =>
      x.apsassessy.fname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsassessy.lname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsassessy.efname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsassessy.elname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.pmsMasfromEvaluationRound.pmsEvaluationRoundId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsassessy.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsassessy.position.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.personalLevel.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.jd.tdesc.toLowerCase().includes(this.search.toLowerCase())
    )
  }
  searchChange() {
    this.currentPage = 1;
    const filteredData = this.assessmentListFilter();
    this.page = Array.from({ length: Math.ceil(filteredData.length / this.pageSize) }, (_, i) => i + 1);
  }

  saveAssessmentOne(item: PmsMasfromEvaluationFullModel) {
    this.pmsEvaluationAssessmentService.post(item).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
        } else {
        }
      }
    })
  }
  saveAssessmentList() {
    let body = this.assessmentList.filter(x => x.active == true)
    if (body.length > 0) {
      this.pmsEvaluationAssessmentService.postList(body).subscribe({
        next: response => {
          if (response.success) {
            this.showAlert(response.message, 'success')
            this.getAssessmentList();
          } else {
          }
        }
      })
    } else {
      this.showAlert('ไม่พบรายการ', 'error')
    }
  }
  //############################# ปิดเเก้ไขเเบบฟอร์มตามรอบการประเมิน modal แรก #############################


  // ############################# Modal 2 #############################

  saveIndicators() {
    if (this.empassessmentRoundListCheckbox.map(x => x.item).length > 0) {
      if (this.empassessmentList) {
        this.empassessmentList.masfromEvaluationAssessment1List = this.empassessmentRoundListCheckbox.map(x => {
          x.item.weight = Number(x.item.weight);
          return x.item as any;
        });
      }
      this.pmsEvaluationAssessmentService.postList([this.empassessmentList]).subscribe({
        next: response => {
          if (response.success) {
            this.showAlert(response.message, 'success')
            this.getApsassessy();
            this.getApsassessyMini();
            this.cdr.detectChanges();
          }
        }, error: err => {
          console.error('Error fetching evaluation cycles:', err);
        }
      })
    } else {
      this.showAlert('กรุณาเลือกรายการ', 'error');
    }
  }
  getApsassessy() {
    this.loading = true
    this.pmsEvaluationAssessmentService.getApsassessy(this.evaluationRoundId, this.apsassessy, this.apsyear).subscribe({
      next: response => {
        this.empassessmentList = response
        this.loading = false
        this.cdr.detectChanges();
      },
      error: err => {
        this.loading = false
        console.error('Error fetching evaluation cycles:', err);
      }
    })
  }
  getApsassessyMini() {
    this.pmsEvaluationAssessmentService.getApsassessyMini(this.evaluationRoundId, this.apsassessy, this.apsyear).subscribe({
      next: response => {
        this.empassessmentRoundList = response
        this.empassessmentRoundListCheckbox = this.empassessmentRoundList.map(item => ({ checkbox: false, item }))
        this.checkTopic();
        this.searchEmpassessmentListFilterChange()
        this.getIndicators();
        this.cdr.detectChanges();
      },
      error: err => {
        console.error('Error fetching evaluation cycles:', err);
      }
    })
  }
  empassessmentListFilter() {
    return this.empassessmentRoundListCheckbox.filter(x =>
      x.item.groupAssessment1?.pmsTopic?.tdesc?.toLowerCase()?.includes(this.searchRound?.toLowerCase() ?? "") ||
      x.item.groupAssessment1?.pmsTopic?.edesc?.toLowerCase()?.includes(this.searchRound?.toLowerCase() ?? "") ||
      x.item.groupAssessment1.pmsTopic.pmsType.tdesc?.toLowerCase()?.includes(this.searchRound?.toLowerCase() ?? "") ||
      x.item.groupAssessment1?.pmsTopic?.pmsTopicId?.toLowerCase()?.includes(this.searchRound?.toLowerCase() ?? ""))
  }

  searchEmpassessmentListFilterChange() {
    this.currentPageRound = 1;
    const filteredData = this.empassessmentListFilter();
    this.pageRound = Array.from({ length: Math.ceil(filteredData.length / this.pageSizeRound) }, (_, i) => i + 1);
  }
  checkTopic() {
    this.competencyTopicIds = Array.from(new Set(
      this.empassessmentRoundListCheckbox.filter(x => x.item.groupAssessment1?.pmsTopic?.pmsTopicId)
        .map(x => x.item.groupAssessment1!?.pmsTopic?.pmsTopicId)
    ));
  }
  toggleCheckbox() {
    this.isChecked = !this.isChecked; // สลับสถานะ
    this.empassessmentRoundListCheckbox.map(item => item.checkbox = this.isChecked);
    this.checkempassessmentRoundListCheckbox();
  }

  checkempassessmentRoundListCheckbox() {
    this.numDataListChecked = this.empassessmentRoundListCheckbox.filter(x => x.checkbox).length
    this.isChecked = this.numDataListChecked ? true : false
  }
  deleteFormOne(item: masfromEvaluationAssessment1List) {
    this.selectData = item;
    this.empassessmentRoundListCheckbox = this.empassessmentRoundListCheckbox.filter(i => i.item !== item);
    this.checkTopic();
    this.indicatorChange();
    this.searchEmpassessmentListFilterChange()
    this.checkempassessmentRoundListCheckbox()
  }

  deleteAssessmentList() {
    let body = this.empassessmentRoundListCheckbox.filter(x => x.checkbox).map(x => x.item);
    if (body.length === 0) {
      this.showAlert('กรุณาเลือกรายการ', 'error');
      return;
    }
    this.empassessmentRoundListCheckbox = this.empassessmentRoundListCheckbox.filter(x => !x.checkbox);
    this.checkTopic();
    this.indicatorChange();
    this.searchEmpassessmentListFilterChange();
    this.checkempassessmentRoundListCheckbox();
  }
  // ############################# ปิด Modal 2 #############################


  //############################# Modal Indicators #############################

  getIndicators() {
    this.pmsEvaluationAssessmentService.getIndicators(this.selectEmp!.jd.jobCodeId).subscribe({
      next: response => {
        this.indicatorsList = response
        this.indicatorChange()
        this.searchIndicatorsChange()
        this.cdr.detectChanges();
      },
      error: err => {
        console.error('Error fetching evaluation cycles:', err);
      }
    })
  }
  indicatorChange() {
    this.indicatorsListShow = this.indicatorsList.filter(x =>
      !this.competencyTopicIds.includes(
        x.groupAssessment1?.pmsTopic?.pmsTopicId
      )
    );
  }
  filterIndicators() {
    return this.indicatorsListShow.filter(x =>
      x.groupAssessment1?.pmsTopic.tdesc?.toLowerCase()?.includes(this.searchIndicator?.toLowerCase() ?? "") ||
      x.groupAssessment1?.pmsTopic.edesc?.toLowerCase()?.includes(this.searchIndicator?.toLowerCase() ?? "") ||
      x.groupAssessment1?.pmsTopic?.pmsTopicId?.toLowerCase()?.includes(this.searchIndicator?.toLowerCase() ?? ""))
  }
  searchIndicatorsChange() {
    this.currentPageIndicator = 1;
    const filteredData = this.filterIndicators();
    this.pageIndicator = Array.from({ length: Math.ceil(filteredData.length / this.pageSizeIndicator) }, (_, i) => i + 1);
  }
  addIndicators(item: masfromEvaluationAssessment1List) {
    this.empassessmentRoundListCheckbox.push({ checkbox: false, item })
    this.competencyTopicIds.push(item.groupAssessment1?.pmsTopic?.pmsTopicId)
    this.indicatorChange();
    this.closeModalClass('form-assessment')
  }

  //############################# ปิด Modal Indicators #############################


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

  openModalClass(id: string, type?: string) {
    this.typeForm = type ?? ""
    if (id == 'modal-alert') {
      if (type == 'deleteForm') {
        this.msg = 'ยืนยันการลบรายการ'
      } else if (type == 'addForm' || type == 'addIndicator') {
        this.msg = 'ยืนยันการบันทึกรายการ'
      }
    }
    if (id) {
      document.getElementById(id)?.classList.add('open');
      document.getElementById(id)?.classList.remove('hidden');
      setTimeout(() => {
        document.getElementById(id)?.setAttribute('aria-overlay', 'false')

      }, 10);
    }

    this.isChecked = false;
    this.numDataListChecked = 0;
  }

  closeModalClass(id: string) {
    const modal = document.getElementById(id);
    if (id) {
      modal?.classList.add("hidden"); // ซ่อน Modal
    }
  }


  openAddRoundModel(evaluationRoundId: string, apsassessy: string, item: PmsMasfromEvaluationFullModel, model: string) {
    this.searchIndicator = ""
    this.selectEmp = item
    this.openModalClass(model);
    this.evaluationRoundId = evaluationRoundId
    this.apsassessy = apsassessy
    this.getApsassessy()
    this.getApsassessyMini();

  }






}
