import { ChangeDetectorRef, Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { BranchModel, MyBranchModel } from 'src/app/shared/model/branch.model';
import { Bu1Model, MyBu1Model } from 'src/app/shared/model/bu1.model';
import { EmpGroupModel, MyEmpGroupModel } from 'src/app/shared/model/emp-group.model';
import { EmpTypeModel, MyEmpTypeModel } from 'src/app/shared/model/employee-type.model';
import { EmployeeModel, MyEmployeeModel } from 'src/app/shared/model/employee.model';
import { JobCodeModel, MyJobCodeModel } from 'src/app/shared/model/job-code.model';
import { MyPLModel, PLModel } from 'src/app/shared/model/pl.model';
import { MyPositionModel, PositionModel } from 'src/app/shared/model/position.model';
import { Bu1Service } from 'src/app/shared/services/bu1.service';
import { EmpGroupService } from 'src/app/shared/services/emp-group.service';
import { EmpTypeService } from 'src/app/shared/services/employee-type.service';
import { EmployeeService } from 'src/app/shared/services/employee.service';
import { FileService } from 'src/app/shared/services/file.service';
import { PLService } from 'src/app/shared/services/pl.service';
import { PositionService } from 'src/app/shared/services/position.service';
import { BranchService } from 'src/app/shared/services/่branch.service';
import { JobCodeService } from 'src/app/shared/services/job-code.service';
import { Bu2Model, MyBu2Model } from 'src/app/shared/model/bu2.model';
import { Bu2Service } from 'src/app/shared/services/bu2.service';
import { Bu3Service } from 'src/app/shared/services/bu3.service';
import { Bu4Service } from 'src/app/shared/services/bu4.service';
import { Bu5Service } from 'src/app/shared/services/bu5.service';
import { Bu6Service } from 'src/app/shared/services/bu6.service';
import { Bu7Service } from 'src/app/shared/services/bu7.service';
import { Bu3Model, MyBu3Model } from 'src/app/shared/model/bu3.model';
import { Bu4Model, MyBu4Model } from 'src/app/shared/model/bu4.model';
import { Bu5Model, MyBu5Model } from 'src/app/shared/model/bu5.model';
import { Bu6Model, MyBu6Model } from 'src/app/shared/model/bu6.model';
import { Bu7Model, MyBu7Model } from 'src/app/shared/model/bu7.model';
import { EmpStatusService } from 'src/app/shared/services/emp-status.service';
import { StatusModel, MyStatusModel } from 'src/app/shared/model/status.model';
import { MyBossModel } from 'src/app/shared/model/boss.model';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { MatDialog } from '@angular/material/dialog';
import Swal from 'sweetalert2';
import { environment } from 'src/environments/environment';
import { TokenService } from 'src/app/shared/services/token.service';
export interface DataModal {
  search: string,
  currentPage: number,
  page: number[]
  pageSize: number
}
@Component({
  selector: 'app-sub-employee-registration',
  templateUrl: './sub-employee-registration.component.html',
  styleUrls: ['./sub-employee-registration.component.scss']
})

export class SubEmployeeRegistrationComponent {
  employee: { loading: boolean, select: EmployeeModel | any, dataList: EmployeeModel[] } = { loading: false, select: new MyEmployeeModel(), dataList: [] }
  search = ""
  currentModal: 'add' | 'update' | 'delete' = 'add'
  columns: ColumnModel[] = [
    {
      field: "picture",
      headerText: "",
      type: "string",
    }, {
      field: "employeeId",
      headerText: "EmployeeCode",
      type: "string",
      isPrimaryKey: true,
    },
    {
      field: "fname",
      headerText: "FirstName",
      type: "string"
    },
    {
      field: "lname",
      headerText: "LastName",
      type: "string"
    },
    {
      field: "position.tdesc",
      headerText: "Position",
      type: "string"
    }]
  searchSettings = {
    fields: ['employeeId', 'fname', 'lname', 'position.tdesc'],
    operator: 'contains',
    ignoreCase: false
  }
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };

  modal: DataModal = {
    search: "",
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    pageSize: 10
  }
  pageSize: number = 10
  page: number = 1
  currentPage: number = 1

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

  selectedImg: File | null = null;
  imgLoading = false

  empGroup: { loading: boolean, dataList: EmpGroupModel[] } = { loading: false, dataList: [] }
  employeeModal: { loading: boolean, dataList: EmployeeModel[] } = { loading: false, dataList: [] }
  bu1: { loading: boolean, dataList: Bu1Model[] } = { loading: false, dataList: [] }
  bu2: { loading: boolean, dataList: Bu2Model[] } = { loading: false, dataList: [] }
  bu3: { loading: boolean, dataList: Bu3Model[] } = { loading: false, dataList: [] }
  bu4: { loading: boolean, dataList: Bu4Model[] } = { loading: false, dataList: [] }
  bu5: { loading: boolean, dataList: Bu5Model[] } = { loading: false, dataList: [] }
  bu6: { loading: boolean, dataList: Bu6Model[] } = { loading: false, dataList: [] }
  bu7: { loading: boolean, dataList: Bu7Model[] } = { loading: false, dataList: [] }
  position: { loading: boolean, dataList: PositionModel[] } = { loading: false, dataList: [] }
  jobcode: { loading: boolean, dataList: JobCodeModel[] } = { loading: false, dataList: [] }
  branch: { loading: boolean, dataList: BranchModel[] } = { loading: false, dataList: [] }
  empType: { loading: boolean, dataList: EmpTypeModel[] } = { loading: false, dataList: [] }
  pl: { loading: boolean, dataList: PLModel[] } = { loading: false, dataList: [] }
  empStatus: { loading: boolean, dataList: StatusModel[] } = { loading: false, dataList: [] }

  @ViewChild('employeeRegistrationModal') employeeRegistrationModal: any
  dialogRef: any
  @ViewChild('empGroupModal') empGroupModal: any
  empGroupDialogRef: any
  @ViewChild('employeeListModal') employeeListModal: any
  employeeListDialogRef: any
  @ViewChild('bu1Modal') bu1Modal: any
  bu1DialogRef: any
  @ViewChild('bu2Modal') bu2Modal: any
  bu2DialogRef: any
  @ViewChild('bu3Modal') bu3Modal: any
  bu3DialogRef: any
  @ViewChild('bu4Modal') bu4Modal: any
  bu4DialogRef: any
  @ViewChild('bu5Modal') bu5Modal: any
  bu5DialogRef: any
  @ViewChild('bu6Modal') bu6Modal: any
  bu6DialogRef: any
  @ViewChild('bu7Modal') bu7Modal: any
  bu7DialogRef: any
  @ViewChild('positionModal') positionModal: any
  positionDialogRef: any
  @ViewChild('jobcodeModal') jobcodeModal: any
  jobcodeDialogRef: any
  @ViewChild('branchModal') branchModal: any
  branchDialogRef: any
  @ViewChild('employeeTypeModal') employeeTypeModal: any
  employeeTypeDialogRef: any
  @ViewChild('employeePlModal') employeePlModal: any
  employeePlDialogRef: any
  constructor(private toastr: ToastrService,
    private employeeService: EmployeeService,
    private cdr: ChangeDetectorRef,
    private empGroupService: EmpGroupService,
    private bu1Service: Bu1Service,
    private bu2Service: Bu2Service,
    private bu3Service: Bu3Service,
    private bu4Service: Bu4Service,
    private bu5Service: Bu5Service,
    private bu6Service: Bu6Service,
    private bu7Service: Bu7Service,
    private positionService: PositionService,
    private jobcodeService: JobCodeService,
    private branchService: BranchService,
    private empTypeService: EmpTypeService,
    private empStatusService: EmpStatusService,
    private fileService: FileService,
    private dialog: MatDialog,
    private tokenService: TokenService,
    private pLService: PLService) { }

  ngOnInit(): void {
    this.getEmployeeList()
    this.getEmpGroupList()
    this.getBu1List()
    this.getPositionList()
    this.getJobcodeList()
    this.getBranchList()
    this.getEmpTypeList()
    this.getPlList()
    this.getEmpStatusList()
  }
  openDialog() {
    this.dialogRef = this.dialog.open(this.employeeRegistrationModal, {
      width: '800px',
    })
  }
  closeDialog() {
    this.dialogRef.close()
  }
  openEmpGroupDialog() {
    this.empGroupDialogRef = this.dialog.open(this.empGroupModal, {
      width: '800px',
    })
  }
  closeEmpGroupDialog() {
    this.empGroupDialogRef.close()
  }
  openEmployeeListDialog() {
    this.employeeListDialogRef = this.dialog.open(this.employeeListModal, {
      width: '800px',
    })
  }
  closeEmployeeListDialog() {
    this.employeeListDialogRef.close()
  }
  openBu1Dialog() {
    this.bu1DialogRef = this.dialog.open(this.bu1Modal, {
      width: '800px',
    })
  }
  closeBu1Dialog() {
    this.bu1DialogRef.close()
  }
  openBu2Dialog() {
    this.bu2DialogRef = this.dialog.open(this.bu2Modal, {
      width: '800px',
    })
  }
  closeBu2Dialog() {
    this.bu2DialogRef.close()
  }
  openBu3Dialog() {
    this.bu3DialogRef = this.dialog.open(this.bu3Modal, {
      width: '800px',
    })
  }
  closeBu3Dialog() {
    this.bu3DialogRef.close()
  }
  openBu4Dialog() {
    this.bu4DialogRef = this.dialog.open(this.bu4Modal, {
      width: '800px',
    })
  }
  closeBu4Dialog() {
    this.bu4DialogRef.close()
  }
  openBu5Dialog() {
    this.bu5DialogRef = this.dialog.open(this.bu5Modal, {
      width: '800px',
    })
  }
  closeBu5Dialog() {
    this.bu5DialogRef.close()
  }
  openBu6Dialog() {
    this.bu6DialogRef = this.dialog.open(this.bu6Modal, {
      width: '800px',
    })
  }
  closeBu6Dialog() {
    this.bu6DialogRef.close()
  }
  openBu7Dialog() {
    this.bu7DialogRef = this.dialog.open(this.bu7Modal, {
      width: '800px',
    })
  }
  closeBu7Dialog() {
    this.bu7DialogRef.close()
  }
  openPositionDialog() {
    this.positionDialogRef = this.dialog.open(this.positionModal, {
      width: '800px',
    })
  }
  closePositionDialog() {
    this.positionDialogRef.close()
  }
  openJobcodeDialog() {
    this.jobcodeDialogRef = this.dialog.open(this.jobcodeModal, {
      width: '800px',
    })
  }
  closeJobcodeDialog() {
    this.jobcodeDialogRef.close()
  }
  openBranchDialog() {
    this.branchDialogRef = this.dialog.open(this.branchModal, {
      width: '800px',
    })
  }
  closeBranchDialog() {
    this.branchDialogRef.close()
  }
  openEmployeeTypeDialog() {
    this.employeeTypeDialogRef = this.dialog.open(this.employeeTypeModal, {
      width: '800px',
    })
  }
  closeEmployeeTypeDialog() {
    this.employeeTypeDialogRef.close()
  }
  openEmployeePlDialog() {
    this.employeePlDialogRef = this.dialog.open(this.employeePlModal, {
      width: '800px',
    })
  }
  closeEmployeePlDialog() {
    this.employeePlDialogRef.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.employee.loading = true
    this.fileService.uploadExcel(formData, 'memployee').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getEmployeeList()
        } else {
          this.showAlert(response.message, 'error')
          this.employee.loading = false
          this.cdr.detectChanges();
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.employee.loading = false
        this.cdr.detectChanges();
      }
    })
  }
  downloadFile() {
    const fileName = 'IMPORT_MEMPLOYEE.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')
      }
    })

  }
  getEmpStatusList() {
    this.empStatus.loading = false
    this.empStatusService.getList().subscribe({
      next: response => {
        this.empStatus.dataList = response.map((x: any) => new MyStatusModel(x))
        this.empStatus.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.empStatus.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  getPlList() {
    this.pl.loading = false
    this.pLService.getList().subscribe({
      next: response => {
        this.pl.dataList = response.map((x: any) => new MyPLModel(x))
        this.pl.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.pl.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  plListFilter() {
    return this.pl.dataList.filter(x => x.plId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()))
  }

  getEmpTypeList() {
    this.empType.loading = false
    this.empTypeService.getList().subscribe({
      next: response => {
        this.empType.dataList = response.map((x: any) => new MyEmpTypeModel(x))
        this.empType.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.empType.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  empTypeListFilter() {
    return this.empType.dataList.filter(x => x.codeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()))
  }

  getBranchList() {
    this.branch.loading = false
    this.branchService.getList().subscribe({
      next: response => {
        this.branch.dataList = response.map((x: any) => new MyBranchModel(x))
        this.branch.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.branch.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  branchListFilter() {
    return this.branch.dataList.filter(x => x.branchId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()))
  }

  getJobcodeList() {
    this.jobcode.loading = false
    this.jobcodeService.getList().subscribe({
      next: response => {
        this.jobcode.dataList = response.map((x: any) => new MyJobCodeModel(x))
        this.jobcode.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.jobcode.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  jobcodeListFilter() {
    return this.jobcode.dataList.filter(x => x.jobcodeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()))
  }

  getPositionList() {
    this.position.loading = false
    this.positionService.getList().subscribe({
      next: response => {
        this.position.dataList = response.map((x: any) => new MyPositionModel(x))
        this.position.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.position.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  positionListFilter() {
    return this.position.dataList.filter(x => x.positionId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()))
  }

  getBu1List() {
    this.bu1.loading = false
    this.bu1Service.getList().subscribe({
      next: response => {
        this.bu1.dataList = response?.map((x: any) => new MyBu1Model(x)) || []
        this.bu1.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.bu1.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  bu1ListFilter() {
    return this.bu1.dataList.filter(x => x.bu1id.toLowerCase().includes(this.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()))
  }
  selectBu1(data?: Bu1Model) {
    this.employee.select.bu1 = new MyBu1Model(data)
    this.employee.select.bu2 = new MyBu2Model()
    this.employee.select.bu3 = new MyBu3Model()
    this.employee.select.bu4 = new MyBu4Model()
    this.employee.select.bu5 = new MyBu5Model()
    this.employee.select.bu6 = new MyBu6Model()
    this.employee.select.bu7 = new MyBu7Model()
    if (this.employee.select.bu1.bu1id) {
      this.getBu2List()
    } else {
      this.bu2.dataList = []
    }
  }

  getBu2List() {
    this.bu2.loading = false
    this.bu2Service.getListByParent(this.employee.select.bu1.bu1id).subscribe({
      next: response => {
        this.bu2.dataList = response?.map((x: any) => new MyBu2Model(x)) || []
        this.bu2.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.bu2.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  bu2ListFilter() {
    return this.bu2.dataList.filter(x => x.bu2id.toLowerCase().includes(this.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()))
  }
  selectBu2(data?: Bu2Model) {
    this.employee.select.bu2 = new MyBu2Model(data)
    this.employee.select.bu3 = new MyBu3Model()
    this.employee.select.bu4 = new MyBu4Model()
    this.employee.select.bu5 = new MyBu5Model()
    this.employee.select.bu6 = new MyBu6Model()
    this.employee.select.bu7 = new MyBu7Model()
    if (this.employee.select.bu2.bu2id) {
      this.getBu3List()
    } else {
      this.bu3.dataList = []
    }
  }

  getBu3List() {
    this.bu3.loading = false
    this.bu3Service.getListByParent(this.employee.select.bu2.bu2id).subscribe({
      next: response => {
        this.bu3.dataList = response?.map((x: any) => new MyBu3Model(x)) || []
        this.bu3.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.bu3.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  bu3ListFilter() {
    return this.bu3.dataList.filter(x => x.bu3id.toLowerCase().includes(this.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()))
  }
  selectBu3(data?: Bu3Model) {
    this.employee.select.bu3 = new MyBu3Model(data)
    this.employee.select.bu4 = new MyBu4Model()
    this.employee.select.bu5 = new MyBu5Model()
    this.employee.select.bu6 = new MyBu6Model()
    this.employee.select.bu7 = new MyBu7Model()
    if (this.employee.select.bu3.bu3id) {
      this.getBu4List()
    } else {
      this.bu4.dataList = []
    }
  }

  getBu4List() {
    this.bu4.loading = false
    this.bu4Service.getListByParent(this.employee.select.bu3.bu3id).subscribe({
      next: response => {
        this.bu4.dataList = response?.map((x: any) => new MyBu4Model(x)) || []
        this.bu4.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.bu4.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  bu4ListFilter() {
    return this.bu4.dataList.filter(x => x.bu4id.toLowerCase().includes(this.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()))
  }
  selectBu4(data?: Bu4Model) {
    this.employee.select.bu4 = new MyBu4Model(data)
    this.employee.select.bu5 = new MyBu5Model()
    this.employee.select.bu6 = new MyBu6Model()
    this.employee.select.bu7 = new MyBu7Model()
    if (this.employee.select.bu4.bu4id) {
      this.getBu5List()
    } else {
      this.bu5.dataList = []
    }
  }

  getBu5List() {
    this.bu5.loading = false
    this.bu5Service.getListByParent(this.employee.select.bu4.bu4id).subscribe({
      next: response => {
        this.bu5.dataList = response?.map((x: any) => new MyBu5Model(x)) || []
        this.bu5.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.bu5.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  bu5ListFilter() {
    return this.bu5.dataList.filter(x => x.bu5id.toLowerCase().includes(this.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()))
  }
  selectBu5(data?: Bu5Model) {
    this.employee.select.bu5 = new MyBu5Model(data)
    this.employee.select.bu6 = new MyBu6Model()
    this.employee.select.bu7 = new MyBu7Model()
    if (this.employee.select.bu5.bu5id) {
      this.getBu6List()
    } else {
      this.bu6.dataList = []
    }
  }

  getBu6List() {
    this.bu6.loading = false
    this.bu6Service.getListByParent(this.employee.select.bu5.bu5id).subscribe({
      next: response => {
        this.bu6.dataList = response?.map((x: any) => new MyBu6Model(x)) || []
        this.bu6.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.bu6.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  bu6ListFilter() {
    return this.bu6.dataList.filter(x => x.bu6id.toLowerCase().includes(this.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()))
  }
  selectBu6(data?: Bu6Model) {
    this.employee.select.bu6 = new MyBu6Model(data)
    this.employee.select.bu7 = new MyBu7Model()
    if (this.employee.select.bu6.bu6id) {
      this.getBu7List()
    } else {
      this.bu7.dataList = []
    }
  }

  getBu7List() {
    this.bu7.loading = false
    this.bu7Service.getListByParent(this.employee.select.bu6.bu6id).subscribe({
      next: response => {
        this.bu7.dataList = response?.map((x: any) => new MyBu7Model(x)) || []
        this.bu7.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.bu7.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  bu7ListFilter() {
    return this.bu7.dataList.filter(x => x.bu7id.toLowerCase().includes(this.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()))
  }
  selectBu7(data?: Bu7Model) {
    this.employee.select.bu7 = new MyBu7Model(data)
  }

  getEmpGroupList() {
    this.empGroup.loading = false
    this.empGroupService.getList().subscribe({
      next: response => {
        this.empGroup.dataList = response.map((x: any) => new MyEmpGroupModel(x))
        this.empGroup.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.empGroup.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  empGroupListFilter() {
    return this.empGroup.dataList.filter(x => x.groupId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()))
  }


  getEmployeeList() {
    this.employee.loading = true
    this.selectedItems.data.clear()
    this.employeeService.getList().subscribe({
      next: response => {
        this.employee.dataList = response.map(x => {
          this.selectedItems.data.set(x.employeeId, false)
          return new MyEmployeeModel(x)
        })
        this.employeeModal.dataList = response.filter(x => x.employeeId != this.decodeJWT(sessionStorage.getItem("accessToken") || '').employeeid).map((x: any) => new MyEmployeeModel(x))
        this.selectedItems.key = 'employeeId'
        this.selectedItems.count = 0
        this.employee.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.employee.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  employeeModalListFilter() {
    return this.employeeModal.dataList.filter(x => x.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
      x.fname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.lname.toLowerCase().includes(this.search.toLowerCase()) ||
      x.position.tdesc.toLowerCase().includes(this.search.toLowerCase()))
  }


  updateEmployeeList(type: 'add' | 'update' | 'delete') {
    this.employee.loading = true
    let body: any = this.employee.select
    if (type == 'delete') {
        if (this.numSelectItem() == 0) {
          this.showAlert('กรุณาเลือกข้อมูลที่จะลบ', 'error')
          return
        }
        const selectedKeys = Array.from(this.selectedItems.data.keys());
        body = this.employee.dataList.filter(x => selectedKeys.includes(x.employeeId) && this.selectedItems.data.get(x.employeeId)).map(x => new MyEmployeeModel(x))
    }
    this.employeeService[type](body).subscribe({
      next: response => {
        if (response.success) {
          if (body.employeeId == this.tokenService.getUserData().employeeId) {
            this.tokenService.saveUserData(new MyEmployeeModel(body))
          }
          this.showAlert(response.message, 'success')
          this.search = ""
          this.getEmployeeList()
        } else {
          this.showAlert(response.message, 'error')
          this.employee.loading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.employee.loading = false
        this.cdr.detectChanges()
      }
    })

  }
  selectEmployee(data?: EmployeeModel) {
    if (this.currentModal == 'update' && !data) {
      this.employee.select = { ...new MyEmployeeModel({ employeeId: this.employee.select.employeeId }), dateIso: '', dateEndIso: '2100-12-31' }
      this.employee.select.resignDate = '2100-12-31'
      this.employee.select.status = new MyStatusModel(this.empStatus.dataList[0])
    } else {
      this.employee.select = { ...new MyEmployeeModel(data || {}), dateIso: this.toISODate(data?.firstHireDate), dateEndIso: this.toISODate(data?.resignDate || '2100-12-31') }
      if (!this.employee.select.resignDate) {
        this.employee.select.resignDate = '2100-12-31'
      }
      if (!this.employee.select.status.statusCode) {
        this.employee.select.status = new MyStatusModel(this.empStatus.dataList[0])
      }
    }
    this.getBu1List()
    if (this.employee.select.bu1.bu1id) {
      this.getBu2List()
    }
    if (this.employee.select.bu2.bu2id) {
      this.getBu3List()
    }
    if (this.employee.select.bu3.bu3id) {
      this.getBu4List()
    }
    if (this.employee.select.bu4.bu4id) {
      this.getBu5List()
    }
    if (this.employee.select.bu5.bu5id) {
      this.getBu6List()
    }
    if (this.employee.select.bu6.bu6id) {
      this.getBu7List()
    }
  }
  selectBoss(data: any) {
    this.employee.select.boss = new MyBossModel({ ...data, empType: data.empType.codeId })
  }

  selectStatus() {
    this.employee.select.status = new MyStatusModel(this.empStatus.dataList.find(x => x.statusCode == this.employee.select.status.statusCode) || {})
  }
  changeDate(target: { [key: string]: any }, field: string, dateIso: string) {
    target[field] = this.toYYYYMMDD(dateIso)
  }
  toISODate(dateInput?: string | null): string {
    if (!dateInput) return "";
    const parsedDate = new Date(dateInput);
    return isNaN(parsedDate.getTime()) ? new Date().toISOString() : parsedDate.toISOString();
  }
  toYYYYMMDD(dateInput?: string | null): string {
    if (!dateInput) return "";
    const parsedDate = new Date(dateInput);
    const options: Intl.DateTimeFormatOptions = {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    };
    const formattedDate = parsedDate.toLocaleDateString('en-GB', options);
    const [day, month, year] = formattedDate.split('/');
    return `${year}-${month}-${day}`;
  }

  searchModalChange(dataList: any[]) {
    this.currentPage = 1
    this.page = Math.ceil(dataList.length / this.pageSize);
  }
 
  selectDataModal(target: { [key: string]: any }, field: string, data: any) {
    target[field] = JSON.parse(JSON.stringify(data))
  }

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


  checkEmployeeModel() {
    let disable = false
    if (!this.employee.select.employeeId ||
      !this.employee.select.fname ||
      !this.employee.select.lname ||
      !this.employee.select.empGroup.groupId ||
      !this.employee.select.firstHireDate ||
      !this.employee.select.resignDate ||
      !this.employee.select.bu1.bu1id ||
      !this.employee.select.bu2.bu2id ||
      !this.employee.select.bu3.bu3id ||
      !this.employee.select.bu4.bu4id ||
      !this.employee.select.bu5.bu5id ||
      !this.employee.select.position.positionId ||
      !this.employee.select.jobCode.jobcodeId ||
      !this.employee.select.branch.branchId ||
      !this.employee.select.empType.codeId ||
      !this.employee.select.personalLevel.plId
    ) {
      disable = true
    }
    return disable

  }

  decodeJWT(token: string) {
    let base64Url = token.split('.')[1];
    let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    let jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
    return JSON.parse(jsonPayload);
  }

  checkPrimary() {
    return this.employee.dataList.find(x => x.employeeId == this.employee.select.employeeId)
  }

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

  onSelectItemChange(arg: any) {
    this.selectedItems = arg
  }
  
  onImgSelected(event: any) {
    this.selectedImg = event.target.files.length > 0 ? event.target.files[0] : null;
    this.uploadImg()
  }
  uploadImg() {
    if (this.selectedImg) {
      this.imgLoading = true
      const formData = new FormData();
      formData.append('file', this.selectedImg);
      this.fileService.uploadImg(formData).subscribe({
        next: response => {
          if (response.success) {
            this.showAlert(response.message, 'success')
            this.employee.select.picture = response.resultObject
          } else {
            this.showAlert(response.message, 'error')
            this.employee.select.picture = ''
          }
          this.imgLoading = false
          this.cdr.detectChanges()
        }, error: error => {
          this.showAlert(error.message, 'error')
          this.employee.select.picture = ''
          this.imgLoading = false
          this.cdr.detectChanges()
        }
      })
    }
  }

  getImg(text: string) {
    return this.fileService.getImg(text)
  }

  onImageError(event: Event) {
    const imgElement = event.target as HTMLImageElement;
    imgElement.src = './assets/img/users/defaultperson.jpg';
  }
}
