import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { MyCompetencytopicModel } from 'src/app/shared/model/competencytopic.model';
import { MyCompetencytypeModel } from 'src/app/shared/model/competencytype.model';
import { CompetencytopicService } from 'src/app/shared/services/competencytopic.service';
import { CompetencytypeService } from 'src/app/shared/services/competencytype.service';
import { FileService } from 'src/app/shared/services/file.service';
export interface DataModel {
  id: string
  name: string
  edesc: string
  code: string
  definition: string
  type: DataModel2
  file: string
  checked: boolean
}
export interface DataModel2 {
  id: string
  name: string
  edesc: string
  code: string
  level: string
}
@Component({
  selector: 'app-competency-topic',
  templateUrl: './competency-topic.component.html',
  styleUrls: ['./competency-topic.component.scss']
})
export class CompetencyTopic {
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  search = ""

  currentPageModal = 1
  pageModal = Array.from({ length: 1 }, (_, i) => i + 1);
  searchModal = ""

  isChecked: boolean = false; // ใช้สำหรับตรวจสอบสถานะของ checkbox
  currentModal = "";
  dataLoading = false
  dataSelectList: DataModel[] = [];
  dataSelect: DataModel = { id: "", name: "", edesc: "", code: "", definition: "", file: "", type: { id: "", name: "", edesc: "", code: "", level: "" }, checked: false }
  competencytypeListLoading = false
  competencytypeList: DataModel2[] = []
  competoncyTopicList: { check: boolean; data: DataModel & { checked?: boolean } }[] = []
  modalStatus = 'add'
  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';
  examFile: File | null = null;
  examFileName: string = 'กรุณาเลือกไฟล์';
  selectedItems: string[] = [];


  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false
  constructor(private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private competencytopicService: CompetencytopicService,
    private competencytypeService: CompetencytypeService
  ) { }
  ngOnInit(): void {
    this.getCompetencytopicList()
    this.getCompetencytypeList()
  }



