import { ChangeDetectorRef, Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { ToastrService } from 'ngx-toastr';
import { CompetencyCourseModel, MyCompetencyCourseModel } from 'src/app/shared/model/competency-course.model';
import { MyCompetencycourseModel } from 'src/app/shared/model/competencycourse.model';
import { CompetencycourseService } from 'src/app/shared/services/competencycourse.service';
import { FileService } from 'src/app/shared/services/file.service';
import Swal from 'sweetalert2';
@Component({
  selector: 'app-development-course',
  templateUrl: './development-course.component.html',
  styleUrls: ['./development-course.component.scss']
})
export class DevelopmentCourseComponent {
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);

  currentModal: 'add' | 'edit' | 'delete' = "add";
  competencyCourse: { loading: boolean, select: CompetencyCourseModel, dataList: CompetencyCourseModel[] } = { loading: false, select: new MyCompetencyCourseModel(), dataList: [] }
  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false

  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';

  columns: ColumnModel[] = [{
    field: "competencyCourseId",
    headerText: "Code",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "CDRName",
    type: "string"
  }]
  searchSettings = {
    fields: ['competencyCourseId', 'tdesc'],
    operator: 'contains',
    ignoreCase: false
  };
  search = ''
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };

  @ViewChild("developmentCourseModal") developmentCourseModal: any;
  dialogRef: any

  constructor(private toastr: ToastrService,
    private dialog: MatDialog,
    private cdr: ChangeDetectorRef,
    private competencycourseService: CompetencycourseService,
    private fileService: FileService
  ) { }
  ngOnInit(): void {
    this.getCompetencycourseList()
  }
  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.competencyCourse.loading = true
    this.fileService.uploadExcel(formData, 'COMPETENCY_COURSE').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getCompetencycourseList()
        } else {
          this.showAlert(response.message, 'error')
          this.competencyCourse.loading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.competencyCourse.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  downloadFile() {
    const fileName = 'IMPORT_COMPETENCY_COURSE.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')
      }
    })

  }

  getCompetencycourseList() {
    this.competencyCourse.loading = true
    this.selectedItems.data.clear()
    this.competencycourseService.getList().subscribe({
      next: response => {
        this.competencyCourse.dataList = response.map(x => {
          this.selectedItems.data.set(x.competencyCourseId, false)
          return new MyCompetencyCourseModel(x)
        })
        this.selectedItems.key = 'competencyCourseId'
        this.selectedItems.count = 0
        this.competencyCourse.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.competencyCourse.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  selectCompetencycourse(competencyCourse?: CompetencyCourseModel) {
    if (competencyCourse) {
      this.competencyCourse.select = new MyCompetencyCourseModel(competencyCourse)
    } else if (this.currentModal == 'add') {
      this.competencyCourse.select = new MyCompetencyCourseModel()
    } else if (this.currentModal == 'edit') {
      this.competencyCourse.select = new MyCompetencyCourseModel({ competencyCourseId: this.competencyCourse.select.competencyCourseId })
    }
  }

  addDevelopmentCourse() {
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'บันทึกข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        this.competencyCourse.loading = true
        this.competencycourseService.post(new MyCompetencyCourseModel(this.competencyCourse.select)).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getCompetencycourseList()
              this.closeDialog()
            } else {
              this.showAlert(response.message, 'error')
              this.competencyCourse.loading = false
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.competencyCourse.loading = false
          }
        })
      }
    })
  }

  deleteDevelopmentCourse() {
    if (!this.numSelectItem()) {
      this.showAlert('กรุณาเลือกข้อมูลที่ต้องการลบ', 'error')
      return
    }
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการลบข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'ลบข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        this.competencyCourse.loading = true
        const selectedKeys = Array.from(this.selectedItems.data.keys());
        const body = this.competencyCourse.dataList.filter(x => selectedKeys.includes(x.competencyCourseId) && this.selectedItems.data.get(x.competencyCourseId)).map(x => new MyCompetencyCourseModel(x))
        this.competencycourseService.delete(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getCompetencycourseList()
              this.closeDialog()
            } else {
              this.showAlert(response.message, 'error')
              this.competencyCourse.loading = false
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.competencyCourse.loading = false
          }
        })
      }
    });
  }

  showAlert(text: string, type: 'success' | 'error') {
    Swal.fire({
      title: 'แจ้งเตือน',
      text: text,
      icon: type,
      confirmButtonText: 'ตกลง',
    });
  }

  checkPrimary() {
    return this.competencyCourse.dataList.find(x => x.competencyCourseId == this.competencyCourse.select.competencyCourseId)
  }

  onSelectItemChange(arg: any) {
    this.selectedItems = arg
  }

  numSelectItem() {
    const selectedKeys = Array.from(this.selectedItems.data.keys());
    const num = this.competencyCourse.dataList.filter(x => selectedKeys.includes(x.competencyCourseId) && this.selectedItems.data.get(x.competencyCourseId)).length
    return num
  }

  openDialog() {
    this.dialogRef = this.dialog.open(this.developmentCourseModal, {
      width: '500px',
      disableClose: false,
    });
  }

  closeDialog() {
    this.dialogRef.close()
  }
}
