import { ChangeDetectorRef, Component } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { Bu1Model, MyBu1Model } from 'src/app/shared/model/bu1.model';
import { Bu2Model, MyBu2Model } from 'src/app/shared/model/bu2.model';
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 { EmployeeModel, MyEmployeeModel } from 'src/app/shared/model/employee.model';
import { JobCodeModel, MyJobCodeModel } from 'src/app/shared/model/job-code.model';
import { MyPositionModel, PositionModel } from 'src/app/shared/model/position.model';
import { Bu1Service } from 'src/app/shared/services/bu1.service';
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 { EmployeeService } from 'src/app/shared/services/employee.service';
import { FileService } from 'src/app/shared/services/file.service';
import { JobCodeService } from 'src/app/shared/services/job-code.service';
import { PositionService } from 'src/app/shared/services/position.service';

@Component({
  selector: 'app-import-data',
  templateUrl: './import-data.component.html',
  styleUrls: ['./import-data.component.scss']
})
export class ImportDataComponent {
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  pageSize = 10
  search = ""
  jobCodeList: JobCodeModel[] = []
  loading = false

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

  selectJob: JobCodeModel = new MyJobCodeModel({})
  modalStatus = ''

  positionList:PositionModel[]=[]
  positionId=''

  bu1List: Bu1Model[] = []
  bu1Id = ''

  bu2List: Bu2Model[] = []
  bu2Id = ''

  bu3List: Bu3Model[] = []
  bu3Id = ''

  bu4List: Bu4Model[] = []
  bu4Id = ''

  bu5List: Bu5Model[] = []
  bu5Id = ''

  bu6List: Bu6Model[] = []
  bu6Id = ''

  bu7List: Bu7Model[] = []
  bu7Id = ''
  