  onExamSelected(event: any) {
    this.examFile = event.target.files.length > 0 ? event.target.files[0] : null;
    this.examFileName = this.examFile?.name || "กรุณาเลือกไฟล์"
  }
  uploadExam() {
    if (!this.examFile) {
      return
    }
    const formData = new FormData();
    formData.append('file', this.examFile);
    this.fileService.uploadFiles(formData).subscribe({
      next: response => {
        if (response.success) {
          this.examFile = null
          this.addCompetency_topic(response.resultObject)
        } else {
          this.showAlert(response.message, 'error')
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.cdr.detectChanges()
      }
    })
  }
  dowloadExam(fileName: string) {
    this.fileService.dowloadFiles(fileName).subscribe({
      next: response => {
        const url = window.URL.createObjectURL(response);
        const a = document.createElement("a");
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        this.cdr.detectChanges()
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.cdr.detectChanges()
      }
    })
  }

  onFileSelected(event: any) {
    this.selectedFile = event.target.files.length > 0 ? event.target.files[0] : null;
    this.selectedFileName = this.selectedFile?.name || "กรุณาเลือกไฟล์"
  }

  uploadFile() {
    if (!this.selectedFile) {
      alert('กรุณาเลือกไฟล์ก่อนอัปโหลด')
      return
    }
    const formData = new FormData();
    formData.append('file', this.selectedFile);
    this.dataLoading = true
    this.fileService.uploadExcel(formData, 'competency_topic').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getCompetencytypeList()
          this.getCompetencytopicList()
        } 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()
      }
    })
  }

  downloadFile() {
    const fileName = 'IMPORT_COMPETENCY_TOPIC.xlsx'
    this.fileService.downloadTemplate(fileName).subscribe({
      next: response => {
        const url = window.URL.createObjectURL(response);
        const a = document.createElement("a");
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      }, error: error => {
        this.showAlert(error.message, 'error')
      }
    })

  }

  getCompetencytypeList() {
    this.competencytypeListLoading = true
    this.competencytypeService.getList().subscribe({
      next: response => {
        this.competencytypeList = response.map(x => ({ id: x.competencyTypeId, name: x.tdesc, edesc: x.edesc, code: x.shortName, level: x.expectationLevel, checked: false }))
        this.competencytypeListLoading = false
        this.searchChange()
        this.cdr.detectChanges()
      }, error: error => {
        this.competencytypeListLoading = false
        this.cdr.detectChanges()
      }
    })
  }
  searchCompetencytypeChange() {
    this.currentPageModal = 1
    this.pageModal = Array.from({ length: Math.ceil(this.competencytypeListFilter().length / 10) }, (_, i) => i + 1);
  }
  competencytypeListFilter() {
    return this.competencytypeList.filter(x => {
      const data = x
      const match = data.id.toLowerCase().includes(this.searchModal) || data.name.toLowerCase().includes(this.searchModal) || data.code.toLowerCase().includes(this.searchModal);
      return match;
    });
  }
  selectCompetencytype(data: DataModel2) {
    this.dataSelect.type = JSON.parse(JSON.stringify(data));
  }
  getCompetencytopicList() {
    this.dataLoading = true
    this.competencytopicService.getList().subscribe({
      next: response => {
        this.competoncyTopicList = response.map(x => ({
          check: false, data: {
            id: x.competencyTopicId, name: x.tdesc, edesc: x.edesc, code: x.competencyType.shortName, definition: x.competencyDetail, file: x.competencyFiles,
            type: { id: x.competencyType.competencyTypeId, name: x.competencyType.tdesc, edesc: x.competencyType.edesc, code: x.competencyType.shortName, level: x.expectationLevel },
            checked: false
          }
        }))
        this.isDataListCheckedAll = false
        this.dataListCheckAll()
        this.dataLoading = false
        this.searchChange()
        this.cdr.detectChanges()
      }, error: error => {
        this.dataLoading = false
        this.cdr.detectChanges()
      }
    })
  }
  searchChange() {
    this.currentPage = 1
    this.page = Array.from({ length: Math.ceil(this.dataListFilter().length / 10) }, (_, i) => i + 1);
    this.dataListCheck()
  }
  dataListFilter() {
    return this.competoncyTopicList.filter(x => {
      const data = x.data
      const match = data.id?.toLowerCase().includes(this.search.toLowerCase()) || data.name?.toLowerCase().includes(this.search.toLowerCase()) || data.code?.toLowerCase().includes(this.search.toLowerCase());
      return match;
    });
  }
  setData(data?: DataModel) {
    this.examFileName = data?.file || 'กรุณาเลือกไฟล์'
    this.dataSelect = JSON.parse(JSON.stringify(data || { id: "", name: "", edesc: "", code: "", definition: "", file: "", type: { id: "", name: "", edesc: "", code: "", level: "" }, checked: false }));
  }

  addCompetency_topic(competencyFiles?: string) {
    if (this.examFile) {
      this.uploadExam()
    } else {
      const body = new MyCompetencytopicModel({
        competencyTopicId: this.dataSelect.id, tdesc: this.dataSelect.name, edesc: this.dataSelect.edesc, competencyDetail: this.dataSelect.definition,
        competencyType: new MyCompetencytypeModel({ competencyTypeId: this.dataSelect.type.id, tdesc: this.dataSelect.type.name, edesc: this.dataSelect.type.edesc, shortName: this.dataSelect.type.code, expectationLevel: this.dataSelect.type.level }),
        competencyFiles: competencyFiles || ((this.examFileName == this.dataSelect.file) ? this.dataSelect.file : '')
      })
      this.dataLoading = true
      this.competencytopicService.post(body).subscribe({
        next: response => {
          if (response.success) {
            this.showAlert(response.message, 'success')
            this.getCompetencytypeList()
            this.getCompetencytopicList()
          } 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()
        }
      })
    }
  }
  deleteCompetency_topic() {
    let body: any
    if (this.modalStatus == "deleteGroup") {
      body = this.competoncyTopicList.filter(x => x.check).map(x => new MyCompetencytopicModel({
        competencyTopicId: x.data.id, tdesc: x.data.name, edesc: x.data.edesc, competencyDetail: x.data.definition,
        competencyType: new MyCompetencytypeModel({ competencyTypeId: x.data.type.id, tdesc: x.data.type.name, edesc: x.data.type.edesc, shortName: x.data.type.code, expectationLevel: x.data.type.level }),
      }))
    } else {
      body = new MyCompetencytopicModel({
        competencyTopicId: this.dataSelect.id, tdesc: this.dataSelect.name, edesc: this.dataSelect.edesc, competencyDetail: this.dataSelect.definition,
        competencyType: new MyCompetencytypeModel({ competencyTypeId: this.dataSelect.type.id, tdesc: this.dataSelect.type.name, edesc: this.dataSelect.type.edesc, shortName: this.dataSelect.type.code, expectationLevel: this.dataSelect.type.level }),
      })
    }
    this.dataLoading = true
    this.competencytopicService.delete(body).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getCompetencytypeList()
          this.getCompetencytopicList()
          this.dataLoading = false
        } 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()
      }
    })
  }

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

  clearData(modalStatus: string) {
    if (modalStatus == 'add') {
      this.setData()
    } else if (modalStatus == 'edit') {
      this.setData({ id: this.dataSelect.id, name: "", edesc: "", code: "", definition: "", file: "", type: { id: "", name: "", edesc: "", code: "", level: "" }, checked: this.dataSelect.checked })
    }
  }

  dataListCheckAll() {
    const selectAll = this.isDataListCheckedAll;
    this.competoncyTopicList.filter(x => {
      const data = x.data
      const match = data.id.toLowerCase().includes(this.search.toLowerCase()) || data.name.toLowerCase().includes(this.search.toLowerCase()) || data.code.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.competoncyTopicList.filter(x => x.check).length;
    this.isDataListChecked = Boolean(this.numDataListChecked)
  }
}