import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { MyJobcodeModel, JobcodeModel } from 'src/app/shared/model/jobcode.model';
import { MyPLModel } from 'src/app/shared/model/pl.model';
import { MyPmsGroupAssessmentModel, PmsGroupAssessmentModel } from 'src/app/shared/model/pms-group-assessment.model';
import { MyPmsGroupAssessment1Model, PmsGroupAssessment1Model } from 'src/app/shared/model/pms-group-assessment1.model';
import { MyPmstopicModel, PmstopicModel } from 'src/app/shared/model/pmstopic.model';
import { PmsGroupAssessmentService } from 'src/app/shared/services/pms-group-assessment.service';
import { PmstopicService } from 'src/app/shared/services/pmstopic.service';
export interface DataModal {
  search: string,
  currentPage: number,
  page: number[]
}
@Component({
  selector: 'app-edit-evaluation-grouping',
  templateUrl: './edit-evaluation-grouping.component.html',
  styleUrls: ['./edit-evaluation-grouping.component.scss']
})
export class EditEvaluationGroupingComponent {
  @Output() sendOnEdit: EventEmitter<boolean> = new EventEmitter<boolean>();
  @Input() pl: JobcodeModel = new MyJobcodeModel()
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  search = ""
  currentModal: 'save' | 'delete' | 'deleteGroup' = "save"
  modal: DataModal = {
    search: "",
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1)
  }

  pmsGroupAssessment: { loading: boolean, select: PmsGroupAssessment1Model, data: PmsGroupAssessmentModel, dataList: { check: boolean, data: PmsGroupAssessment1Model }[] } = {
    loading: false,
    select: new MyPmsGroupAssessment1Model(),
    data: new MyPmsGroupAssessmentModel(), dataList: []
  }
  pmsGroupAssessmentIndex = -1
  pmstopic: { loading: boolean, select: PmstopicModel, dataList: { check: boolean, data: PmstopicModel }[] } = { loading: false, select: new MyPmstopicModel(), dataList: [] }

  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false
  constructor(private toastr: ToastrService,
    private pmsGroupAssessmentService: PmsGroupAssessmentService,
    private cdr: ChangeDetectorRef,
    private pmstopicService: PmstopicService
  ) { }
  ngOnInit(): void {
    this.getPmsGroupAssessmentBy_plId()
    this.getPmstopicList()
  }
  getPmstopicList() {
    this.pmstopic.loading = true
    this.pmstopicService.getList().subscribe({
      next: response => {
        this.pmstopic.dataList = response.map(x => ({ check: false, data: new MyPmstopicModel(x) }))
        this.isDataListCheckedAll = false
        this.dataListCheckAll()
        this.pmstopic.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.pmstopic.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  pmstopicListFilter() {
    return this.pmstopic.dataList.filter(x => {
      const data = x.data
      if (this.pmsGroupAssessment.dataList.some(y => y.data.pmsTopic.pmsTopicId == data.pmsTopicId)) {
        return
      }
      const match = data.pmsTopicId.toLowerCase().includes(this.modal.search.toLowerCase()) ||
        data.tdesc.toLowerCase().includes(this.modal.search.toLowerCase()) ||
        data.pmsType.tdesc.toLowerCase().includes(this.modal.search.toLowerCase()) ||
        (data.weight + "").toLowerCase().includes(this.modal.search.toLowerCase())
      return match
    })
  }
  selectPmstopic(data?: PmstopicModel) {
    this.pmsGroupAssessment.dataList.push({ check: false, data: new MyPmsGroupAssessment1Model({ pmsTopic: new MyPmstopicModel(data) }) })
    this.pmsGroupAssessment.dataList.sort((a, b) => a.data.pmsTopic.pmsTopicId.localeCompare(b.data.pmsTopic.pmsTopicId))
    this.isDataListCheckedAll = false
    this.dataListCheckAll()
    this.cdr.markForCheck()
  }

  getPmsGroupAssessmentBy_plId() {
    this.pmsGroupAssessment.loading = true
    this.pmsGroupAssessmentService.getBy_plId(this.pl.jobCodeId).subscribe({
      next: response => {
        this.pmsGroupAssessment.data = response
        this.pmsGroupAssessment.dataList = response.pmsGroupAssessment1List.map(x => ({ check: false, data: new MyPmsGroupAssessment1Model(x) }))
        this.pmsGroupAssessment.dataList.sort((a, b) => a.data.pmsTopic.pmsTopicId.localeCompare(b.data.pmsTopic.pmsTopicId))
        this.pmsGroupAssessment.loading = false
        this.isDataListCheckedAll = false
        this.dataListCheckAll()
        this.searchChange();
        this.cdr.detectChanges();
      }, error: error => {
        this.pmsGroupAssessment.loading = false
        this.cdr.detectChanges()
      }
    });
  }
  pmsGroupAssessmentListFilter() {
    return this.pmsGroupAssessment.dataList.filter(x => {
      const data = x.data
      const match = data.pmsTopic.pmsTopicId.toLowerCase().includes(this.search.toLowerCase()) ||
        data.pmsTopic.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
        data.pmsTopic.pmsType.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
        (data.pmsTopic.weight + "").toLowerCase().includes(this.search.toLowerCase())
      return match;
    });
  }
  selectPmsGroupAssessment(data: PmsGroupAssessment1Model) {
    this.pmsGroupAssessment.select = new MyPmsGroupAssessment1Model(data)
  }

  searchModalChange(dataList: any[]) {
    this.modal.currentPage = 1
    this.modal.page = Array.from({ length: Math.ceil(dataList.length / 10) }, (_, i) => i + 1);
    this.cdr.markForCheck()
  }
  searchChange() {
    this.currentPage = 1
    this.page = Array.from({ length: Math.ceil(this.pmsGroupAssessmentListFilter().length / 10) }, (_, i) => i + 1)
    this.dataListCheck();
    this.cdr.detectChanges()
  }
  dataListCheckAll() {
    const selectAll = this.isDataListCheckedAll;
    this.pmsGroupAssessmentListFilter().forEach(x => x.check = selectAll);
    this.dataListCheck();
  }
  dataListCheck() {
    const dataCheck = this.pmsGroupAssessmentListFilter();
    this.isDataListCheckedAll = dataCheck.length ? dataCheck.every(x => x.check) : false;
    this.numDataListChecked = this.pmsGroupAssessment.dataList.filter(x => x.check).length
    this.isDataListChecked = Boolean(this.numDataListChecked)
  }

  savePmsGroupAssessment() {
    const body = {
      personalLevel: new MyPLModel(),
      jd: new MyJobcodeModel(this.pl),
      companyId: "",
      jlId: this.pmsGroupAssessment.data.jlId,
      pmsGroupAssessment1List: this.pmsGroupAssessment.dataList.map(x => new MyPmsGroupAssessment1Model(x.data))
    }
    this.pmsGroupAssessmentService.post(body).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
        } else {
          this.showAlert(response.message, 'error')
        }
        this.cdr.detectChanges()
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.cdr.detectChanges()
      }
    })
  }
  deletePmsGroupAssessment() {
    switch (this.currentModal) {
      case ('delete'): {
        this.pmsGroupAssessment.dataList = this.pmsGroupAssessment.dataList.filter((_, i) => i != this.pmsGroupAssessmentIndex)
        break;
      }
      case ('deleteGroup'): {
        this.pmsGroupAssessment.dataList = this.pmsGroupAssessment.dataList.filter((x) => !x.check)
        break;
      }
    }
    this.pmsGroupAssessment.dataList.sort((a, b) => a.data.pmsTopic.pmsTopicId.localeCompare(b.data.pmsTopic.pmsTopicId))
    this.isDataListCheckedAll = false
    this.dataListCheckAll()
    this.cdr.markForCheck()
  }

  showAlert(text: string, type: 'success' | 'error') {
    this.toastr[type](text, 'แจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    })
  }

  onBack() {
    this.sendOnEdit.emit(false);
  }

}
