import { ChangeDetectorRef, Component } from '@angular/core';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { ToastrService } from 'ngx-toastr';
import { JobCodeModel, MyJobCodeModel } from 'src/app/shared/model/job-code.model';
import { FileService } from 'src/app/shared/services/file.service';
import { JobCodeService } from 'src/app/shared/services/job-code.service';


@Component({
  selector: 'app-sub-job-competency',
  templateUrl: './sub-job-competency.component.html',
  styleUrls: ['./sub-job-competency.component.scss']
})
export class SubJobCompetencyComponent {
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  pageSize = 10
  search = ""
  jobCodeList: JobCodeModel[] = []
  loading = false

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

  selectJob: JobCodeModel = new MyJobCodeModel({})
  currentModal: 'add' | 'edit' | 'delete' = "add"
  columns: ColumnModel[] = [{
    field: "jobcodeId",
    headerText: "JDCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "DescriptionJobTypeThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "DescriptionJobTypeEng",
    type: "string"
  }]
  searchSettings = {
    fields: ['jobcodeId', 'tdesc', 'edesc'],
    operator: 'contains',
    ignoreCase: false
  }
  constructor(
    private toastr: ToastrService,
    private fileService: FileService,
    private jobcodeService: JobCodeService,
    private cdr: ChangeDetectorRef,
  ) { }
  ngOnInit(): void {
    this.getListJob();
  }
  getListJob() {
    this.loading = false
    this.jobcodeService.getList().subscribe({
      next: response => {
        this.jobCodeList = response.map((x: any) => new MyJobCodeModel(x))
        this.jobCodeList = this.jobCodeList.sort((a, b) => a.jobcodeId.localeCompare(b.jobcodeId))
        this.loading = false
        this.searchChange()
        this.cdr.detectChanges()
      }, error: error => {
        this.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  searchChange() {
    this.currentPage = 1
    this.page = Array.from({ length: Math.ceil(this.jobcodeFilter().length / this.pageSize) }, (_, i) => i + 1);
  }
  edit(item: JobCodeModel) {
    this.selectJob = new MyJobCodeModel({})
    this.selectJob = new MyJobCodeModel(item)
  }
  clearValue() {
    this.selectJob.competencyWorkText = ''
  }
  save() {
    this.jobcodeService.post(this.selectJob).subscribe((response: any) => {
      if (response.success) {
        this.showAlert(response.message, 'success')
        this.selectJob = new MyJobCodeModel({})
        this.getListJob();
      } else {
        this.showAlert(response.message, 'error')
      }
      this.cdr.detectChanges()
    })
  }
  deleteJob() {
    this.jobcodeService.delete(this.selectJob).subscribe((response: any) => {
      if (response.success) {
        this.showAlert(response.message, 'success')
        this.selectJob = new MyJobCodeModel({})
        this.getListJob();
      } else {
        this.showAlert(response.message, 'error')
      }
      this.cdr.detectChanges()
    })
  }
  jobcodeFilter() {
    return this.jobCodeList.filter(x =>
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.jobcodeId.toLowerCase().includes(this.search.toLowerCase())
    )
  }
  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.loading = true
    this.fileService.uploadExcel(formData, 'MJOBCODE_COMPETENCY').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getListJob();
        } else {
          this.showAlert(response.message, 'error')
          this.loading = false
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.loading = false
      }
    })
  }


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

  }

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



}

