import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { ToastrService } from 'ngx-toastr';
import { MyPositionModel, PositionModel } from 'src/app/shared/model/position.model';
import { FileService } from 'src/app/shared/services/file.service';
import { PositionService } from 'src/app/shared/services/position.service';
import Swal from 'sweetalert2';
@Component({
  selector: 'app-job-family',
  templateUrl: './job-family.component.html',
  styleUrls: ['./job-family.component.scss']
})
export class JobFamilyComponent implements OnInit {
  selectedFile: File | null = null;
  selectedFileName: string = 'selectedFileName';
  currentModal: 'add' | 'edit' | 'delete' = 'add'
  position: { loading: boolean, select: PositionModel, dataList: PositionModel[] } = { loading: false, select: new MyPositionModel(), dataList: [] }

  columns: ColumnModel[] = [{
    field: "positionId",
    headerText: "JobFamilyCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "JobFamilyNameThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "JobFamilyNameEng",
    type: "string"
  }]
  searchSettings = {
    fields: ['positionId', 'tdesc', 'edesc'],
    operator: 'contains',
    ignoreCase: false
  };
  search = ''
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  @ViewChild("jobFamilyModal") jobFamilyModal: any;
  dialogRef: any

  selectedImg: File | null = null;
  imgLoading = false
  constructor(private positionService: PositionService,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private dialog: MatDialog
  ) { }
  ngOnInit(): void {
    this.getPositionList()
  }
  openDialog() {
    this.dialogRef = this.dialog.open(this.jobFamilyModal, {
      width: '500px',
    })
  }
  closeDialog() {
    this.dialogRef.close()
  }


  onFileSelected(event: any) {
    this.selectedFile = event.target.files.length > 0 ? event.target.files[0] : null;
    this.selectedFileName = this.selectedFile?.name || "selectedFileName"
  }

  uploadFile() {
    // if (!this.selectedFile) {
    //   alert('กรุณาเลือกไฟล์ก่อนอัปโหลด')
    //   return
    // }
    // const formData = new FormData();
    // formData.append('file', this.selectedFile);
    // this.position.loading = true
    // this.fileService.uploadExcel(formData, 'mposition').subscribe({
    //   next: response => {
    //     if (response.success) {
    //       this.showAlert(response.message, 'success')
    //       this.getPositionList()
    //     } else {
    //       this.showAlert(response.message, 'error')
    //       this.position.loading = false
    //       this.cdr.detectChanges();
    //     }
    //   }, error: error => {
    //     this.showAlert(error.message, 'error')
    //     this.position.loading = false
    //     this.cdr.detectChanges();
    //   }
    // })
  }

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

  }
  getPositionList() {
    this.position.loading = true
    this.selectedItems.data.clear()
    this.positionService.getList().subscribe({
      next: response => {
        this.position.dataList = response.map(x => {
          this.selectedItems.data.set(x.positionId, false)
          return new MyPositionModel(x)
        })
        this.selectedItems.key = 'positionId'
        this.selectedItems.count = 0
        this.position.loading = false
        this.cdr.detectChanges();
      }, error: error => {
        this.position.loading = false
        console.error('Error fetching employee types:', error);
        this.cdr.detectChanges()
      }
    })
  }

  selectPosition(position?: PositionModel) {
    if (position) {
      this.position.select = new MyPositionModel(position)
    } else if (this.currentModal == 'add') {
      this.position.select = new MyPositionModel()
    } else if (this.currentModal == 'edit') {
      this.position.select = new MyPositionModel({ positionId: this.position.select.positionId })
    }
  }

  addPosition() {
    // Swal.fire({
    //   icon: 'question',
    //   title: 'แจ้งเตือน',
    //   text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
    //   showCancelButton: true,
    //   confirmButtonText: 'ยืนยัน',
    // }).then((result) => {
    //   if (result.isConfirmed) {
    //     this.position.loading = true
    //     this.positionService.post(this.position.select).subscribe({
    //       next: response => {
    //         if (response.success) {
    //           this.showAlert(response.message, 'success')
    //           this.getPositionList()
    //           this.closeDialog()
    //         } else {
    //           this.showAlert(response.message, 'error')
    //           this.position.loading = false
    //           this.cdr.detectChanges()
    //           this.closeDialog()
    //         }
    //       }, error: error => {
    //         this.showAlert(error.message, 'error')
    //         this.position.loading = false
    //         this.cdr.detectChanges()
    //         this.closeDialog()
    //       }
    //     })
    //   }
    // })
  }

  deletePosition() {
    // if (this.numSelectItem() == 0) {
    //   this.showAlert('กรุณาเลือกข้อมูลที่จะลบ', 'error')
    //   return
    // }
    // Swal.fire({
    //   icon: 'question',
    //   title: 'แจ้งเตือน',
    //   text: 'ยืนยันการลบข้อมูลหรือไม่',
    //   showCancelButton: true,
    //   confirmButtonText: 'ลบข้อมูล',
    // }).then((result) => {
    //   if (result.isConfirmed) {
    //     this.position.loading = true
    //     const selectedKeys = Array.from(this.selectedItems.data.keys());
    //     const body = this.position.dataList.filter(x => selectedKeys.includes(x.positionId) && this.selectedItems.data.get(x.positionId)).map(x => new MyPositionModel(x))
    //     this.positionService.delete(body).subscribe({
    //       next: response => {
    //         if (response.success) {
    //           this.showAlert(response.message, 'success')
    //           this.getPositionList()
    //         } else {
    //           this.showAlert(response.message, 'error')
    //           this.position.loading = false
    //           this.cdr.detectChanges()
    //         }
    //       }, error: error => {
    //         this.showAlert(error.message, 'error')
    //         this.position.loading = false
    //         this.cdr.detectChanges()
    //       }
    //     })
    //   }
    // })
  }
  showAlert(text: string, type: 'success' | 'error') {
    Swal.fire({
      icon: type,
      title: 'แจ้งเตือน',
      text: text,
      showCancelButton: false,
      confirmButtonText: 'ยืนยัน',
    })
  }



  checkPrimary() {
    return this.position.dataList.find(x => x.positionId == this.position.select.positionId)
  }

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

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

  onImgSelected(event: any) {
    this.selectedImg = event.target.files.length > 0 ? event.target.files[0] : null;
    this.uploadImg()
  }
  uploadImg() {
    if (this.selectedImg) {
      this.imgLoading = true
      const formData = new FormData();
      formData.append('file', this.selectedImg);
      this.fileService.uploadImg(formData).subscribe({
        next: response => {
          if (response.success) {
            this.showAlert(response.message, 'success')
            // this.employee.select.picture = response.resultObject
          } else {
            this.showAlert(response.message, 'error')
            // this.employee.select.picture = ''
          }
          this.imgLoading = false
          this.cdr.detectChanges()
        }, error: error => {
          this.showAlert(error.message, 'error')
          // this.employee.select.picture = ''
          this.imgLoading = false
          this.cdr.detectChanges()
        }
      })
    }
  }
  getImg(text: string) {
    return this.fileService.getImg(text)
  }
  onImageError(event: Event) {
    const imgElement = event.target as HTMLImageElement;
    imgElement.src = './assets/img/users/defaultperson.jpg';
  }
}

