import { ChangeDetectorRef, Component, EventEmitter, Input, Output, Renderer2, ViewChild } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { MyPmsMasfromEvaluationModel, PmsMasfromEvaluationModel } from 'src/app/shared/model/pms-masfrom-evaluation.model';
import { PmsMasfromEvaluationCycleService } from 'src/app/shared/services/pms-masfrom-evaluation.service';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { MatDialog } from '@angular/material/dialog';
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-management-evaluation-cycle',
  templateUrl: './management-evaluation-cycle.component.html',
  styleUrls: ['./management-evaluation-cycle.component.scss']
})
export class ManagementCycleComponent {
  @Output() evaluationRoundIdChange = new EventEmitter<string>();
  apsPeriodStart: string = '';
  apsPeriodEnd: string = '';

  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  search = ""
  modalStatus: 'createForm' | 'add' | 'edit' | 'delete' | 'deleteGroup' = 'add'
  pmsMasfromEvaluation: {
    loading: boolean,
    select: PmsMasfromEvaluationModel,
    dataList: PmsMasfromEvaluationModel[]
  } = {
      loading: false,
      select: new MyPmsMasfromEvaluationModel({}),
      dataList: []
    }
  dataLoading = false
  itemToDelete: PmsMasfromEvaluationModel | 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) + "",
  ]

  columns: ColumnModel[] = [{
    field: "pmsEvaluationRoundId",
    headerText: "PeriodCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "name",
    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",
    headerText: "Status",
    type: "string"
  },]
  searchSettings = {
    fields: ['pmsEvaluationRoundId', 'tdesc', 'apsyear', 'apsPeriodStart', 'apsPeriodEnd', 'statusCode'],
    operator: 'contains',
    ignoreCase: false
  };
  syncfutionDataList: any[] = []
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  @ViewChild("managementEvaluationCycleModal") managementEvaluationCycleModal: any;
  dialogRef: any
  @ViewChild("PLModal") PLModal: any;
  dialogRefPL: any
  @ViewChild("managementEvaluationCycleModalForm") managementEvaluationCycleModalForm: any;
  dialogRefForm: any

  modalStatusEdit = false
  constructor(private pmsMasfromEvaluationCycleService: PmsMasfromEvaluationCycleService,
    private toastr: ToastrService,
    private dialog: MatDialog,
    private cdr: ChangeDetectorRef,
    private renderer: Renderer2,
    private jobcodeService: JobcodeService,
    public translateService: TranslateService
  ) {
    this.translateService.onLangChange.subscribe((event) => {
      this.setSyncfutionDataList()
    });

  }
  setSyncfutionDataList() {
    if (this.pmsMasfromEvaluation.dataList) { 
      this.syncfutionDataList = this.pmsMasfromEvaluation.dataList.map(e => ({
        pmsEvaluationRoundId: e.pmsEvaluationRoundId,
        name: this.translateService.getCurrentLang() == 'th' ? e.tdesc : e.edesc,
        apsyear: e.apsyear,
        apsPeriodStart: e.apsPeriodStart,
        apsPeriodEnd: e.apsPeriodEnd,
        statusCode: this.translateService.getCurrentLang() == 'th' ? e.statusCode.tdesc : e.statusCode.edesc,
        statusFrom: e.statusFrom
      }))
    }
  }
  ngOnInit(): void {
    this.getPmsMasfromEvaluationCycleList()
    this.unlisten = this.renderer.listen('document', 'keydown', (event) => {
      if (event.key === 'Escape') {
        this.evaluationRoundId = ''
      }
    });
    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(x => x.statusCom && x.statusPms)
        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.pmsMasfromEvaluation.select.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.pmsMasfromEvaluation.select.jd.splice(this.pl.selectIndex, 1);
      return;
    }
    this.pmsMasfromEvaluation.select.jd.push(new MyJobcodeModel(data))
  }


  getPmsMasfromEvaluationCycleList() {
    this.dataLoading = true
    this.selectedItems.data.clear()
    this.pmsMasfromEvaluationCycleService.getList().subscribe({
      next: response => {
        this.pmsMasfromEvaluation.dataList = response.map(x => {
          this.selectedItems.data.set(x.pmsEvaluationRoundId, false)
          return new MyPmsMasfromEvaluationModel(x)
        })
        this.selectedItems.key = 'pmsEvaluationRoundId'
        this.selectedItems.count = 0
        this.dataLoading = false
        this.isDataListCheckedAll = false
        this.setSyncfutionDataList()
        this.cdr.detectChanges();
      },
      error: err => {
        this.dataLoading = false
        this.cdr.detectChanges();
      }
    });
  }
  selectPmsMasfromEvaluationCycle(dataSelect?: any) {
    const data = dataSelect ? this.pmsMasfromEvaluation.dataList.find(e => e.pmsEvaluationRoundId == dataSelect.pmsEvaluationRoundId) : undefined
    if (data) {
      this.pmsMasfromEvaluation.select = new MyPmsMasfromEvaluationModel(data)
    } else if (this.modalStatus == 'add') {
      this.pmsMasfromEvaluation.select = new MyPmsMasfromEvaluationModel()
    } else if (this.modalStatus == 'edit') {
      this.pmsMasfromEvaluation.select = new MyPmsMasfromEvaluationModel(this.pmsMasfromEvaluation.select)
    }
  }

  setData(data?: PmsMasfromEvaluationModel) {
    this.pmsMasfromEvaluation.select = new MyPmsMasfromEvaluationModel(data)
  }

  addPmsMasfromEvaluation() {
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'บันทึกข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        if (this.pmsMasfromEvaluation.select.jd.length === 0) {
          this.plListFilter().forEach(x => this.selectPl(x));
        }
        const body = new MyPmsMasfromEvaluationModel(this.pmsMasfromEvaluation.select);
        this.dataLoading = true;
        this.pmsMasfromEvaluationCycleService.post(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success');
              this.getPmsMasfromEvaluationCycleList();
              this.closeDialog();
            } 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();
          }
        });
      }
    });
  }
  deletePmsMasfromEvaluation() {
    if (!this.numSelectItem()) {
      this.showAlert('กรุณาเลือกข้อมูลที่ต้องการลบ', 'error');
      return;
    }

    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการลบข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'ลบข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        this.dataLoading = true;
        const selectedKeys = Array.from(this.selectedItems.data.keys());
        const body = this.pmsMasfromEvaluation.dataList.filter(x => selectedKeys.includes(x.pmsEvaluationRoundId) && this.selectedItems.data.get(x.pmsEvaluationRoundId)).map(x => new MyPmsMasfromEvaluationModel(x))


        this.pmsMasfromEvaluationCycleService.delete(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success');
              this.getPmsMasfromEvaluationCycleList();
              this.closeDialog();
            } 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 MyPmsMasfromEvaluationModel(this.pmsMasfromEvaluation.select))
    }
  }

  openModal(id: string, evaluationRoundId: string) {
    this.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 MyPmsMasfromEvaluationModel(this.pmsMasfromEvaluation.select)
        body.active = 1
        this.dataLoading = true
        this.pmsMasfromEvaluationCycleService.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.pmsMasfromEvaluationCycleService.postCreateForm(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getPmsMasfromEvaluationCycleList()
            } 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.pmsMasfromEvaluation.dataList.find(x => x.pmsEvaluationRoundId == this.pmsMasfromEvaluation.select.pmsEvaluationRoundId)
  }

  openDialog() {
    this.dialogRef = this.dialog.open(this.managementEvaluationCycleModal, {
      width: '500px',
      disableClose: false,
    });
  }
  openPLDialog() {
    this.dialogRefPL = this.dialog.open(this.PLModal, {
      width: '800px',
    })
  }
  openDialogForm() {
    this.dialogRefForm = this.dialog.open(this.managementEvaluationCycleModalForm, {
      width: '1200px',
      disableClose: false,
    });
  }
  closeDialog() {
    this.dialogRef.close()
  }
  closePLDialog() {
    this.dialogRefPL.close()
  }
  closeDialogForm() {
    this.dialogRefForm.close()
  }
  onSelectItemChange(arg: any) {
    this.selectedItems = arg
  }

  numSelectItem() {
    const selectedKeys = Array.from(this.selectedItems.data.keys());
    const num = this.pmsMasfromEvaluation.dataList.filter(x => selectedKeys.includes(x.pmsEvaluationRoundId) && this.selectedItems.data.get(x.pmsEvaluationRoundId)).length
    return num
  }
}


