import { Component, OnInit } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ExcelService } from 'src/app/service/excel.service';
import { ConfirmModalComponent } from '../confirm-modal/confirm-modal.component';
import { AlertModalComponent } from '../alert-modal/alert-modal.component';
import { CourseModel } from 'src/app/model/course.model';
import { CourseService } from 'src/app/service/course.service';
import { UploadService } from 'src/app/service/upload.service';

@Component({
  selector: 'app-list-course',
  templateUrl: './list-course.component.html',
  styleUrls: ['./list-course.component.scss']
})
export class ListCourseComponent implements OnInit {
  page = 1;
  pageSize = 10;
  listCourse:CourseModel[]=[]
  modelCourse:CourseModel = new CourseModel({});
  checkEdit:boolean = false
  search:string = ''
  constructor(private modalService: NgbModal,private courseService:CourseService,private uploadService:UploadService) {
  }
  async onUploadImage(event:any){
    try{
      if (event.target.files.length > 0) {
        let fileData = event.target.files[0];
        const formData = new FormData();
        formData.append('file', fileData);
        const data = await this.uploadService.uploadImage(formData).toPromise();
       if(data){
         this.modelCourse.thumbnail = data.body.fileId
       }
      }
    } catch (error) {
      console.error('Error loading data:', error);
    }
  }
  onSelectFile(event:any) {
    if (event.target.files && event.target.files[0]) {
      let reader = new FileReader();
      reader.readAsDataURL(event.target.files[0]); // read file as data url
      reader.onload = (event) => { // called once readAsDataURL is completed
        if(event){
          let base64 = event.target!.result as string
          this.modelCourse.courseObj = base64.split(',')[1];
       }
      }
    }
  }
 async downloadFile(logId:string){
    try {
      const data = await this.courseService.downloadFile(logId).toPromise();
    } catch (error) {
      console.error('Error loading data:', error);
    }
  }
  deleteFile(item:CourseModel){
    const modalRef = this.modalService.open(ConfirmModalComponent, {
      centered: true,
      backdrop: 'static',
    })
    modalRef.componentInstance.message = 'คุณต้องการลบข้อมูลหรือไม่'
    modalRef.result.then(result => {
      this.courseService.deleteCourse(item).subscribe(result => {
        if (result) {
          this.openAlertModal('ลบข้อมูลสำเร็จ')
          this.getListCourse();
        } else {
      this.openAlertModal('ไม่สามารถลบข้อมูลได้')
        }
      }, error => {
        this.openAlertModal(error.message)
      })
    }, reject => { })

  }
  openAlertModal(message?: string) {
    const modalRef = this.modalService.open(AlertModalComponent, {
      centered: true,
      backdrop: 'static'
    })
    modalRef.componentInstance.message = message ? message : ""
    modalRef.result.then(result => {
      this.modalService.dismissAll()
    }, reason => {
      this.modalService.dismissAll()
    })
  }

  onUpdate(){
    const modalRef = this.modalService.open(ConfirmModalComponent, {
      centered: true,
      backdrop: 'static',
    })
    modalRef.componentInstance.message = 'คุณต้องการอัพเดทข้อมูลหรือไม่'
    modalRef.result.then(result => {
      console.log(this.modelCourse);
      this.courseService.createCourse(this.modelCourse).subscribe(result => {
        if (result) {
          this.openAlertModal('อัพเดทข้อมูลสำเร็จ')
          this.getListCourse();
        } else {
      this.openAlertModal('ไม่สามารถอัพเดทข้อมูลได้')
        }
      }, error => {
        this.openAlertModal(error.message)
      })
    }, reject => { })
  }
  onCreate(){
    const modalRef = this.modalService.open(ConfirmModalComponent, {
      centered: true,
      backdrop: 'static',
    })
    modalRef.componentInstance.message = 'คุณต้องการบันทึกข้อมูลหรือไม่'
    modalRef.result.then(result => {
      this.courseService.createCourse(this.modelCourse).subscribe(result => {
        if (result) {
          this.openAlertModal('บันทึกข้อมูลสำเร็จ')
          this.getListCourse();
        } else {
      this.openAlertModal('ไม่สามารถสร้างเอกสารได้')
        }
      }, error => {
        this.openAlertModal(error.message)
      })
    }, reject => { })
  }
  onSumit() {
   if(this.checkEdit){
    this.onUpdate();
   }else{
    this.onCreate();
   }
  }
  async getExcelById(targetModal: NgbModal,id:string){
    try {
      const data = await this.courseService.getCourseById(id).toPromise();
      this.modelCourse = new CourseModel(data)
      if(data){
        this.modalService.open(targetModal, {
          centered: true,
          backdrop: 'static',
          size: 'lg'
        });
      }
    } catch (error) {
      console.error('Error loading data:', error);
    }
  }
  openModal(targetModal: NgbModal,item?:CourseModel) {
    if(item){
      this.getExcelById(targetModal,item.logId)
      this.checkEdit = true
    }else{
      this.modelCourse = new CourseModel({});
      this.checkEdit = false
      this.modalService.open(targetModal, {
        centered: true,
        backdrop: 'static',
        size: 'lg'
      });
    }
   
  }
  getStatus(status:string){
    if(status == '0'){
      return 'รออนุมัติ'
    } else if(status == '1'){
      return 'เปิดใช้งาน'
    } else if(status == '2'){
      return 'ไม่อนุมัติ'
    }
  }
  async getListCourse(){
    try {
      const data = await this.courseService.getListCourse().toPromise();
      this.listCourse = data.map(x => new CourseModel(x))
    } catch (error) {
      console.error('Error loading data:', error);
    }
  }
  filterListCourse(){
    return this.listCourse.filter(x => x.thName.toLowerCase().includes(this.search.toLowerCase())||x.engName.toLowerCase().includes(this.search.toLowerCase()))
  }
  
  ngOnInit() {
    this.getListCourse();
  }


  closeBtnClick() {
    this.modalService.dismissAll();
  }

}
