import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
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';
export interface DataModel {
  plId: string
  tdesc: string
  edesc: string
  companyId: string
}

@Component({
  selector: 'app-employee-level',
  templateUrl: './employee-level.component.html',
  styleUrls: ['./employee-level.component.scss']
})
export class EmployeeLevel implements OnInit {
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  search = ""
  modalStatus = 'add'
  plList: { check: boolean, data: DataModel }[] = []
  pl: PLModel = new MyPLModel({})
  dataLoading = false
  dataSelect: DataModel = { plId: "", tdesc: "", edesc: "", companyId: "" }
  itemToDelete: PLModel | null = null;

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


  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false
  constructor(private plService: PLService,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService
  ) { }

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

  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.dataLoading = 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.dataLoading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.dataLoading = 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.dataLoading = true
    this.plService.getList().subscribe({
      next: response => {
        this.plList = response.map(x => ({ check: false, data: { plId: x.plId, tdesc: x.tdesc, edesc: x.edesc, companyId: x.companyId } }))
        this.dataLoading = false
        this.isDataListCheckedAll = false
        this.dataListCheckAll()
        this.searchChange();
        this.cdr.detectChanges();
      }, error: error => {
        this.dataLoading = false
        console.error('Error fetching employee types:', error);
        this.cdr.detectChanges()
      }
    });
  }

  searchChange() {
    this.currentPage = 1
    this.page = Array.from({ length: Math.ceil(this.plListFilter().length / 10) }, (_, i) => i + 1);
    this.dataListCheck();
    this.cdr.detectChanges()
  }

  plListFilter() {
    return this.plList.filter(x => {
      const data = x.data
      const match = data.plId.toLowerCase().includes(this.search.toLowerCase()) || data.tdesc.toLowerCase().includes(this.search.toLowerCase()) || data.edesc.toLowerCase().includes(this.search.toLowerCase());
      return match;
    });
  }

  setData(data?: DataModel) {
    this.dataSelect = JSON.parse(JSON.stringify(data || { plId: "", tdesc: "", edesc: "", companyId: "" }));
  }

  addPL() {
    const body = new MyPLModel({ plId: this.dataSelect.plId, tdesc: this.dataSelect.tdesc, edesc: this.dataSelect.edesc, companyId: this.dataSelect.companyId })
    this.dataLoading = true
    this.plService.post(body).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getPLList()
        } else {
          this.showAlert(response.message, 'error')
          this.dataLoading = true
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.dataLoading = true
        this.cdr.detectChanges()
      }
    })
  }

  deletePL() {
    let body: PLModel | PLModel[] = []
    if (this.dataSelect.plId) {
      body = new MyPLModel({ plId: this.dataSelect.plId, tdesc: this.dataSelect.tdesc, edesc: this.dataSelect.edesc, companyId: this.dataSelect.companyId })
    } else {
      body = this.plList.filter(x => x.check).map(x => new MyPLModel({ plId: x.data.plId, tdesc: x.data.tdesc, edesc: x.data.edesc, companyId: x.data.companyId }))
    }
    this.dataLoading = true
    this.plService.delete(body).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getPLList()
        } else {
          this.showAlert(response.message, 'error')
          this.dataLoading = true
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.dataLoading = true
        this.cdr.detectChanges()
      }
    })
  }

  showAlert(text: string, type: 'success' | 'error') {
    this.toastr[type](text, 'แจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    });
  }

  dataListCheckAll() {
    const selectAll = this.isDataListCheckedAll;
    this.plList.filter(x => {
      const data = x.data
      const match = data.plId.toLowerCase().includes(this.search.toLowerCase()) || data.tdesc.toLowerCase().includes(this.search.toLowerCase()) || data.edesc.toLowerCase().includes(this.search.toLowerCase());
      return match;
    }).forEach(x => x.check = selectAll);
    this.dataListCheck();
  }
  dataListCheck() {
    const dataCheck = this.plListFilter();
    this.isDataListCheckedAll = dataCheck.length ? dataCheck.every(x => x.check) : false;
    this.numDataListChecked = this.plList.filter(x => x.check).length
    this.isDataListChecked = Boolean(this.numDataListChecked)
  }


  clearPl(modalStatus: string) {
    if (modalStatus == 'add') {
      this.dataSelect.plId = ''
      this.dataSelect.tdesc = ''
      this.dataSelect.edesc = ''
    } else if (modalStatus == 'edit') {
      this.dataSelect.tdesc = ''
      this.dataSelect.edesc = ''
    }
  }
}