import { ChangeDetectorRef, Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { ToastrService } from 'ngx-toastr';
import { EmpTypeModel, MyEmpTypeModel } from 'src/app/shared/model/employee-type.model';
import { EmpTypeService } from 'src/app/shared/services/employee-type.service';
import { FileService } from 'src/app/shared/services/file.service';
import Swal from 'sweetalert2';
@Component({
  selector: 'app-employee-categories',
  templateUrl: './employee-categories.component.html',
  styleUrls: ['./employee-categories.component.scss']
})
export class EmployeeCategories {
  search = ""
  currentModal: 'add' | 'edit' | 'delete' = 'add'
  emp_type: { loading: boolean, select: EmpTypeModel, dataList: EmpTypeModel[] } = { loading: false, select: new MyEmpTypeModel(), dataList: [] }
  itemToDelete: EmpTypeModel | null = null;

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

  columns: ColumnModel[] = [{
    field: "codeId",
    headerText: "EmploymentTypeCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "EmploymentTypeDescThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "EmploymentTypeDescEng",
    type: "string"
  }]
  searchSettings = {
    fields: ['codeId', 'tdesc', 'edesc'],
    operator: 'contains',
    ignoreCase: false
  }
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  @ViewChild("employeeCategoriesModal") employeeCategoriesModal: any;
  dialogRef: any
  constructor(private empTypeService: EmpTypeService,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private dialog: MatDialog 
  ) { }
  ngOnInit(): void {
    this.getEmpTypeList()
  }

  openDialog() {
    this.dialogRef = this.dialog.open(this.employeeCategoriesModal, {
      width: '500px',
      height: '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 || "กรุณาเลือกไฟล์"
  }

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

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

  }

  getEmpTypeList() {
    this.emp_type.loading = true
    this.selectedItems.data.clear()
    this.empTypeService.getList().subscribe({
      next: response => {
        this.emp_type.dataList = response.map(x => {
          this.selectedItems.data.set(x.codeId, false)
          return new MyEmpTypeModel(x)
        })
        this.selectedItems.key = 'codeId'
        this.selectedItems.count = 0
        this.emp_type.loading = false
        this.cdr.detectChanges();
      }, error: error => {
        this.emp_type.loading = false
        this.cdr.detectChanges()
      }
    });
  }

  selectEmp_type(emp_type?: EmpTypeModel) {
    if (emp_type) {
      this.emp_type.select = new MyEmpTypeModel(emp_type)
    } else if (this.currentModal == 'add') {
      this.emp_type.select = new MyEmpTypeModel()
    } else if (this.currentModal == 'edit') {
      this.emp_type.select = new MyEmpTypeModel({ codeId: this.emp_type.select.codeId })
    }
  }



  addEmp_type() {
    Swal.fire({
      icon: 'warning',
      title: 'แจ้งเตือน',
      text: 'คุณต้องการเพิ่มประเภทพนักงานหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'ยืนยัน',
    }).then((result) => {
      if (result.isConfirmed) {
        this.emp_type.loading = true
        this.empTypeService.post(this.emp_type.select).subscribe({
          next: response => {
            if (response.success) {
          this.showAlert(response.message, 'success')
          this.getEmpTypeList()
          this.closeDialog()
        } else {
          this.showAlert(response.message, 'error')
          this.emp_type.loading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.emp_type.loading = false
              this.cdr.detectChanges()
            }
          })
      }
    })
  }

  deleteEmp_type() {
    if (this.numSelectItem() == 0) {
      this.showAlert('กรุณาเลือกข้อมูลที่จะลบ', 'error')
      return
    }
    Swal.fire({
      icon: 'warning',
      title: 'แจ้งเตือน',
      text: 'คุณต้องการลบประเภทพนักงานทั้งหมดหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'ยืนยัน',
    }).then((result) => {
      if (result.isConfirmed) {
        this.emp_type.loading = true
        const selectedKeys = Array.from(this.selectedItems.data.keys());
    const body = this.emp_type.dataList.filter(x => selectedKeys.includes(x.codeId) && this.selectedItems.data.get(x.codeId)).map(x => new MyEmpTypeModel(x))
    this.empTypeService.delete(body).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getEmpTypeList()
        } else {
          this.showAlert(response.message, 'error')
          this.emp_type.loading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.emp_type.loading = false
            this.cdr.detectChanges()
          }
        })
      }
    })
  }

  showAlert(text: string, type: 'success' | 'error') {
    Swal.fire({
      icon: type,
      title: 'แจ้งเตือน',
      text: text,
      showCancelButton: false,
      confirmButtonText: 'ยืนยัน',
    })
  }


  checkPrimary() {
    return this.emp_type.dataList.find(x => x.codeId == this.emp_type.select.codeId)
  }

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

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