import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, TemplateRef, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ColumnModel } from '@syncfusion/ej2-grids';
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,
  page: number[],
  search: string
  pageSize: number
}

@Component({
  selector: 'app-set-approvers',
  templateUrl: './set-approvers.component.html',
  styleUrls: ['./set-approvers.component.scss']
})
export class SetApproversComponent implements OnInit {

  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  searchModal = ""

  groupapprove_list: GroupApproveModel[] = []
  groupapprove_listLoading = false
  groupapprove: GroupApproveModel = new MyGroupApproveModel()

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

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


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

  columns: ColumnModel[] = [{
    field: "apsassessy.thFullName",
    headerText: "EmployeeName",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "apsapprove1.thFullName",
    headerText: "Approver1",
    type: "string"
  },
  {
    field: "apsapprove2.thFullName",
    headerText: "Approver2",
    type: "string"
  },
  {
    field: "apsapprove3.thFullName",
    headerText: "Approver3",
    type: "string"
  },
  {
    field: "apsapprove4.thFullName",
    headerText: "Approver4",
    type: "string"
  },
  {
    field: "apsapprove5.thFullName",
    headerText: "Approver5",
    type: "string"
  }]
  searchSettings = {
    fields: ['apsassessy.thFullName', 'apsapprove1.thFullName', 'apsapprove2.thFullName', 'apsapprove3.thFullName', 'apsapprove4.thFullName', 'apsapprove5.thFullName'],
    operator: 'contains',
    ignoreCase: false
  };
  search = ''
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };

  @ViewChild("setApproversModal") setApproversModal: any;
  @ViewChild("employeeTableModal") employeeTableModal: any;
  dialogRef: any
  dialogRefEmp: any

  constructor(private groupapproveService: GroupApproveService,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private employeeService: EmployeeService,
    private fileService: FileService,
    private dialog: MatDialog
  ) { }
  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, 'COMPETENCY_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_COMPETENCY_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.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.thFullName.toLowerCase().includes(this.search.toLowerCase()) ||
      x.position.edesc.toLowerCase().includes(this.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.selectedItems.data.clear()
    this.groupapproveService.getList().subscribe({
      next: response => {
        this.groupapprove_list = response.map(x => {
          this.selectedItems.data.set(x.personalLevel.plId, false)
          return new MyGroupApproveModel(x)
        })
        this.selectedItems.key = 'personalLevel.plId'
        this.selectedItems.count = 0
        this.groupapprove_listLoading = false
        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.apsassessy.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsassessy.thFullName.toLowerCase().includes(this.search.toLowerCase()) ||

      x.apsapprove1.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove1.thFullName.toLowerCase().includes(this.search.toLowerCase()) ||

      x.apsapprove2.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove2.thFullName.toLowerCase().includes(this.search.toLowerCase()) ||

      x.apsapprove3.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove3.thFullName.toLowerCase().includes(this.search.toLowerCase()) ||

      x.apsapprove4.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove4.thFullName.toLowerCase().includes(this.search.toLowerCase()) ||

      x.apsapprove5.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.apsapprove5.thFullName.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
  }

  openDialog() {
    this.dialogRef = this.dialog.open(this.setApproversModal, {
      width: '500px',
    })
  }

  closeDialog() {
    this.dialogRef.close()
  }

  openDialogEmp() {
    this.dialogRefEmp = this.dialog.open(this.employeeTableModal, {
      width: '1200px',
    })
  }

  closeDialogEmp() {
    this.dialogRefEmp.close()
  }
}