import { ChangeDetectorRef, Component, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ConfigService } from '@ks89/angular-modal-gallery/lib/services/config.service';
import { TranslateService } from '@ngx-translate/core';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { ToastrService } from 'ngx-toastr';
import { MenuBodyModel } from 'src/app/shared/model/config-permission.model';
import { DocumentManagerModel, MyDocumentManagerModel } from 'src/app/shared/model/document-manager.model';
import { ConfigPermissionService } from 'src/app/shared/services/config-permission.service';
import { DocumentManagerService } from 'src/app/shared/services/documents.service';
import { FileService } from 'src/app/shared/services/file.service';
import { NavService } from 'src/app/shared/services/navservice';
import Swal from 'sweetalert2';
@Component({
  selector: 'app-document-upload-manager',
  templateUrl: './document-upload-manager.component.html',
  styleUrls: ['./document-upload-manager.component.scss']
})
export class DocumentUploadManagerComponent {
  pathTitle = ['menu.Organization', 'menu.LeaveType', 'DocumentUploadManager']

  @ViewChild("fileInputMedium") fileInputMedium: any;
  selectedFile: File | null = null;
  selectedFileName: string = 'PleaseSelectFile';

  currentModal: 'add' | 'edit' | 'delete' = 'add'
  documentManager: { loading: boolean, select: DocumentManagerModel, dataList: DocumentManagerModel[] } = { loading: false, select: new MyDocumentManagerModel(), dataList: [] }

  syncfutionDataList: any[] = []
  columns: ColumnModel[] = [{
    field: "documentId",
    headerText: "code",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "DocumentNameThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "DocumentNameEng",
    type: "string"
  },
  {
    field: "lineNo",
    headerText: "DisplayOrder",
    type: "string"
  },
  {
    field: "statusText",
    headerText: "Eva",
    type: "string"
  }]
  searchSettings = {
    fields: ['documentId', 'tdesc', 'edesc', 'lineNo', 'statusText'],
    operator: 'contains',
    ignoreCase: false
  };
  search = ''
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  @ViewChild("documentModal") documentModal: any;
  dialogRef: any
  constructor(private documentManagerService: DocumentManagerService,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private dialog: MatDialog,
    private translateService: TranslateService
  ) {
    this.translateService.onLangChange.subscribe((event) => {
      this.setSyncfutionDataList()
    });
  }
  ngOnInit(): void {
    this.getDocumentManagerList()
  }
  getDocumentManagerList() {
    this.documentManager.loading = true
    this.selectedItems.data.clear()
    this.documentManagerService.getList().subscribe({
      next: response => {
        this.documentManager.dataList = response.map(x => {
          this.selectedItems.data.set(x.documentId, false)
          return new MyDocumentManagerModel(x)
        })
        this.setSyncfutionDataList()
        this.selectedItems.key = 'documentId'
        this.selectedItems.count = 0
        this.documentManager.loading = false
        this.cdr.detectChanges();
      }, error: error => {
        this.documentManager.loading = false
        console.error('Error fetching employee types:', error);
        this.cdr.detectChanges()
      }
    })
  }
  setSyncfutionDataList() {
    this.syncfutionDataList = this.documentManager.dataList.map(e => (
      ({ ...e, statusText: e.status == 0 ? this.translateService.instant('Close') : this.translateService.instant('Open') })
    ))
  }
  openDialog() {
    if (this.fileInputMedium) {
      this.fileInputMedium.nativeElement.value = "";
    }
    this.selectedFileName = this.documentManager.select.documentFiles || 'PleaseSelectFile'
    this.dialogRef = this.dialog.open(this.documentModal, {
      width: '500px',
    })
  }
  closeDialog() {
    this.dialogRef.close()
  }


  selectDocumentManager(documentManager?: DocumentManagerModel) {
    this.documentManager.select = new MyDocumentManagerModel(documentManager)
  }

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

  deleteDocumentManager() {
    if (this.numSelectItem() == 0) {
      this.showAlert('กรุณาเลือกข้อมูลที่จะลบ', 'error')
      return
    }
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการลบข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'ลบข้อมูล',
    }).then((result) => {
      if (result.isConfirmed) {
        this.documentManager.loading = true
        const selectedKeys = Array.from(this.selectedItems.data.keys());
        const body = this.documentManager.dataList.filter(x => selectedKeys.includes(x.documentId) && this.selectedItems.data.get(x.documentId)).map(x => new MyDocumentManagerModel(x))
        this.documentManagerService.delete(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getDocumentManagerList()
            } else {
              this.showAlert(response.message, 'error')
              this.documentManager.loading = false
              this.cdr.detectChanges()
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.documentManager.loading = false
            this.cdr.detectChanges()
          }
        })
      }
    })
  }
  showAlert(text: string, type: 'success' | 'error') {
    Swal.fire({
      icon: type,
      title: 'แจ้งเตือน',
      text: text,
      showCancelButton: false,
      confirmButtonText: 'ยืนยัน',
    })
  }



  checkPrimary() {
    return this.documentManager.dataList.find(x => x.documentId == this.documentManager.select.documentId)
  }

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

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

  onFileSelected(event: any) {
    this.selectedFile = event.target.files.length > 0 ? event.target.files[0] : null;
    this.selectedFileName = this.selectedFile?.name || "PleaseSelectFile"
    this.uploadFile()
  }
  uploadFile() {
    if (!this.selectedFile) return;

    const formData = new FormData();
    formData.append('file', this.selectedFile);

    this.fileService.uploadFiles(formData).subscribe({
      next: response => {
        if (response.success) {
          this.selectedFile = null;
          this.documentManager.select.documentFiles = response.resultObject
        } else {
          this.showAlert(response.message, 'error');
          this.cdr.detectChanges();
        }
      },
      error: error => {
        this.showAlert(error.message, 'error');
        this.cdr.detectChanges();
      }
    });
  }
  downloadFile(fileName: string) {
    this.fileService.downloadFiles(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);
        this.cdr.detectChanges()
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.cdr.detectChanges()
      }
    })
  }
}
