import { ChangeDetectorRef, Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { FileService } from 'src/app/shared/services/file.service';
import { PLService } from 'src/app/shared/services/pl.service';
import { ColumnModel } from '@syncfusion/ej2-grids';
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';

@Component({
  selector: 'app-evaluation-grouping',
  templateUrl: './evaluation-grouping.component.html',
  styleUrls: ['./evaluation-grouping.component.scss']
})
export class EvaluationGroupingComponent {
  @Output() sendPathTitle: EventEmitter<string[]> = new EventEmitter<string[]>();
  onEdit = false

  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  pageSize = 10
  search = ""
  currentModal: 'add' | 'edit' | 'delete' | 'deleteGroup' = "add"

  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';

  columns: ColumnModel[] = [{
    field: "jobCodeId",
    headerText: "JDCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "name",
    headerText: "JobDescription",
    type: "string"
  }]
  searchSettings = {
    fields: ['jobCodeId', 'name'],
    operator: 'contains',
    ignoreCase: false
  };
  syncfutionDataList: any[] = []
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };

  pl: { loading: boolean, select: JobcodeModel, dataList: JobcodeModel[] } = { loading: false, select: new MyJobcodeModel(), dataList: [] }
  constructor(private toastr: ToastrService, private jobcodeService: JobcodeService, private cdr: ChangeDetectorRef, private fileService: FileService, private translateService: TranslateService
  ) {
    this.translateService.onLangChange.subscribe((event) => {
      this.setSyncfutionDataList()
    });

  }
  setSyncfutionDataList() {
    if (this.pl.dataList) {
      this.syncfutionDataList = this.pl.dataList.map(e => ({
        jobCodeId: e.jobCodeId,
        name: this.translateService.getCurrentLang() == 'th' ? e.tdesc : e.edesc,
      }))
    }
  }
  ngOnInit(): void {
    this.onSendPathTitle()
    this.getPLList()
  }
  onFileSelected(event: any) {
    this.selectedFile = event.target.files.length > 0 ? event.target.files[0] : null;
    this.selectedFileName = this.selectedFile?.name || "กรุณาเลือกไฟล์"
  }

  uploadFile() {
    if (!this.selectedFile) {
      alert('กรุณาเลือกไฟล์ก่อนอัปโหลด')
      return
    }
    const formData = new FormData();
    formData.append('file', this.selectedFile);
    this.pl.loading = true
    this.fileService.uploadExcel(formData, 'PMS_GROUP_ASSESSMENT').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getPLList()
        } else {
          this.showAlert(response.message, 'error')
          this.pl.loading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.pl.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  downloadFile() {
    const fileName = 'IMPORT_PMS_GROUP_ASSESSMENT.xlsx'
    this.fileService.downloadTemplate(fileName).subscribe({
      next: response => {
        const url = window.URL.createObjectURL(response);
        const a = document.createElement("a");
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      }, error: error => {
        this.showAlert(error.message, 'error')
      }
    })

  }
  getPLList() {
    this.pl.loading = true
    this.jobcodeService.getGroupAssessmentList().subscribe({
      next: response => {
        this.pl.dataList = response.map(x => {
          return new MyJobcodeModel(x)
        })
        this.pl.loading = false
        this.cdr.detectChanges();
        this.setSyncfutionDataList()
        this.cdr.markForCheck()
      }, error: error => {
        this.pl.loading = false
        console.error('Error fetching employee types:', error);
        this.cdr.detectChanges()
      }
    });
  }
  plListFilter() {
    return this.pl.dataList.filter(x => {
      const data = x
      const match = data.jobCodeId.toLowerCase().includes(this.search.toLowerCase()) || data.tdesc.toLowerCase().includes(this.search.toLowerCase())
      return match;
    });
  }
  selectPl(dataSelect?: any) {
    const data = this.pl.dataList.find(e => e.jobCodeId == dataSelect.jobCodeId)
    if (data) {
      this.pl.select = new MyJobcodeModel(data)
    } else if (this.currentModal == 'add') {
      this.pl.select = new MyJobcodeModel()
    } else if (this.currentModal == 'edit') {
      this.pl.select = new MyJobcodeModel({ jobCodeId: this.pl.select.jobCodeId })
    }
  }
  searchChange() {
    this.currentPage = 1
    this.page = Array.from({ length: Math.ceil(this.plListFilter().length / 10) }, (_, i) => i + 1)
    this.cdr.detectChanges()
  }
  onSendPathTitle() {
    if (this.onEdit) {
      this.sendPathTitle.emit(['menu.PerformanceManagementSystem', 'PMSManage', 'GroupingKPI', 'แก้ไขกลุ่มการประเมิน']);
    } else if (!this.onEdit) {
      this.sendPathTitle.emit(['menu.PerformanceManagementSystem', 'PMSManage', 'GroupingKPI']);
    }
  }

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

}