  supervisorPositionId=''
  employeeList:EmployeeModel[]=[]
  checkJobCodeId=false
  constructor(
    private toastr: ToastrService,
    private fileService: FileService,
    private jobcodeService: JobCodeService,
    private cdr: ChangeDetectorRef,
    private positionService: PositionService,
    private bu1Service: Bu1Service,
    private bu2Service: Bu2Service,
    private bu3Service: Bu3Service,
    private bu4Service: Bu4Service,
    private bu5Service: Bu5Service,
    private bu6Service: Bu6Service,
    private bu7Service: Bu7Service,
    private employeeService:EmployeeService
  ) { }
  ngOnInit(): void {
    this.getListJob();

    this.getPositionList();
    this.getBu1List();
    this.getBu2List();
    this.getBu3List();
    this.getBu4List();
    this.getBu5List();
    this.getBu6List();
    this.getBu7List();
    // this.getEmployeeList();
  }
   getEmployeeList() {
      this.employeeService.getList().subscribe({
        next: response => {
          this.employeeList = response.map((x: any) => new MyEmployeeModel(x))
          this.cdr.detectChanges()
        }, error: error => {
          this.cdr.detectChanges()
        }
      })
    }

  
  getListJob() {
    this.loading = false
    this.jobcodeService.getList().subscribe({
      next: response => {
        this.jobCodeList = response.map((x: any) => new MyJobCodeModel(x))
        this.jobCodeList = this.jobCodeList.sort((a, b) => a.jobcodeId.localeCompare(b.jobcodeId))
        this.loading = false
        this.searchChange()
        this.cdr.detectChanges()
      }, error: error => {
        this.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  checkJodid(){
    let check = this.jobCodeList.some(x => x.jobcodeId == this.selectJob.jobcodeId)
    this.checkJobCodeId = check
    
  }
  edit(item: JobCodeModel) {
    this.selectJob = new MyJobCodeModel({})
    this.selectJob = new MyJobCodeModel(item)

    this.positionId = item.position.positionId
    this.supervisorPositionId = item.supervisorPosition.positionId
    this.bu1Id = item.bu1.bu1id
    this.bu2Id = item.bu2.bu2id
    this.bu3Id = item.bu3.bu3id
    this.bu4Id = item.bu4.bu4id
    this.bu5Id = item.bu5.bu5id
    this.bu6Id = item.bu6.bu6id
    this.bu7Id = item.bu7.bu7id
    console.log("🚀 ~ ImportDataComponent ~ edit ~ this.selectJob:", this.selectJob)
  }
  add(){
    this.selectJob = new MyJobCodeModel({})
    this.checkJobCodeId = false
    this.positionId = ''
    this.supervisorPositionId = ''
    this.bu1Id = ''
    this.bu2Id = ''
    this.bu3Id = ''
    this.bu4Id = ''
    this.bu5Id = ''
    this.bu6Id = ''
    this.bu7Id = ''
  }

  searchChange() {
    this.currentPage = 1
    this.page = Array.from({ length: Math.ceil(this.jobcodeFilter().length / this.pageSize) }, (_, i) => i + 1);
  }

  clearValue() {
    this.selectJob.jobObjective = ''

    this.selectJob.supervisorPosition = new MyPositionModel({})
    this.supervisorPositionId = ''

    this.selectJob.position = new MyPositionModel({})
    this.positionId = ''

    this.selectJob.bu1 = new MyBu1Model({})
    this.bu1Id = ''

    this.selectJob.bu2 = new MyBu2Model({})
    this.bu2Id = ''

    this.selectJob.bu3 = new MyBu3Model({})
    this.bu3Id = ''

    this.selectJob.bu4 = new MyBu4Model({})
    this.bu4Id = ''

    this.selectJob.bu5 = new MyBu5Model({})
    this.bu5Id = ''

    this.selectJob.bu6 = new MyBu6Model({})
    this.bu6Id = ''

    this.selectJob.bu7 = new MyBu7Model({})
    this.bu7Id = ''
  }
  save() {
    this.jobcodeService.post(this.selectJob).subscribe((response: any) => {
      if (response.success) {
        this.showAlert(response.message, 'success')
        this.selectJob = new MyJobCodeModel({})
        this.getListJob();
      } else {
        this.showAlert(response.message, 'error')
      }
      this.cdr.detectChanges()
    })
  }
  deleteJob() {
    this.jobcodeService.delete(this.selectJob).subscribe((response: any) => {
      if (response.success) {
        this.showAlert(response.message, 'success')
        this.selectJob = new MyJobCodeModel({})
        this.getListJob();
      } else {
        this.showAlert(response.message, 'error')
      }
      this.cdr.detectChanges()
    })
  }
  jobcodeFilter() {
    return this.jobCodeList.filter(x =>
      x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.search.toLowerCase()) ||
      x.jobcodeId.toLowerCase().includes(this.search.toLowerCase())
    )
  }
  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.loading = true
    this.fileService.uploadExcel(formData, 'MJOBCODE_GENERAL').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getListJob();
        } else {
          this.showAlert(response.message, 'error')
          this.loading = false
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.loading = false
      }
    })
  }


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

  showAlert(text: string, type: 'success' | 'error') {
    this.toastr[type](text, 'แจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    })
  }
  
  getPositionList() {
    this.positionService.getList().subscribe({
      next: response => {
        this.positionList = response.map(x => new MyPositionModel(x))
        this.cdr.detectChanges();
      }, error: error => {
        this.cdr.detectChanges()
    }
  })
  }
  changPosition() {
    let value = this.positionList.find(x => x.positionId == this.positionId);
    if (value) {
      this.selectJob.position = value
    }else{
      this.selectJob.position = new MyPositionModel({})
    }
  }
  changSupervisorPosition() {
    let value = this.positionList.find(x => x.positionId == this.supervisorPositionId);
    if (value) {
      this.selectJob.supervisorPosition = value
    }else{
      this.selectJob.supervisorPosition = new MyPositionModel({})
    }
  }

  getBu1List() {
    this.bu1Service.getList().subscribe({
      next: response => {
        this.bu1List = response.map(x => new MyBu1Model(x))
        this.cdr.detectChanges()
      }, error: error => {
        this.cdr.detectChanges()
      }
    })
  }
  changBu1() {
    let value = this.bu1List.find(x => x.bu1id == this.bu1Id);
    if (value) {
      this.selectJob.bu1 = value
    }else{
      this.selectJob.bu1 = new MyBu1Model({})
    }
  }

  getBu2List() {
    this.bu2Service.getList().subscribe({
      next: response => {
        this.bu2List = response.map(x => new MyBu2Model(x))
        this.cdr.detectChanges()
      }, error: error => {
        this.cdr.detectChanges()
      }
    })
  }
  changBu2() {
    let value = this.bu2List.find(x => x.bu2id == this.bu2Id);
    if (value) {
      this.selectJob.bu2 = value
    }else{
      this.selectJob.bu2 = new MyBu2Model({})
    }
  }

  getBu3List() {
    this.bu3Service.getList().subscribe({
      next: response => {
        this.bu3List = response.map(x => new MyBu3Model(x))
        this.cdr.detectChanges()
      }, error: error => {
        this.cdr.detectChanges()
      }
    })
  }
  changBu3() {
    let value = this.bu3List.find(x => x.bu3id == this.bu3Id);
    if (value) {
      this.selectJob.bu3 = value
    }else{
      this.selectJob.bu3 = new MyBu3Model({})
    }
  }

  getBu4List() {
    this.bu4Service.getList().subscribe({
      next: response => {
        this.bu4List = response.map(x => new MyBu4Model(x))
        this.cdr.detectChanges()
      }, error: error => {
        this.cdr.detectChanges()
      }
    })
  }
  changBu4() {
    let value = this.bu4List.find(x => x.bu4id == this.bu4Id);
    if (value) {
      this.selectJob.bu4 = value
    }else{
      this.selectJob.bu4 = new MyBu4Model({})
    }
  }
  getBu5List() {
    this.bu5Service.getList().subscribe({
      next: response => {
        this.bu5List = response.map(x => new MyBu5Model(x))
        this.cdr.detectChanges()
      }, error: error => {
        this.cdr.detectChanges()
      }
    })
  }
  changBu5() {
    let value = this.bu5List.find(x => x.bu5id == this.bu5Id);
    if (value) {
      this.selectJob.bu5 = value
    }else{
      this.selectJob.bu5 = new MyBu5Model({})
    }
  }

  getBu6List() {
    this.bu6Service.getList().subscribe({
      next: response => {
        this.bu6List = response.map(x => new MyBu6Model(x))
        this.cdr.detectChanges()
      }, error: error => {
        this.cdr.detectChanges()
      }
    })
  }
  changBu6() {
    let value = this.bu6List.find(x => x.bu6id == this.bu6Id);
    if (value) {
      this.selectJob.bu6 = value
    }else{
      this.selectJob.bu6 = new MyBu6Model({})
    }
  }
  getBu7List() {
    this.bu7Service.getList().subscribe({
      next: response => {
        this.bu7List = response.map(x => new MyBu7Model(x))
        this.cdr.detectChanges()
      }, error: error => {
        this.cdr.detectChanges()
      }
    })
  }
  changBu7() {
    let value = this.bu7List.find(x => x.bu7id == this.bu7Id);
    if (value) {
      this.selectJob.bu7 = value
    }else{
      this.selectJob.bu7 = new MyBu7Model({})
    }
  }
  closeModal() {
    const modal = document.getElementById("company-registration-page-alert-modal");
    if (modal) {
      modal.classList.add("hidden"); // ซ่อน Modal
    }
  }
}