import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { CompetencyGradeModel } 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-grade-management',
  templateUrl: './grade-management.component.html',
  styleUrls: ['./grade-management.component.scss'],
})
export class GradeManagementComponent {
  @Output() sendPathTitle: EventEmitter<string[]> = new EventEmitter<string[]>();
  typeTab: "" | "add" | "edit" = "";
  currentPage = 1;
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false
  search = '';

  dataList: DataModel[] = [];
  dataLoading = false
  dataSelect: DataModel = { check: false, code: '', tdesc: '', edesc: '', competencyGrades: [], companyId: '' }

  constructor(private toastr: ToastrService,
    private competencyGroupGradeService: CompetencyGroupGradeService,
    private cdr: ChangeDetectorRef) {
    this.sendPathTitle.emit(['CompetencySystem', 'menu.Grade', 'GradeManage'])
  }
  ngOnInit(): void {
    this.getCompetencyGroupGradeList()
  }
  selectData(data?: DataModel) {
    this.dataSelect = JSON.parse(JSON.stringify(data || { check: false, code: '', tdesc: '', edesc: '', competencyGrades: [], companyId: '' }))
  }
  getCompetencyGroupGradeList() {
    this.dataLoading = true
    this.competencyGroupGradeService.getList().subscribe({
      next: response => {
        this.dataList = response.map(x => ({ check: false, code: x.groupGradeId, tdesc: x.tdesc, edesc: x.edesc, competencyGrades: x.competencyGrades, companyId: x.companyId }))
        this.isDataListCheckedAll = false
        this.dataListCheckAll()
        this.searchChange()
        this.dataLoading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.dataLoading = false
        this.cdr.detectChanges()
      }
    })
  }
  pathTitleChange(tap?: 'add' | 'edit') {
    this.typeTab = tap || ''
    switch (this.typeTab) {
      case 'add': {
        this.sendPathTitle.emit(['CompetencySystem', 'menu.Grade', 'GradeManage', 'เพิ่มกลุ่มเกรด'])
        break;
      }
      case 'edit': {
        this.sendPathTitle.emit(['CompetencySystem', 'menu.Grade', 'GradeManage', 'แก้ไขกลุ่มเกรด'])
        break;
      }
      default: {
        this.sendPathTitle.emit(['CompetencySystem', 'menu.Grade', 'GradeManage'])
      }
    }
  }

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

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

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

  deleteCompetencyGroupGradeList() {
    const body = this.dataSelect.code ? new MyCompetencyGroupGradeModel({ groupGradeId: this.dataSelect.code, tdesc: this.dataSelect.tdesc, edesc: this.dataSelect.edesc, companyId: this.dataSelect.companyId }) : this.dataList.filter(x => x.check).map(x => new MyCompetencyGroupGradeModel({ groupGradeId: x.code, tdesc: x.tdesc, edesc: x.edesc }))
    this.dataLoading = true
    this.competencyGroupGradeService.delete(body).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getCompetencyGroupGradeList()
        } else {
          this.showAlert(response.message, 'error')
          this.dataLoading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.dataLoading = false
        this.cdr.detectChanges()
      }
    })
  }

  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.dataList.filter(x => x.check).length;
    this.isDataListChecked = Boolean(this.numDataListChecked)
  }
}
