import { ChangeDetectorRef, Component } from '@angular/core';
import { ColumnModel } from '@syncfusion/ej2-grids';
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, MyJlModel, MyJobCodeModel, MySupervisorJobCodeModel } from 'src/app/shared/model/job-code.model';
import { JobcodeModel, MyJobcodeModel } from 'src/app/shared/model/jobcode.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 { 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 { JobcodeService } from 'src/app/shared/services/jobcode.service';
import { PLService } from 'src/app/shared/services/pl.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 {
  search = ""
  jobCodeList: JobCodeModel[] = []
  loading = false

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

  selectJob: JobCodeModel = new MyJobCodeModel({})

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

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

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

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

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

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

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

  bu7List: Bu7Model[] = []
  bu7Id = ''

  jdList: JobcodeModel[] = []
  jd = ''

  employeeList: EmployeeModel[] = []
  checkJobCodeId = false

  jlList: PLModel[] = []
  jl = ''

  expectation: number | null = null

  currentModal: 'add' | 'edit' | 'delete' = "add"
  columns: ColumnModel[] = [{
    field: "jobcodeId",
    headerText: "JDCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "DescriptionJobTypeThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "DescriptionJobTypeEng",
    type: "string"
  }]
  searchSettings = {
    fields: ['jobcodeId', 'tdesc', 'edesc'],
    operator: 'contains',
    ignoreCase: false
  }
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  constructor(
    private toastr: ToastrService,
    private fileService: FileService,
    private jobCodeService: JobCodeService,
    private jobcodeService: JobcodeService,
    private pLService: PLService,
    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.getJlList();
    this.getJdList();
    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()
      }
    })
  }


  getJdList() {
    this.jobcodeService.getGroupAssessmentList().subscribe({
      next: response => {
        this.jdList = response.map(x => new MyJobcodeModel(x))
        this.cdr.detectChanges()
      }, error: error => {
        this.cdr.detectChanges()
      }
    })
  }
  getJlList() {
    this.pLService.getList().subscribe({
      next: response => {
        this.jlList = response.map(x => new MyPLModel(x))
        this.cdr.detectChanges()
      }, error: error => {
        this.cdr.detectChanges()
      }
    })
  }
  getListJob() {
    this.loading = false
    this.selectedItems.data.clear()
    this.jobCodeService.getList().subscribe({
      next: response => {
        this.jobCodeList = response.map((x: any) => {
          this.selectedItems.data.set(x.jobcodeId, false)
          return new MyJobCodeModel(x)
        })
        this.selectedItems.key = 'jobcodeId'
        this.selectedItems.count = 0
        this.loading = false
        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.jd = item.supervisorJobCode.jobCodeId
    this.jl = item.jl.plId
    this.expectation = item.expectation
    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
  }
  add() {
    this.selectJob = new MyJobCodeModel({})
    this.checkJobCodeId = false
    this.positionId = ''
    this.jd = ''
    this.jl = ''
    this.expectation = null
    this.bu1Id = ''
    this.bu2Id = ''
    this.bu3Id = ''
    this.bu4Id = ''
    this.bu5Id = ''
    this.bu6Id = ''
    this.bu7Id = ''
  }


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

    this.selectJob.supervisorJobCode = new MySupervisorJobCodeModel({})
    this.jd = ''

    this.selectJob.jl = new MyJlModel({})
    this.jl = ''

    this.selectJob.expectation = null
    this.expectation = null

    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.search = ''
        this.getListJob();
      } else {
        this.showAlert(response.message, 'error')
      }
      this.cdr.detectChanges()
    })
  }
  deleteJob() {
    const selectedKeys = Array.from(this.selectedItems.data.keys());
    const body = this.jobCodeList.filter(x => selectedKeys.includes(x.jobcodeId) && this.selectedItems.data.get(x.jobcodeId)).map(x => new MyJobCodeModel(x))
    this.jobCodeService.delete(body).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()
    })
  }

  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({})
    }
  }
  changSupervisorJobCode() {
    let value = this.jdList.find(x => x.jobCodeId == this.jd);
    if (value) {
      this.selectJob.supervisorJobCode = value
    } else {
      this.selectJob.supervisorJobCode = new MySupervisorJobCodeModel()
    }
  }
  changJl() {
    let value = this.jlList.find(x => x.plId == this.jl);
    if (value) {
      this.selectJob.jl = value
    } else {
      this.selectJob.jl = new MyJlModel()
    }
  }
  changExpectation() {
    this.selectJob.expectation = this.expectation
  }

  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
    }
  }
  checkPrimary() {
    return this.jobCodeList.find(x => x.jobcodeId == this.selectJob.jobcodeId)
  }

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

  onSelectItemChange(arg: any) {
    this.selectedItems = arg
  }
}
