import { Component, OnInit } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ConfirmModalComponent } from '../confirm-modal/confirm-modal.component';
import { AlertModalComponent } from '../alert-modal/alert-modal.component';
import { UploadService } from 'src/app/service/upload.service';
import { TagService } from 'src/app/service/tag.service';
import { TagModel } from 'src/app/model/tag.mmodel';
import { GroupModel } from 'src/app/model/group.mmodel';
import { GroupService } from 'src/app/service/group.service';
import { OpenImageComponent } from '../open-image/open-image.component';
import { WidgetModel } from 'src/app/model/widgets.model';
import { WidgetService } from 'src/app/service/widgets.service';
declare var require: any
const FileSaver = require('file-saver');
@Component({
  selector: 'app-list-widgets',
  templateUrl: './list-widgets.component.html',
  styleUrls: ['./list-widgets.component.scss']
})
export class ListWidgetsComponent implements OnInit {
  page = 1;
  pageSize = 10;
  listWidgets: WidgetModel[] = []
  modelWidget: WidgetModel = new WidgetModel({});
  checkEdit: boolean = false
  search: string = ''
  listTag: TagModel[] = []
  listGroup:GroupModel[]=[]
  constructor(private modalService: NgbModal, private widgetService: WidgetService,
     private uploadService: UploadService,
      private tagService: TagService,
       private groupService: GroupService) {
  }

  onSelectFile(event:any) {
    if (event.target.files && event.target.files[0]) {
      const reader = new FileReader();
      const file: File = event.target.files[0];
      console.log("🚀 ~ ListExcelComponent ~ onSelectFile ~ file:", file)
      reader.readAsDataURL(event.target.files[0]); // read file as data url
      reader.onload = (event) => { // called once readAsDataURL is completed
        if(event){
          const allowedTypes = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-excel.sheet.macroEnabled.12'];
          if (!allowedTypes.includes(file.type)) {
            this.openAlertModal('อัพโหลดได้เฉพาะไฟล์ *.xlsx *.xlsm เท่านั้น')
          } else {
            let base64 = event.target!.result as string
            this.modelWidget.widgetObj = base64.split(',')[1];
            this.modelWidget.fileType = file.name.split('.')[file.name.split('.').length-1]
          }
       }
      }
    }
  }
  async downloadFile(logId:string){
    try {
      const data = await this.widgetService.downloadFile(logId).toPromise();
      if(data){
        FileSaver.saveAs(new Blob([data]), "file_download.xlsx");
      }
    } catch (error) {
      console.error('Error loading data:', error);
    }
  }
  async getListGroup(){
    try{
      const data = await this.groupService.getList().toPromise();
      this.listGroup = data.map(x => new GroupModel(x))
    }catch(error){
      console.error('Error loading data:', error);
    }
  }
  selectGroup(){
    let findData = this.listGroup.find(x => x.groupId == this.modelWidget.group.groupId) 
    this.modelWidget.group = findData?new GroupModel(findData):new GroupModel({})
  }
  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 allowedTypes = ['image/png', 'image/jpeg', 'image/jpg'];
        if (!allowedTypes.includes(fileData.type)) {
          this.openAlertModal('อัพโหลดได้เฉพาะไฟล์ *.jpeg, *.jpg, *.png เท่านั้น')
        } else {
          const data = await this.uploadService.uploadImage(formData).toPromise();
          if (data) {
            this.modelWidget.picture = data.body.fileId
          }
        }
      }
    } catch (error) {
      console.error('Error loading data:', error);
    }
  }

  deleteFile(item: WidgetModel) {
    const modalRef = this.modalService.open(ConfirmModalComponent, {
      centered: true,
      backdrop: 'static',
    })
    modalRef.componentInstance.message = 'คุณต้องการลบข้อมูลหรือไม่'
    modalRef.result.then(result => {
      this.widgetService.deleteWidget(item).subscribe(result => {
        if (result) {
          this.openAlertModal('ลบข้อมูลสำเร็จ')
          this.getListWidgets();
        } 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 => {
      this.modelWidget.status = Number(this.modelWidget.status)
      this.widgetService.createWidget(this.modelWidget).subscribe(result => {
        this.modalService.dismissAll()
        this.openAlertModal('อัพเดทข้อมูลสำเร็จ')
        this.getListWidgets();
        if (result) {
          this.modalService.dismissAll()
          this.openAlertModal('อัพเดทข้อมูลสำเร็จ')
          this.getListWidgets();
        } 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.modelWidget.status = Number(this.modelWidget.status)
      this.widgetService.createWidget(this.modelWidget).subscribe(result => {
        if (result) {
          this.modalService.dismissAll()
          this.openAlertModal('บันทึกข้อมูลสำเร็จ')
          this.getListWidgets();
        } else {
          this.openAlertModal('ไม่สามารถสร้างเอกสารได้')
        }
      }, error => {
        this.openAlertModal(error.message)
      })
    }, reject => { })
  }
  onSumit() {
    if (this.checkEdit) {
      this.onUpdate();
    } else {
      this.onCreate();
    }
  }
  async getWidgetById(targetModal: NgbModal, id: string) {
    try {
      const data = await this.widgetService.getWidgetById(id).toPromise();
      this.modelWidget = new WidgetModel(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?: WidgetModel) {
    console.log("🚀 ~ ListWidgetsComponent ~ openModal ~ item:", item)
    if (item) {
      this.getWidgetById(targetModal, item.widgetId)
      this.checkEdit = true
    } else {
      this.modelWidget = new WidgetModel({});
      this.checkEdit = false
      this.modalService.open(targetModal, {
        centered: true,
        backdrop: 'static',
        size: 'lg'
      });
    }

  }
  getStatus(status: string) {
    if (status == '0') {
      return 'Private'
    } else if (status == '1') {
      return 'Public'
    } 
  }
  async getListWidgets() {
    try {
      const data = await this.widgetService.getListWidgets().toPromise();
      this.listWidgets = data.map(x => new WidgetModel(x))
    } catch (error) {
      console.error('Error loading data:', error);
    }
  }
  filterListWidget() {
    return this.listWidgets.filter(x => x.widgetTname.toLowerCase().includes(this.search.toLowerCase()) || x.widgetEname.toLowerCase().includes(this.search.toLowerCase()))
  }

  ngOnInit() {
    this.getListWidgets();
    this.getListTag();
    this.getListGroup();
  }

  async getListTag() {
    try {
      const data = await this.tagService.getListWidgets().toPromise();
      this.listTag = data.map(x => new TagModel(x))
    } catch (error) {
      console.error('Error loading data:', error);
    }
  }
  openEmployeeModal(image:string) {
    const modalRef = this.modalService.open(OpenImageComponent, {
      centered: true,
      windowClass: 'my-dialog-img-preview'
    })
    modalRef.componentInstance.linkImage = image
    modalRef.result.then(result => {
    }, reason => {
      this.modalService.dismissAll()
    })
  }
  closeBtnClick() {
    this.modalService.dismissAll();
  }
  openLink(url: string) {
    window.open(url, "_blank");
  }
}
