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-work-detail',
  templateUrl: './work-detail.component.html',
  styleUrls: ['./work-detail.component.scss']
})
export class WorkDetailComponent {
  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
  }
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  constructor(
    private toastr: ToastrService,
    private fileService: FileService,
    private jobcodeService: JobCodeService,
    private cdr: ChangeDetectorRef,
  ) { }
  ngOnInit(): void {
    this.getListJob();
  }
  getListJob() {
    this.loading = false
    this.selectedItems.data.clear()
    this.jobcodeService.getList().subscribe({
      next: response => {
        this.jobCodeList = response.map((x: any) => {
          this.selectedItems.data.set(x.jobcodeId, false)
          return new MyJobCodeModel(x)
        })
        this.selectedItems.key = 'jobcodeId'
        this.selectedItems.count = 0
        this.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.loading = false
        this.cdr.detectChanges()
      }
    })
  }


  edit(item: JobCodeModel) {
    this.selectJob = new MyJobCodeModel(item || {})
  }
  clearValue() {
    this.selectJob.competencyWorkText = ''
    this.selectJob.serviceWorkText = ''
    this.selectJob.serviceWorkPercent = 0
    this.selectJob.responsibleWorkText = ''
    this.selectJob.responsibleWorkPercent = 0
    this.selectJob.specialWorkText = ''
    this.selectJob.specialWorkPercent = 0
    this.selectJob.allPositionWorkText = ''
    this.selectJob.allPositionWorkPercent = 0
    this.selectJob.otherWorkText = ''
    this.selectJob.otherWorkPercent = 0
  }
  toNumber(value: string | number): number {
    return typeof value === 'string' ? parseInt(value) : value;
  }
  save() {
    this.selectJob.serviceWorkPercent = this.toNumber(this.selectJob.serviceWorkPercent)
    this.selectJob.responsibleWorkPercent = this.toNumber(this.selectJob.responsibleWorkPercent)
    this.selectJob.specialWorkPercent = this.toNumber(this.selectJob.specialWorkPercent)
    this.selectJob.allPositionWorkPercent = this.toNumber(this.selectJob.allPositionWorkPercent)
    this.selectJob.otherWorkPercent = this.toNumber(this.selectJob.otherWorkPercent)
    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() {
    const selectedKeys = Array.from(this.selectedItems.data.keys());
    const body = this.jobCodeList.filter(x => selectedKeys.includes(x.jobcodeId) && this.selectedItems.data.get(x.jobcodeId)).map(x => new MyJobCodeModel(x))
    this.jobcodeService.delete(body).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_DETAIL').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 _DETAIL.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',
    })
  }


  checkPrimary() {
    return this.jobCodeList.find(x => x.jobcodeId == this.selectJob.jobcodeId)
  }

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

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