import { ChangeDetectorRef, Component, EventEmitter, Output, Renderer2, ViewChild } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { EvaluationCycleModel, MyEvaluationCycleModel } from 'src/app/shared/model/evaluation-cycle.model';
import { EvaluationCycleService } from 'src/app/shared/services/evaluation-cycle.service';
import { PLModel, MyPLModel } from 'src/app/shared/model/pl.model';
import { MatDialog } from '@angular/material/dialog';
import { ColumnModel } from '@syncfusion/ej2-grids';
import Swal from 'sweetalert2';
import { JobcodeService } from 'src/app/shared/services/jobcode.service';
import { JobcodeModel, MyJobcodeModel } from 'src/app/shared/model/jobcode.model';
import { TranslateService } from '@ngx-translate/core';
export interface DataModal {
  search: string,
  currentPage: number,
  page: number[],
  pageSize: number
}
@Component({
  selector: 'app-evaluation-cycle',
  templateUrl: './evaluation-cycle.component.html',
  styleUrls: ['./evaluation-cycle.component.scss']
})
export class EvaluationCycleComponent {
  @Output() evaluationRoundIdChange = new EventEmitter<string>();
  @ViewChild("evaluationRoundModal") evaluationRoundModal: any;
  dialogRef: any

  @ViewChild("evaluationRoundModalForm") evaluationRoundModalForm: any;
  dialogRefForm: any

  @ViewChild("PLModal") PLModal: any;
  dialogRefPL: any

  apsPeriodStart: string = '';
  apsPeriodEnd: string = '';

  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  modalStatus: 'createForm' | 'add' | 'edit' | 'delete' | 'deleteGroup' = 'add'
  evaluation_cyclelist: EvaluationCycleModel[] = []
  evaluation_cycle: EvaluationCycleModel = new MyEvaluationCycleModel({})
  dataLoading = false
  itemToDelete: EvaluationCycleModel | null = null;
  isDataListChecked = false
  isDataListCheckedAll = false
  numDataListChecked = 0
  evaluationRoundId = ''
  private unlisten!: () => void;

