import { ChangeDetectorRef, Component, EventEmitter, Input, Output, SimpleChanges } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { CompetencyGradeModel, MyCompetencyGradeModel } from 'src/app/shared/model/competency-grades.model';
import { MyCompetencyGroupGradeModel } from 'src/app/shared/model/competency-group-grade.model';
import { CompetencyGroupGradeService } from 'src/app/shared/services/competency-group-grade.service';

export interface DataModel {
  check: boolean
  code: string
  tdesc: string
  edesc: string
  competencyGrades: CompetencyGradeModel[]
  companyId: string
}

@Component({
  selector: 'app-sub-grade-registration',
  templateUrl: './sub-grade-registration.component.html',
  styleUrls: ['./sub-grade-registration.component.scss'],
})
export class SubGradeRegistrationComponent {
  @Input() dataSelect: DataModel = { check: false, code: '', tdesc: '', edesc: '', competencyGrades: [], companyId: '' }
  @Output() sendDataSelect: EventEmitter<DataModel> = new EventEmitter<DataModel>();
  competencyGrade: { select: CompetencyGradeModel, dataList: { check: boolean, data: CompetencyGradeModel }[] } = { select: new MyCompetencyGradeModel({}), dataList: [] }
  currentPage = 1;
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false
  search = '';
  modalStatus: 'add' | 'edit' | 'delete' | 'deleteGroup' = 'add'
  constructor(private toastr: ToastrService,
    private cdr: ChangeDetectorRef
  ) {
  }
  ngOnInit(): void {
    this.competencyGrade.dataList = this.dataSelect.competencyGrades.map(x => ({ check: false, data: x }))
    this.searchChange()
  }
  ngOnChanges(changes: SimpleChanges): void {
    if (changes) {
      this.competencyGrade.dataList = changes['dataSelect'].currentValue.competencyGrades.map((x: CompetencyGradeModel) => ({ check: false, data: x }))
      this.isDataListCheckedAll = false
      this.dataListCheckAll()
      this.searchChange()
    }

  }
  searchChange() {
    this.currentPage = 1;
    const filteredData = this.dataListFilter();
    this.page = Array.from({ length: Math.ceil(filteredData.length / 10) }, (_, i) => i + 1);
    this.dataListCheck();
  }

  selectData(data?: { check: boolean, data: CompetencyGradeModel }) {
    this.competencyGrade.select = new MyCompetencyGradeModel(data?.data || {})
  }

  dataListFilter() {
    return this.competencyGrade.dataList.filter((x) => {
      const data = x.data
      const match = data.gradeId.toLowerCase().includes(this.search.toLowerCase()) || data.tdesc.toLowerCase().includes(this.search.toLowerCase()) || data.edesc.toLowerCase().includes(this.search.toLowerCase());
      return match;
    });
  }

  dataListCheckAll() {
    const selectAll = this.isDataListCheckedAll;
    this.dataListFilter().forEach(x => x.check = selectAll);
    this.dataListCheck();
  }

  dataListCheck() {
    const dataCheck = this.dataListFilter();
    this.isDataListCheckedAll = dataCheck.length ? dataCheck.every(x => x.check) : false;
    this.numDataListChecked = this.competencyGrade.dataList.filter(x => x.check).length;
    this.isDataListChecked = Boolean(this.numDataListChecked)
  }
  updateCompetencyGroupGrade() {
    switch (this.modalStatus) {
      case 'add': {
        this.competencyGrade.dataList.push({ check: false, data: this.competencyGrade.select })
        this.cdr.detectChanges()
        break
      }
      case 'edit': {
        this.competencyGrade.dataList = this.competencyGrade.dataList.map(x => x.data.gradeId == this.competencyGrade.select.gradeId ? { check: false, data: this.competencyGrade.select } : x)
        this.cdr.detectChanges()
        break
      }
      case 'delete': {
        this.competencyGrade.dataList = this.competencyGrade.dataList.filter(x => this.competencyGrade.select.gradeId != x.data.gradeId)
        this.cdr.detectChanges()
        break
      }
      case 'deleteGroup': {
        this.competencyGrade.dataList = this.competencyGrade.dataList.filter(x => !x.check)
        this.cdr.detectChanges()
        break
      }
    }
    this.sendDataSelect.emit({ ...this.dataSelect, competencyGrades: this.competencyGrade.dataList.map(x => ({ ...x.data, weight: +(x.data.weight || '0'), gradeMinScore: +(x.data.gradeMinScore || '0'), gradeMaxScore: +(x.data.gradeMaxScore || '0') })) })
  }
  showAlert(text: string, type: 'success' | 'error') {
    this.toastr[type](text, 'แจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    });
  }

  clear() {
    if (this.modalStatus == 'add') {
      this.competencyGrade.select = new MyCompetencyGradeModel({})
    } else if (this.modalStatus == 'edit') {
      this.competencyGrade.select = new MyCompetencyGradeModel({ gradeId: this.competencyGrade.select.gradeId })
    }
  }

  checkNumberEmpty(data: any) {
    if (typeof (data) == 'number') {
      if (data == 0) {
        return false
      }
    } else {
      if (data == null || data == undefined || data == "") {
        return true
      }
    }
    return false
  }
}
