import { ChangeDetectorRef, Component, ViewChild } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { MyPmstypeModel, PmstypeModel } from 'src/app/shared/model/pmstype.model';
import { FileService } from 'src/app/shared/services/file.service';
import { PmstypeService } from 'src/app/shared/services/pmstype.service';
import { ColumnModel } from '@syncfusion/ej2-grids';
import Swal from 'sweetalert2';
import { MatDialog } from '@angular/material/dialog';

@Component({
  selector: 'app-assessment-types',
  templateUrl: './assessment-types.component.html',
  styleUrls: ['./assessment-types.component.scss']
})
export class AssessmentTypesComponent {

  pmstype: { loading: boolean, select: PmstypeModel, dataList: PmstypeModel[] } = { loading: false, select: new MyPmstypeModel(), dataList: [] }
  modalStatus: "add" | "edit" | 'delete' = "add"
  columns: ColumnModel[] = [{
    field: "pmsTypeId",
    headerText: "Code",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "TypeName",
    type: "string"
  },
  {
    field: "shortName",
    headerText: "Abbreviations",
    type: "string"
  }]
  searchSettings = {
    fields: ['pmsTypeId', 'tdesc', 'shortName'],
    operator: 'contains',
    ignoreCase: false
  };
  search = ""
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
   @ViewChild("assessmentTypesModal") assessmentTypesModal: any;
    dialogRef: any

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

  ngOnInit(): void {
    this.getPmstypeList()
  }

  getPmstypeList() {
    this.pmstype.loading = true
    this.selectedItems.data.clear()
    this.pmstypeService.getList().subscribe({
      next: response => {
        this.pmstype.dataList = response.map(x => {
          return new MyPmstypeModel(x)
        })
        this.pmstype.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.pmstype.loading = false
        this.cdr.detectChanges()
      }
    })
  }

 
  selectPmstype(data?: PmstypeModel) {
    if (data) {
      this.pmstype.select = new MyPmstypeModel(data)
    } else if (this.modalStatus == 'add') {
      this.pmstype.select = new MyPmstypeModel()
    } else if (this.modalStatus == 'edit') {
      this.pmstype.select = new MyPmstypeModel({ pmsTypeId: this.pmstype.select.pmsTypeId })
    }
  }

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

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

  }

  clearPmstype(modalStatus: string) {
    if (modalStatus == 'add') {
      this.selectPmstype()
    } else if (modalStatus == 'edit') {
      this.selectPmstype(new MyPmstypeModel({ pmsTypeId: this.pmstype.select.pmsTypeId }))
    }
  }
  checkPrimary() {
    return this.pmstype.dataList.find(x => x.pmsTypeId == this.pmstype.select.pmsTypeId)
  }
  

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

}