  modal: DataModal = {
    search: "",
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    pageSize: 10
  }
  PLsearchmodal: DataModal = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }
  pl: { loading: boolean, selectIndex: number, dataList: JobcodeModel[] } = { loading: false, selectIndex: -1, dataList: [] }
  currentDate = new Date()
  yearList = [
    (this.currentDate.getFullYear() - 1) + "",
    (this.currentDate.getFullYear()) + "",
    (this.currentDate.getFullYear() + 1) + "",
  ]
  modalStatusEdit = false
  dialogFormRef: any

  columns: ColumnModel[] = [{
    field: "evaluationRoundId",
    headerText: "PeriodCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "Description",
    type: "string"
  },
  {
    field: "apsyear",
    headerText: "Year_round",
    type: "string"
  },
  {
    field: "apsPeriodStart",
    headerText: "StartDate",
    type: "string"
  },
  {
    field: "apsPeriodEnd",
    headerText: "EndDate",
    type: "string"
  },
  {
    field: "statusCode.tdesc",
    headerText: "Status",
    type: "string"
  }]
  searchSettings = {
    fields: ['evaluationRoundId', 'tdesc', 'apsyear', 'apsPeriodStart', 'apsPeriodEnd', 'statusCode.tdesc'],
    operator: 'contains',
    ignoreCase: false
  };
  search = ''
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };

  constructor(private evaluationCycleService: EvaluationCycleService,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private renderer: Renderer2,
    private jobcodeService: JobcodeService,
    private dialog: MatDialog,
    public translateService: TranslateService
  ) { }

  ngOnInit(): void {
    this.getEvaluationCycleList()
    this.unlisten = this.renderer.listen('document', 'keydown', (event) => {
      if (event.key === 'Escape') {
        this.evaluationRoundId = ''
        this.dialogFormRef.close();
      }
    });
    this.getPlList()
  }
  ngOnDestroy() {
    if (this.unlisten) {
      this.unlisten(); // เรียกใช้งานจริง ๆ เพื่อลบ event listener
    }
  }

  getPlList() {
    this.pl.loading = false
    this.jobcodeService.getGroupAssessmentList().subscribe({
      next: response => {
        this.pl.dataList = response.map((x: any) => new MyJobcodeModel(x)).filter(e => e.statusCom)
        this.pl.loading = false
        this.searchChange()
        this.cdr.detectChanges()
      }, error: error => {
        this.pl.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  plListFilter() {
    return this.pl.dataList.filter(x =>
      (x.jobCodeId.toLowerCase().includes(this.PLsearchmodal.search.toLowerCase()) ||
        x.tdesc.toLowerCase().includes(this.PLsearchmodal.search.toLowerCase()) ||
        x.edesc.toLowerCase().includes(this.PLsearchmodal.search.toLowerCase())) &&
      !this.evaluation_cycle.jd.some(y => y.jobCodeId == x.jobCodeId)
    );
  }
  onPLModalSearchChange() {
    this.PLsearchmodal.currentPage = 1
    this.PLsearchmodal.page = Array.from({ length: Math.ceil(this.plListFilter().length / 10) }, (_, i) => i + 1);
  }
  selectPl(data?: JobcodeModel) {
    if (!data) {
      this.evaluation_cycle.jd.splice(this.pl.selectIndex, 1);
      return;
    }
    this.evaluation_cycle.jd.push(new MyJobcodeModel(data))
  }

  getEvaluationCycleList() {
    this.dataLoading = true
    this.selectedItems.data.clear()
    this.evaluationCycleService.getList().subscribe({
      next: response => {
        this.evaluation_cyclelist = response.map(x => {
          this.selectedItems.data.set(x.evaluationRoundId, false)
          return new MyEvaluationCycleModel(x)
        })
        this.selectedItems.key = 'evaluationRoundId'
        this.selectedItems.count = 0
        this.dataLoading = false
        this.isDataListCheckedAll = false
        this.cdr.detectChanges();
      },
      error: err => {
        this.dataLoading = false
        this.cdr.detectChanges();
      }
    });
  }
  // dataListCheckAll() {
  //   const selectAll = this.isDataListCheckedAll;
  //   this.evaluation_cycleListFilter().forEach(x => x = selectAll);
  //   this.dataListCheck();
  // }

  dataListCheck() {
    const dataCheck = this.evaluation_cycleListFilter();
    this.isDataListCheckedAll = dataCheck.length ? dataCheck.every(x => x) : false;
    this.numDataListChecked = this.evaluation_cyclelist.filter(x => x).length;
    this.isDataListChecked = Boolean(this.numDataListChecked)
  }
  searchChange() {
    this.currentPage = 1
    this.page = Array.from({ length: Math.ceil(this.evaluation_cycleListFilter().length / 10) }, (_, i) => i + 1);
    this.dataListCheck()
  }
  evaluation_cycleListFilter() {
    return this.evaluation_cyclelist.filter(x => {
      const data = x
      const match = data.evaluationRoundId.toLowerCase().includes(this.search.toLowerCase()) || data.tdesc.toLowerCase().includes(this.search.toLowerCase()) || data.edesc.toLowerCase().includes(this.search.toLowerCase());
      return match;
    });
  }
  setData(data?: EvaluationCycleModel) {
    this.evaluation_cycle = new MyEvaluationCycleModel(data)
  }

  selectEvaluationCycle(EvaluationCycle?: EvaluationCycleModel) {
    if (EvaluationCycle) {
      this.evaluation_cycle = new MyEvaluationCycleModel(EvaluationCycle);
      this.evaluationRoundId = this.evaluation_cycle.evaluationRoundId;
    } else if (this.modalStatus == 'add') {
      this.evaluation_cycle = new MyEvaluationCycleModel();
      this.evaluationRoundId = '';
    }
  }

  addevaluation_cycle() {
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'บันทึกข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        if (this.evaluation_cycle.jd.length === 0) {
          this.plListFilter().forEach(x => this.selectPl(x));
        }

        const body = new MyEvaluationCycleModel(this.evaluation_cycle);
        this.dataLoading = true;

        this.evaluationCycleService.post(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success');
              this.getEvaluationCycleList();
              this.closeDialog()
            } else {
              this.dataLoading = false;
              this.showAlert(response.message, 'error');
              this.cdr.detectChanges();
            }
          },
          error: error => {
            this.showAlert(error.message, 'error');
            this.dataLoading = false;
            this.cdr.detectChanges();
          }
        });
      }
    });
  }

  deleteevaluation_cycle() {
    if (!this.numSelectItem()) {
      this.showAlert('กรุณาเลือกข้อมูลที่ต้องการลบ', 'error')
      return
    }
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการลบข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'ลบข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        const selectedKeys = Array.from(this.selectedItems.data.keys());
        const body = this.evaluation_cyclelist.filter(x => selectedKeys.includes(x.evaluationRoundId) && this.selectedItems.data.get(x.evaluationRoundId)).map(x => new MyEvaluationCycleModel(x))
        console.log(body);

        this.dataLoading = true
        this.evaluationCycleService.delete(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getEvaluationCycleList()
            } else {
              this.showAlert(response.message, 'error')
              this.dataLoading = false
              this.cdr.detectChanges()
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.cdr.detectChanges()
            this.dataLoading = false
          }
        })
      }
    });
  }

  // ลบหลายรายการ
  //   deleteevaluation_cycleall() {
  //   Swal.fire({
  //     icon: 'question',
  //     title: 'แจ้งเตือน',
  //     text: 'ยืนยันการลบข้อมูลหรือไม่',
  //     showCancelButton: true,
  //     confirmButtonText: 'ลบข้อมูล',
  //     cancelButtonText: 'ย้อนกลับ',
  //     reverseButtons: true,
  //   }).then((result) => {
  //     if (result.isConfirmed) {
  //       let body: EvaluationCycleModel | EvaluationCycleModel[] = [];

  //       if (this.evaluation_cycle.evaluationRoundId) {
  //         body = new MyEvaluationCycleModel(this.evaluation_cycle);
  //       } else {
  //         body = this.evaluation_cyclelist
  //           .filter(x => x)
  //           .map(x => new MyEvaluationCycleModel(x));
  //       }

  //       console.log(body);

  //       this.dataLoading = true;

  //       this.evaluationCycleService.delete(body).subscribe({
  //         next: response => {
  //           if (response.success) {
  //             this.showAlert(response.message, 'success');
  //             this.getEvaluationCycleList();
  //           } else {
  //             this.showAlert(response.message, 'error');
  //             this.dataLoading = false;
  //             this.cdr.detectChanges();
  //           }
  //         },
  //         error: error => {
  //           this.showAlert(error.message, 'error');
  //           this.dataLoading = false;
  //           this.cdr.detectChanges();
  //         }
  //       });
  //     }
  //   });
  // }


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

  clear() {
    if (this.modalStatus == 'add') {
      this.setData()
    } else if (this.modalStatus == 'edit') {
      this.setData(new MyEvaluationCycleModel({ evaluationRoundId: this.evaluation_cycle.evaluationRoundId }))
    }
  }

  openModal(evaluationRoundId: string) {
    this.evaluationRoundId = ''
    this.dialogFormRef = this.dialog.open(this.evaluationRoundModalForm, {
      width: '80vw',
      disableClose: true,
      enterAnimationDuration: '300ms', // ระยะเวลาการเปิด
      exitAnimationDuration: '150ms',  // ระยะเวลาการปิด
    });
    this.evaluationRoundId = evaluationRoundId
    this.evaluationRoundIdChange.emit(evaluationRoundId)

    // if (id == 'evaluation-cycle-person-modal') {
    //   this.evaluationRoundId = evaluationRoundId
    //   this.evaluationRoundIdChange.emit(evaluationRoundId)
    //   setTimeout(() => {
    //     document.getElementById(id)?.classList.add('open');
    //     document.getElementById(id)?.classList.remove('hidden');
    //     document.getElementById(id)?.setAttribute('aria-overlay', 'false');
    //   }, 10);
    // }
  }

  searchModalChange(dataList: any[]) {
    this.modal.currentPage = 1
    this.modal.page = Array.from({ length: Math.ceil(dataList.length / 10) }, (_, i) => i + 1);
  }

  createForm(data: any) {
    Swal.fire({
      title: 'สร้างแบบฟอร์ม?',
      text: 'คุณต้องการสร้างแบบฟอร์มการประเมินใหม่หรือไม่',
      icon: 'question',
      showCancelButton: true,
      confirmButtonText: 'ยืนยัน',
      cancelButtonText: 'ยกเลิก',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        this.modalStatus = 'createForm';
        this.setData(data); // เซ็ตข้อมูลก่อน

        const body = new MyEvaluationCycleModel(this.evaluation_cycle);
        body.active = 1;
        this.dataLoading = true;

        this.evaluationCycleService.post(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success');
            } else {
              this.dataLoading = false;
              this.showAlert(response.message, 'error');
              this.cdr.detectChanges();
            }
          },
          error: error => {
            this.showAlert(error.message, 'error');
            this.dataLoading = false;
            this.cdr.detectChanges();
          }
        });

        this.evaluationCycleService.postCreateForm(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success');
              this.getEvaluationCycleList();
            } else {
              this.dataLoading = false;
              this.showAlert(response.message, 'error');
              this.cdr.detectChanges();
            }
          },
          error: error => {
            this.showAlert(error.message, 'error');
            this.dataLoading = false;
            this.cdr.detectChanges();
          }
        });
      }
    });
  }


  checkPrimary() {
    return this.evaluation_cyclelist.find(x => x.evaluationRoundId == this.evaluation_cycle.evaluationRoundId)
  }
  numSelectItem() {
    const selectedKeys = Array.from(this.selectedItems.data.keys());
    const num = this.evaluation_cyclelist.filter(x => selectedKeys.includes(x.evaluationRoundId) && this.selectedItems.data.get(x.evaluationRoundId)).length
    return num
  }

  onSelectItemChange(arg: any) {
    this.selectedItems = arg
  }

  openDialog() {
    this.dialogRef = this.dialog.open(this.evaluationRoundModal, {
      width: '500px',
      disableClose: false,
    });
  }
  closeDialog() {
    this.dialogRef.close()
  }

  openDialogForm() {
    this.dialogRefForm = this.dialog.open(this.evaluationRoundModalForm, {
      width: '1200px',
      disableClose: false,
    });
  }
  closeDialogForm() {
    this.dialogRefForm.close()
  }

  openDialogPL() {
    this.dialogRefPL = this.dialog.open(this.PLModal, {
      width: '800px',
    });
  }
  closeDialogPL() {
    this.dialogRefPL.close()
  }
}


