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 { MyPLModel, PLModel } from 'src/app/shared/model/pl.model';
import { FileService } from 'src/app/shared/services/file.service';
import { PLService } from 'src/app/shared/services/pl.service';
import Swal from 'sweetalert2';
@Component({
  selector: 'app-employee-level',
  templateUrl: './employee-level.component.html',
  styleUrls: ['./employee-level.component.scss']
})
export class EmployeeLevel implements OnInit {
  search = ""
  currentModal: 'add' | 'edit' | 'delete' = 'add'
  pl: { loading: boolean, select: PLModel, dataList: PLModel[] } = { loading: false, select: new MyPLModel(), dataList: [] }


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


  columns: ColumnModel[] = [{
    field: "plId",
    headerText: "JobLevelCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "JobLevelDescThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "JobLevelDescEng",
    type: "string"
  }]
  searchSettings = {
    fields: ['plId', 'tdesc', 'edesc'],
    operator: 'contains',
    ignoreCase: false
  }
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  @ViewChild("employeeLevelModal") employeeLevelModal: any;   
  dialogRef: any
  constructor(private plService: PLService,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private dialog: MatDialog 
  ) { }

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

  openDialog() {
    this.dialogRef = this.dialog.open(this.employeeLevelModal, {
      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.pl.loading = true
    this.fileService.uploadExcel(formData, 'pl').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getPLList()
        } else {
          this.showAlert(response.message, 'error')
          this.pl.loading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.pl.loading = false
        this.cdr.detectChanges()
      }
    })
  }

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

  }

  getPLList() {
    this.pl.loading = true
    this.selectedItems.data.clear()
    this.plService.getList().subscribe({
      next: response => {
        this.pl.dataList = response.map(x => {
          this.selectedItems.data.set(x.plId, false)
          return new MyPLModel(x)
        })
        this.selectedItems.key = 'plId'
        this.selectedItems.count = 0
        this.pl.loading = false
        this.cdr.detectChanges();
      }, error: error => {
        this.pl.loading = false
        this.cdr.detectChanges()
      }
    });
  }

  selectPl(pl?: PLModel) {
    if (pl) {
      this.pl.select = new MyPLModel(pl)
    } else if (this.currentModal == 'add') {
      this.pl.select = new MyPLModel()
    } else if (this.currentModal == 'edit') {
      this.pl.select = new MyPLModel({ plId: this.pl.select.plId })
    }
  }

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

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

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


  checkPrimary() {
    return this.pl.dataList.find(x => x.plId == this.pl.select.plId)
  }

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

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