import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { ToastrService } from 'ngx-toastr';
import { JobcodeModel, MyJobcodeModel } from 'src/app/shared/model/jobcode.model';
import { FileService } from 'src/app/shared/services/file.service';
import { JobcodeService } from 'src/app/shared/services/jobcode.service';

@Component({
  selector: 'app-group-competencies',
  templateUrl: './group-competencies.component.html',
  styleUrls: ['./group-competencies.component.scss']
})
export class GroupCompetenciesComponent {
  @Output() sendPathTitle: EventEmitter<string[]> = new EventEmitter<string[]>();
  editTab = false
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);

  groupCompetenciesList: JobcodeModel[] = []
  groupCompetencies: JobcodeModel = new MyJobcodeModel({})
  dataLoading = false

  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';
  syncfutionDataList: any[] = []
  columns: ColumnModel[] = [{
    field: "jobCodeId",
    headerText: "JDCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "name",
    headerText: "JobDescription",
    type: "string"
  }]
  searchSettings = {
    fields: ['jobCodeId', 'name'],
    operator: 'contains',
    ignoreCase: false
  };
  search = ''
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };

  constructor(private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private jobcodeService: JobcodeService,
    private translateService: TranslateService
  ) {
    this.pathTitleChange()
    this.translateService.onLangChange.subscribe((event) => {
      this.setSyncfutionDataList()
    });

  }
  ngOnInit(): void {
    this.getGroupCompetenciesList()
  }

  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.dataLoading = true
    this.fileService.uploadExcel(formData, 'COMPETENCY_GROUP_ASSESSMENT').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.dataLoading = false
          this.cdr.detectChanges()
        } 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()
      }
    })
  }

  downloadFile() {
    const fileName = 'IMPORT_COMPETENCY_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')
      }
    })

  }
  getGroupCompetenciesList() {
    this.dataLoading = true
    this.selectedItems.data.clear()
    this.jobcodeService.getGroupAssessmentList().subscribe({
      next: response => {
        this.groupCompetenciesList = response.map(x => {
          this.selectedItems.data.set(x.jobCodeId, false)
          return new MyJobcodeModel(x)
        })
        this.setSyncfutionDataList()
        this.groupCompetenciesList = response
        this.dataLoading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.dataLoading = false
        this.cdr.detectChanges()
      }
    })
  }
  setSyncfutionDataList() {
    if (this.groupCompetenciesList) {
      this.syncfutionDataList = this.groupCompetenciesList.map(e => ({
        jobCodeId: e.jobCodeId,
        name: this.translateService.getCurrentLang() == 'th' ? e.tdesc : e.edesc,
      }))
    }
  }
  selectGroupCompetencies(data: any) {
    const groupCompetencies = this.groupCompetenciesList.find(x => x.jobCodeId == data.jobCodeId)
    this.groupCompetencies = new MyJobcodeModel(groupCompetencies)
  }

  pathTitleChange() {
    this.sendPathTitle.emit(this.editTab ? ['การประเมินสมรรถนะ', 'การจัดการสมรรถนะ', 'จัดกลุ่มสมรรถนะ', 'แก้ไขกลุ่มสมรรถนะ'] : ['การประเมินสมรรถนะ', 'การจัดการสมรรถนะ', 'จัดกลุ่มสมรรถนะ'])
  }


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

  checkPrimary() {
    return this.groupCompetenciesList.find(x => x.jobCodeId == this.groupCompetencies.jobCodeId)
  }

}
