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 { EmpGroupModel, MyEmpGroupModel } from 'src/app/shared/model/emp-group.model';
import { EmpGroupService } from 'src/app/shared/services/emp-group.service';
import { FileService } from 'src/app/shared/services/file.service';
import Swal from 'sweetalert2';
export interface DataModel {
  groupId: string
  tdesc: string
  edesc: string
  companyId: string
  checked: boolean
}

@Component({
  selector: 'app-employee-group-unit',
  templateUrl: './employee-group-unit.component.html',
  styleUrls: ['./employee-group-unit.component.scss']
})
export class EmployeeGroupUnit implements OnInit {
  currentModal: 'add' | 'edit' | 'delete' = 'add'
  emp_group: { loading: boolean, select: EmpGroupModel, dataList: EmpGroupModel[] } = { loading: false, select: new MyEmpGroupModel(), dataList: [] }
  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';

  columns: ColumnModel[] = [{
    field: "groupId",
    headerText: "EmployeeGroupCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "EmployeeGroupDescThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "EmployeeGroupDescEng",
    type: "string"
  }]
  searchSettings = {
    fields: ['groupId', '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("employeeGroupUnitModal") employeeGroupUnitModal: any; 
  dialogRef: any
  constructor(private empGroupService: EmpGroupService,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private dialog: MatDialog
  ) { }

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

  openDialog() {
    this.dialogRef = this.dialog.open(this.employeeGroupUnitModal, {
      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();
    formData.append('file', this.selectedFile);
    this.emp_group.loading = true
    this.fileService.uploadExcel(formData, 'mgroup').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getEmpGroupList()
        } else {
          this.showAlert(response.message, 'error')
          this.emp_group.loading = false
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.emp_group.loading = false
      }
    })
  }

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

  }

  getEmpGroupList() {
    this.emp_group.loading = true
    this.selectedItems.data.clear()
    this.empGroupService.getList().subscribe({
      next: response => {
        this.emp_group.dataList = response.map(x => {
          this.selectedItems.data.set(x.groupId, false)
          return new MyEmpGroupModel(x)
        })
        this.selectedItems.key = 'groupId'
        this.selectedItems.count = 0
        this.emp_group.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.emp_group.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  selectEmp_group(emp_group?: EmpGroupModel) {
    if (emp_group) {
      this.emp_group.select = new MyEmpGroupModel(emp_group)
    } else if (this.currentModal == 'add') {
      this.emp_group.select = new MyEmpGroupModel()
    } else if (this.currentModal == 'edit') {
      this.emp_group.select = new MyEmpGroupModel({ groupId: this.emp_group.select.groupId })
    }
  }

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

  deleteEmp_group() {
    if (this.numSelectItem() == 0) {
      this.showAlert('กรุณาเลือกข้อมูลที่จะลบ', 'error')
      return
    }
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการลบข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'ลบข้อมูล',
    }).then((result) => {
      if (result.isConfirmed) {
        this.emp_group.loading = true
        const selectedKeys = Array.from(this.selectedItems.data.keys());
    const body = this.emp_group.dataList.filter(x => selectedKeys.includes(x.groupId) && this.selectedItems.data.get(x.groupId)).map(x => new MyEmpGroupModel(x))
    this.empGroupService.delete(body).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success');
          this.getEmpGroupList();
        } else {
          this.showAlert(response.message, 'error');
          this.emp_group.loading = false
          this.cdr.detectChanges()
        }
      },
      error: error => {
        this.showAlert(error.message, 'error')
        this.emp_group.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_group.dataList.find(x => x.groupId == this.emp_group.select.groupId)
  }

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

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