import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { PmstopicModel, MyPmstopicModel } from 'src/app/shared/model/pmstopic.model';
import { MyPmstypeModel, PmstypeModel } from 'src/app/shared/model/pmstype.model';
import { FileService } from 'src/app/shared/services/file.service';
import { PmstopicService } from 'src/app/shared/services/pmstopic.service';
import { PmstypeService } from 'src/app/shared/services/pmstype.service';
interface table {
  currentPage: number,
  page: number[],
  search: string
}
@Component({
  selector: 'app-assessment-topics',
  templateUrl: './assessment-topics.component.html',
  styleUrls: ['./assessment-topics.component.scss']
})
export class AssessmentTopicsComponent {
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  search = ""
  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false
  pmstopic: { loading: boolean, select: PmstopicModel, dataList: { check: boolean, data: PmstopicModel }[] } = { loading: false, select: new MyPmstopicModel(), dataList: [] }
  pmstype: { loading: boolean, select: PmstypeModel, dataList: { check: boolean, data: PmstypeModel }[] } = { loading: false, select: new MyPmstypeModel(), dataList: [] }
  modal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: ""
  }
  modalStatus: "add" | "edit" | 'delete' | 'deleteGroup' = "add"

  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';
  constructor(private cdr: ChangeDetectorRef,
    private pmstopicService: PmstopicService,
    private toastr: ToastrService,
    private fileService: FileService,
    private pmstypeService: PmstypeService
  ) {
  }

  ngOnInit(): void {
    this.getPmstopicList()
    this.getPmstypeList()
  }
  getPmstypeList() {
    this.pmstype.loading = true
    this.pmstypeService.getList().subscribe({
      next: response => {
        this.pmstype.dataList = response.map(x => ({ check: false, data: new MyPmstypeModel(x) }))
        this.isDataListCheckedAll = false
        this.dataListCheckAll()
        this.pmstype.loading = false
        this.searchChange()
        this.cdr.detectChanges()
      }, error: error => {
        this.pmstype.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  pmstypeListFilter() {
    return this.pmstype.dataList.filter(x => {
      const data = x.data
      if (x.data.pmsTypeId != '06' && x.data.pmsTypeId != '07') {
        const match = data.pmsTypeId.toLowerCase().includes(this.modal.search.toLowerCase()) ||
          data.tdesc.toLowerCase().includes(this.modal.search.toLowerCase()) ||
          data.shortName.toLowerCase().includes(this.modal.search.toLowerCase())
        return match
      }
      return
    })
  }
  selectPmstype(data?: PmstypeModel) {
    this.pmstopic.select.pmsType = new MyPmstypeModel(data)
  }
  getPmstopicList() {
    this.pmstopic.loading = true
    this.pmstopicService.getList().subscribe({
      next: response => {
        this.pmstopic.dataList = response.map(x => ({ check: false, data: new MyPmstopicModel(x) }))
        this.isDataListCheckedAll = false
        this.dataListCheckAll()
        this.pmstopic.loading = false
        this.searchChange()
        this.cdr.detectChanges()
      }, error: error => {
        this.pmstopic.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  pmstopicListFilter() {
    return this.pmstopic.dataList.filter(x => {
      const data = x.data
      const match = data.pmsTopicId.toLowerCase().includes(this.search.toLowerCase()) ||
        data.tdesc.toLowerCase().includes(this.search.toLowerCase())
      return match
    })
  }
  selectPmstopic(data?: PmstopicModel) {
    this.pmstopic.select = new MyPmstopicModel(data)
  }
  updatePmstopic(typeApi: 'post' | 'delete') {
    let body: PmstopicModel | PmstopicModel[]
    switch (this.modalStatus) {
      case ('delete'): {
        body = [new MyPmstopicModel(this.pmstopic.select)]
        break;
      }
      case ('deleteGroup'): {
        body = this.pmstopic.dataList.filter(x => x.check).map(x => new MyPmstopicModel(x.data))
        break;
      }
      default: {
        body = new MyPmstopicModel(this.pmstopic.select)
      }
    }
    this.pmstopic.loading = true
    this.pmstopicService[typeApi]((body as any)).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getPmstopicList()
          this.searchChange()
        } else {
          this.showAlert(response.message, 'error')
          this.pmstopic.loading = false
        }
        this.cdr.detectChanges()
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.pmstopic.loading = false
        this.cdr.detectChanges()
      }
    })
  }

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


  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.pmstopic.loading = true
    this.fileService.uploadExcel(formData, '').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getPmstopicList()
        } else {
          this.showAlert(response.message, 'error')
          this.pmstopic.loading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.pmstopic.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  downloadFile() {
    const fileName = '.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')
      }
    })

  }


  dataListCheckAll() {
    const selectAll = this.isDataListCheckedAll;
    this.pmstopic.dataList.filter(x => {
      const data = x.data
      const match = data.pmsTopicId.toLowerCase().includes(this.search.toLowerCase()) ||
        data.tdesc.toLowerCase().includes(this.search.toLowerCase())
      return match
    }).forEach(x => x.check = selectAll);
    this.dataListCheck();
  }

  dataListCheck() {
    const dataCheck = this.pmstopicListFilter();
    this.isDataListCheckedAll = dataCheck.length ? dataCheck.every(x => x.check) : false;
    this.numDataListChecked = this.pmstopic.dataList.filter(x => x.check).length;
    this.isDataListChecked = Boolean(this.numDataListChecked)
  }
  clearPmstopic(modalStatus: string) {
    if (modalStatus == 'add') {
      this.selectPmstopic()
    } else if (modalStatus == 'edit') {
      this.selectPmstopic(new MyPmstopicModel({ pmsTopicId: this.pmstopic.select.pmsTopicId }))
    }
  }
  searchChange() {
    this.currentPage = 1
    this.page = Array.from({ length: Math.ceil(this.pmstopicListFilter().length / 10) }, (_, i) => i + 1);
    this.dataListCheck()
  }
  modalSearchChange(dataList: any) {
    this.modal.currentPage = 1
    this.modal.page = Array.from({ length: Math.ceil(dataList.length / 10) }, (_, i) => i + 1);
  }


}