import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { EmployeeModel, MyEmployeeModel } from 'src/app/shared/model/employee.model';
import { GroupApproveModel, MyGroupApproveModel } from 'src/app/shared/model/group-approve.model';
import { EmployeeService } from 'src/app/shared/services/employee.service';
import { FileService } from 'src/app/shared/services/file.service';
import { GroupApproveService } from 'src/app/shared/services/group-approve.service';
interface table {
  currentPage: number,
  pageSize: number,
  page: number[],
  search: string
}
@Component({
  selector: 'app-assigning-approvers',
  templateUrl: './assigning-approvers.component.html',
  styleUrls: ['./assigning-approvers.component.scss']
})
export class AssigningApproversComponent {

  currentPage = 1
  pageSize = 10
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  groupapprove_list: GroupApproveModel[] = []
  groupapprove_listLoading = false
  groupapprove: GroupApproveModel = new MyGroupApproveModel()
  search = ""

  employee_list: EmployeeModel[] = []
  employee_listLoading = false
  employee: EmployeeModel = new MyEmployeeModel({})
  employeeModal: table = {
    currentPage: 1,
    pageSize: 10,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: ""
  }
  empnumber = 0

  currentModel: 'add' | 'edit' | 'delete' = "add"


  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';
  constructor(private groupapproveService: GroupApproveService,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private employeeService: EmployeeService,
    private fileService: FileService
  ) { }
  ngOnInit(): void {
    this.getGroupapprove_list()
    this.getEemployeeList()
  }
  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.groupapprove_listLoading = true
    this.fileService.uploadExcel(formData, 'PMS_GROUP_APPROVE').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getGroupapprove_list()
        } else {
          this.showAlert(response.message, 'error')
          this.groupapprove_listLoading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.groupapprove_listLoading = false
        this.cdr.detectChanges()
      }
    })
  }
  downloadFile() {
    const fileName = 'IMPORT_PMS_GROUP_APPROVE.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')
      }
    })
  }

  getEemployeeList() {
    this.employee_listLoading = true
    this.employeeService.getList().subscribe({
      next: response => {
        this.employee_list = response.map(x => {
          return new MyEmployeeModel(x)
        })
        this.employee_listLoading = false
        this.searchEMP()
        this.cdr.detectChanges()
      }, error: error => {
        this.employee_listLoading = false
        this.cdr.detectChanges()
      }
    })
  }
  employee_listFilter() {
    return this.employee_list.filter(x => x.fname.toLowerCase().includes(this.employeeModal.search.toLowerCase()) ||
      x.lname.toLowerCase().includes(this.employeeModal.search.toLowerCase()))
  }
  searchEMP() {
    this.employeeModal.currentPage = 1
    this.employeeModal.page = Array.from({ length: Math.ceil(this.employee_listFilter().length / 10) }, (_, i) => i + 1);
  }
  empChange() {
    const employee = this.employee_list.find(x => x.employeeId == this.employee.employeeId)
    this.selectEMP(employee || new MyEmployeeModel({ employeeId: this.employee.employeeId }))
  }
  selectEMP(employee?: EmployeeModel) {
    const data = new MyEmployeeModel(employee || {});
    if (this.empnumber == 1) {
      this.groupapprove.apsapprove1 = data
    } else if (this.empnumber == 2) {
      this.groupapprove.apsapprove2 = data
    } else if (this.empnumber == 3) {
      this.groupapprove.apsapprove3 = data
    } else if (this.empnumber == 4) {
      this.groupapprove.apsapprove4 = data
    } else if (this.empnumber == 5) {
      this.groupapprove.apsapprove5 = data
    }

  }
  getGroupapprove_list() {
    this.groupapprove_listLoading = true
    this.groupapproveService.getList().subscribe({
      next: response => {
        this.groupapprove_list = response.map(x => new MyGroupApproveModel(x))
        this.groupapprove_listLoading = false
        this.searchChange()
        this.cdr.detectChanges()
      }, error: error => {
        this.groupapprove_listLoading = false
        this.cdr.detectChanges()
      }
    })
  }
  searchChange() {
    this.currentPage = 1
    this.page = Array.from({ length: Math.ceil(this.groupapprove_listFilter().length / 10) }, (_, i) => i + 1);
  }
  groupapprove_listFilter() {
    return this.groupapprove_list.filter(x => x.apsapprove1.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove2.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove3.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove4.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove5.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove1.fname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove1.lname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove2.fname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove2.lname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove3.fname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove3.lname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove4.fname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove4.lname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove5.fname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove5.lname.toLowerCase().includes(this.search.toLowerCase()))
  }

  selectGroupapprove(groupapprove?: GroupApproveModel) {
    this.groupapprove = new MyGroupApproveModel(groupapprove)
  }

  showAlert(text: string, type: 'success' | 'error') {
    this.toastr[type](text, 'แจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    })
  }
  addgroupapprove() {
    this.groupapprove_listLoading = true
    this.groupapproveService.post(this.groupapprove).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getGroupapprove_list()
        } else {
          this.showAlert(response.message, 'error')
          this.groupapprove_listLoading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.groupapprove_listLoading = false
        this.cdr.detectChanges()
      }
    })
  }
  deletegroupapprove() {
    this.groupapprove_listLoading = true
    this.groupapproveService.delete(this.groupapprove).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getGroupapprove_list()
        } else {
          this.showAlert(response.message, 'error')
          this.groupapprove_listLoading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.groupapprove_listLoading = false
        this.cdr.detectChanges()
      }
    })
  }
  clear() {
    const data = new MyEmployeeModel({});
    this.groupapprove.apsapprove1 = data
    this.groupapprove.apsapprove2 = data
    this.groupapprove.apsapprove3 = data
    this.groupapprove.apsapprove4 = data
    this.groupapprove.apsapprove5 = data
  }
}