import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { GroupAssessmentModel, MyGroupAssessmentModel } from 'src/app/shared/model/group-assessment.model';
import { GroupAssessment1ListModel, MyGroupAssessment1ListModel } from 'src/app/shared/model/group-assessment1-list.model';
import { MyJobcodeModel, JobcodeModel } from 'src/app/shared/model/jobcode.model';
import { GroupAssessmentService } from 'src/app/shared/services/group-assessment.service';
import { IndicatorsCoursesService } from 'src/app/shared/services/indicators-courses.service';
import { CompetencyIndicatorsCourses1MiniModel, MyCompetencyIndicatorsCourses1MiniModel } from 'src/app/shared/model/competency-indicators-courses1-mini.model';

@Component({
  selector: 'app-edit-group-competencies',
  templateUrl: './edit-group-competencies.component.html',
  styleUrls: ['./edit-group-competencies.component.scss']
})
export class EditGroupCompetenciesComponent {
  @Input() jobCode: JobcodeModel = new MyJobcodeModel()
  @Output() sendEdit: EventEmitter<boolean> = new EventEmitter<boolean>();
  groupCompetencies: GroupAssessmentModel = new MyGroupAssessmentModel()
  dataSelectList: GroupAssessment1ListModel[] = [];
  dataSelect: GroupAssessment1ListModel = new MyGroupAssessment1ListModel()
  dataList: { check: boolean, data: GroupAssessment1ListModel }[] = []
  dataListModal: { check: boolean, data: CompetencyIndicatorsCourses1MiniModel }[] = []

  search = ""
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  searchModal = ""
  currentPageModal = 1
  pageModal = Array.from({ length: 1 }, (_, i) => i + 1);
  dataLoading = false
  dataModalLoading = false

  groupAssessmentIndex = -1

  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false


  constructor(private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private groupAssessmentService: GroupAssessmentService,
    private indicatorsCoursesService: IndicatorsCoursesService
  ) { }

  ngOnInit() {
    this.getGroupAssessmentById()
    this.getIndicatorsCoursesList()
  }
  onEdit() {
    this.sendEdit.emit(false);
  }

  getGroupAssessmentById() {
    this.dataLoading = true;
    this.groupAssessmentService.getById(this.jobCode.jobCodeId).subscribe({
      next: response => {[[]]
        this.groupCompetencies = new MyGroupAssessmentModel({ ...response, jd: new MyJobcodeModel(this.jobCode) })
        this.dataList = new MyGroupAssessmentModel(response).groupAssessment1List.map(x => ({ check: false, data: new MyGroupAssessment1ListModel(x) }))
        this.dataList.sort((a, b) => {
          const topicA = a.data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.competencyTopic.competencyTopicId.toLowerCase();
          const topicB = b.data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.competencyTopic.competencyTopicId.toLowerCase();
          const expectationA = a.data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.expectation.toLowerCase();
          const expectationB = b.data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.expectation.toLowerCase();
          return topicA.localeCompare(topicB) || expectationA.localeCompare(expectationB);
        })
        this.dataLoading = false;
        this.searchChange();
        this.cdr.detectChanges();
      },
      error: error => {
        this.dataLoading = false;
        this.cdr.detectChanges();
      }
    });
  }

  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 data = x.data;
        const match =
          data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.competencyTopic.competencyTopicId.toLowerCase().includes(this.search.toLowerCase()) ||
          data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.competencyTopic.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
          data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.expectation.toLowerCase().includes(this.search.toLowerCase());
        return match;
      })
  }



  getIndicatorsCoursesList() {
    this.dataModalLoading = true
    this.indicatorsCoursesService.getList().subscribe({
      next: response => {
        this.dataListModal = response.map(x => ({ check: false, data: new MyCompetencyIndicatorsCourses1MiniModel(x) }));
        this.dataModalLoading = false;
        this.searchModalChange();
        this.cdr.detectChanges();
      },
      error: error => {
        this.dataModalLoading = false;
        this.cdr.detectChanges();
      }
    });
  }

  selectIndicatorsCourses(data: CompetencyIndicatorsCourses1MiniModel) {
    this.dataList.push({
      check: false, data: new MyGroupAssessment1ListModel({
        competencyIndicatorsCourses1Mini: new MyCompetencyIndicatorsCourses1MiniModel(data)
      })
    })
    this.dataList.sort((a, b) => {
      const topicA = a.data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.competencyTopic.competencyTopicId.toLowerCase();
      const topicB = b.data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.competencyTopic.competencyTopicId.toLowerCase();
      const expectationA = a.data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.expectation.toLowerCase();
      const expectationB = b.data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.expectation.toLowerCase();
      return topicA.localeCompare(topicB) || expectationA.localeCompare(expectationB);
    });
    this.isDataListCheckedAll = false
    this.searchChange()
    this.dataListCheckAll()
  }

  searchModalChange() {
    this.currentPageModal = 1;
    const filteredData = this.dataListModalFilter();
    this.pageModal = Array.from({ length: Math.ceil(filteredData.length / 10) }, (_, i) => i + 1);
  }

  dataListModalFilter() {
    return this.dataListModal.filter(x => {
      const data = x.data
      if (this.dataList.some(y => y.data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.competencyTopic.competencyTopicId == data.competencyIndicatorsCourses0.competencyTopic.competencyTopicId)) {
        return
      }
      const match = data.competencyIndicatorsCourses0.competencyTopic.competencyTopicId.toLowerCase().includes(this.searchModal.toLowerCase()) ||
        data.competencyIndicatorsCourses0.competencyTopic.tdesc.toLowerCase().includes(this.searchModal.toLowerCase()) ||
        data.competencyIndicatorsCourses0.expectation.toLowerCase().includes(this.searchModal.toLowerCase())
      return match;
    });
  }

  saveGroupAssessment1() {
    this.groupCompetencies.groupAssessment1List = this.dataList.map(x => new MyGroupAssessment1ListModel(x.data))
    this.groupAssessmentService.post(this.groupCompetencies).subscribe({
      next: (response) => {
        if (response.success) {
          this.showAlert(response.message, 'success');
        } else {
          this.showAlert(response.message, 'error');
        }
      },
      error: (error) => {
        this.showAlert(error.message, 'error');
      }
    });
  }

  deleteGroupAssessmentById() {
    if (this.groupAssessmentIndex == -1) {
      this.dataList = this.dataList.filter(item => !item.check);
      this.isDataListCheckedAll = false
      this.dataListCheckAll()
      this.cdr.detectChanges();
    } else {
      this.dataList = this.dataList.filter((_, index) => index !== this.groupAssessmentIndex);
      this.isDataListCheckedAll = false
      this.dataListCheckAll()
      this.cdr.detectChanges();
    }
  }
  showAlert(text: string, type: 'success' | 'error') {
    this.toastr[type](text, 'แจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    })
  }


  dataListCheckAll() {
    const selectAll = this.isDataListCheckedAll;
    this.dataList
      .filter(x => {
        const data = x.data;
        const match =
          data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.competencyTopic.competencyTopicId.toLowerCase().includes(this.search.toLowerCase()) ||
          data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
          data.competencyIndicatorsCourses1Mini.competencyIndicatorsCourses0.expectation.toLowerCase().includes(this.search.toLowerCase());
        return match;
      }).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)
  }
}
