import { ChangeDetectorRef, Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
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 { EvaluationAssessmentService } from 'src/app/shared/services/evaluation-assessment.service';
import { EvaluationCycleService } from 'src/app/shared/services/evaluation-cycle.service';
import Swal from 'sweetalert2';
@Component({
  selector: 'app-edit-define-document-form',
  templateUrl: './edit-define-document-form.component.html',
  styleUrls: ['./edit-define-document-form.component.scss']
})

export class EditDefineDocumentFormComponent {
  @ViewChild("evaluationFormEmpModal") evaluationFormEmpModal: any;
  @ViewChild("IndicatorsEmpModal") IndicatorsEmpModal: any;
  @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: AppraisalModel[] = []
  loadingAssessmentList = false
  evaluationRound: EvaluationCycleModel = new MyEvaluationCycleModel()

  isChecked: boolean = false;

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

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

  searchRound = ""
  selectEmp: AppraisalModel = new MyAppraisalModel()
  numDataListChecked = 0
  msg = ""
  typeForm = ""

  selectData: AppraisalRoundModel = new MyAppraisalRoundModel()

  loading = false

  indicatorsList: AppraisalRoundModel[] = []
  indicatorsListShow: AppraisalRoundModel[] = []
  searchIndicator = ""
  currentPageIndicator = 1
  pageIndicator = Array.from({ length: 1 }, (_, i) => i + 1);
  pageSizeIndicator = 10
  competencyTopicIds: string[] = []
  dialogRef: any
  constructor(private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private evaluationAssessmentService: EvaluationAssessmentService,
    private evaluationCycleService: EvaluationCycleService,
    private dialog: MatDialog
  ) {

  }

  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.evaluationCycleService.getById(this.evaluationRoundId!).subscribe({
      next: response => {
        this.evaluationRound = response
        this.cdr.detectChanges();
      },
      error: err => {
        console.error('Error fetching evaluation cycles:', err);
      }
    });

  }
  getAssessmentList() {
    this.loadingAssessmentList = true
    this.evaluationAssessmentService.getById(this.evaluationRoundId!, this.apsyear).subscribe({
      next: response => {
        this.assessmentList = response
        this.searchChange()
        this.loadingAssessmentList = false
        this.cdr.detectChanges();
      },
      error: err => {
        console.error('Error fetching evaluation cycles:', err);
      }
    });
  }
  assessmentListFilter() {
    if (!Array.isArray(this.assessmentList)) {
      return []; // หรือ return null แล้วจัดการใน HTML
    }

    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.masfromEvaluationRound.evaluationRoundId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsassessy.employeeId.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: AppraisalModel) {
    this.evaluationAssessmentService.post(item).subscribe({
      next: response => {
        if (response.success) {
          this.showAlertToastr(response.message, 'success')
        } else {
        }
      }
    })
  }
  saveAssessmentList() {
    let body = this.assessmentList
    if (body.length > 0) {
      this.evaluationAssessmentService.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.masfromTopic = this.empassessmentRoundListCheckbox.map(x => x.item) as any;
      }
      Swal.fire({
        icon: 'question',
        title: 'แจ้งเตือน',
        text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
        showCancelButton: true,
        confirmButtonText: 'บันทึกข้อมูล',
        cancelButtonText: 'ย้อนกลับ',
        reverseButtons: true,
      }).then((result) => {
        if (result.isConfirmed) {
          this.evaluationAssessmentService.postList([this.empassessmentList]).subscribe({
            next: response => {
              if (response.success) {
                this.showAlert(response.message, 'success')
                this.getApsassessy();
                this.getApsassessyMini();
                this.cdr.detectChanges();
                // this.closeDialog();
              }
            }, error: err => {
              console.error('Error fetching evaluation cycles:', err);
            }
          })
        }
      });


    } else {
      this.showAlert('กรุณาเลือกรายการ', 'error');
    }
  }
  getApsassessy() {
    this.loading = true
    this.evaluationAssessmentService.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.evaluationAssessmentService.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?.competencyIndicatorsCourses1Mini?.competencyIndicatorsCourses0?.competencyTopic?.tdesc?.toLowerCase()?.includes(this.searchRound?.toLowerCase() ?? "") ||
      x.item.groupAssessment1?.competencyIndicatorsCourses1Mini?.competencyIndicatorsCourses0?.competencyTopic?.edesc?.toLowerCase()?.includes(this.searchRound?.toLowerCase() ?? "") ||
      x.item.groupAssessment1?.competencyIndicatorsCourses1Mini?.competencyIndicatorsCourses0?.competencyTopic?.competencyTopicId?.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?.competencyIndicatorsCourses1Mini?.competencyIndicatorsCourses0?.competencyTopic?.competencyTopicId)
        .map(x => x.item.groupAssessment1!.competencyIndicatorsCourses1Mini!.competencyIndicatorsCourses0!.competencyTopic!.competencyTopicId)
    ));
  }
  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: AppraisalRoundModel) {
    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();
    // this.evaluationAssessmentService.deletemMini(body, this.selectEmp.apsassessy.employeeId, this.selectEmp.masfromEvaluationRound.evaluationRoundId).subscribe({
    //   next: response => {
    //     if (response.success) {
    //       this.showAlert(response.message, 'success')
    //       this.getApsassessyMini();
    //     } else {
    //       this.showAlert(response.message, 'error')
    //     }
    //   }
    // })
  }
  // ############################# ปิด Modal 2 #############################


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

  getIndicators() {
    this.evaluationAssessmentService.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?.competencyIndicatorsCourses1Mini?.competencyIndicatorsCourses0?.competencyTopic?.competencyTopicId
      )
    );
  }
  filterIndicators() {
    return this.indicatorsListShow.filter(x =>
      x.groupAssessment1?.competencyIndicatorsCourses1Mini?.competencyIndicatorsCourses0?.competencyTopic?.tdesc?.toLowerCase()?.includes(this.searchIndicator?.toLowerCase() ?? "") ||
      x.groupAssessment1?.competencyIndicatorsCourses1Mini?.competencyIndicatorsCourses0?.competencyTopic?.edesc?.toLowerCase()?.includes(this.searchIndicator?.toLowerCase() ?? "") ||
      x.groupAssessment1?.competencyIndicatorsCourses1Mini?.competencyIndicatorsCourses0?.competencyTopic?.competencyTopicId?.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);
  }
  openModalIndicators() {
    const modalRef = this.dialog.open(this.IndicatorsEmpModal, {
      width: '60vw',
      enterAnimationDuration: '300ms', // ระยะเวลาการเปิด
      exitAnimationDuration: '150ms',  // ระยะเวลาการปิด
      disableClose: false,
    });
  }
  addIndicators(item: AppraisalRoundModel) {
    this.empassessmentRoundListCheckbox.push({ checkbox: false, item })
    this.competencyTopicIds.push(item.groupAssessment1?.competencyIndicatorsCourses1Mini?.competencyIndicatorsCourses0?.competencyTopic?.competencyTopicId)
    this.indicatorChange();
  }

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


  showAlert(text: string, type: 'success' | 'error') {
    Swal.fire({
      title: 'แจ้งเตือน',
      text: text,
      icon: type,
      confirmButtonText: 'ตกลง',
    });


  }
  showAlertToastr(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: AppraisalModel, model: string) {
    this.dialogRef = this.dialog.open(this.evaluationFormEmpModal, {
      width: '80vw',
      disableClose: false,
      enterAnimationDuration: '300ms', // ระยะเวลาการเปิด
      exitAnimationDuration: '150ms',  // ระยะเวลาการปิด
    });

    this.searchIndicator = ""
    this.selectEmp = item
    this.openModalClass(model);
    this.evaluationRoundId = evaluationRoundId
    this.apsassessy = apsassessy
    this.getApsassessy()
    this.getApsassessyMini();

  }

  closeDialog() {
    this.dialogRef.close()
  }




}
