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';

export interface DataModel {
  check: boolean;
  code: string;
  tdesc: string;
  edesc: string;
  pmsGrade: CompetencyGradeModel[]
}

@Component({
  selector: 'app-pms-sub-grade-registration',
  templateUrl: './pms-sub-grade-registration.component.html',
  styleUrls: ['./pms-sub-grade-registration.component.scss'],
})
export class PmsSubGradeRegistrationComponent {
  @Input() dataSelect: DataModel = { check: false, code: '', tdesc: '', edesc: '', pmsGrade: [] }
  @Output() sendDataSelect: EventEmitter<DataModel> = new EventEmitter<DataModel>();
  pmsGrade: { 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.pmsGrade.dataList = this.dataSelect.pmsGrade.map(x => ({ check: false, data: x }))
    this.searchChange()
  }
  ngOnChanges(changes: SimpleChanges): void {
    if (changes) {
      this.pmsGrade.dataList = changes['dataSelect'].currentValue.pmsGrade.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.pmsGrade.select = new MyCompetencyGradeModel(data?.data || {})
  }

  dataListFilter() {
    return this.pmsGrade.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.pmsGrade.dataList.filter(x => x.check).length;
    this.isDataListChecked = Boolean(this.numDataListChecked)
  }
  updatePmsGroupGrade() {
    switch (this.modalStatus) {
      case 'add': {
        this.pmsGrade.dataList.push({ check: false, data: this.pmsGrade.select })
        this.cdr.detectChanges()
        break
      }
      case 'edit': {
        this.pmsGrade.dataList = this.pmsGrade.dataList.map(x => x.data.gradeId == this.pmsGrade.select.gradeId ? { check: false, data: this.pmsGrade.select } : x)
        this.cdr.detectChanges()
        break
      }
      case 'delete': {
        this.pmsGrade.dataList = this.pmsGrade.dataList.filter(x => this.pmsGrade.select.gradeId != x.data.gradeId)
        this.cdr.detectChanges()
        break
      }
      case 'deleteGroup': {
        this.pmsGrade.dataList = this.pmsGrade.dataList.filter(x => !x.check)
        this.cdr.detectChanges()
        break
      }
    }
    this.sendDataSelect.emit({ ...this.dataSelect, pmsGrade: this.pmsGrade.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.pmsGrade.select = new MyCompetencyGradeModel({})
    } else if (this.modalStatus == 'edit') {
      this.pmsGrade.select = new MyCompetencyGradeModel({ gradeId: this.pmsGrade.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
  }
}
