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 { CompetencytypeModel, MyCompetencytypeModel } from 'src/app/shared/model/competencytype.model';
import { CompetencytypeService } from 'src/app/shared/services/competencytype.service';
import { FileService } from 'src/app/shared/services/file.service';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-type-registration',
  templateUrl: './type-registration.component.html',
  styleUrls: ['./type-registration.component.scss']
})
export class TypeRegistration {


  typeList: CompetencytypeModel[] = [];
  dataLoading = false
  competoncy_type: CompetencytypeModel = new MyCompetencytypeModel({})
  currentModal: 'add' | 'edit' | 'delete' = 'add'
  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';

  columns: ColumnModel[] = [{
    field: "competencyTypeId",
    headerText: "Code",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "TypeName",
    type: "string"
  },
  {
    field: "shortName",
    headerText: "Abbreviations",
    type: "string"
  }]
  searchSettings = {
    fields: ['competencyTypeId', '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("typeRegistrationModal") typeRegistrationModal: any;
  dialogRef: any
  constructor(private competencytypeService: CompetencytypeService,
    private dialog: MatDialog,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService

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

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

  downloadFile() {
    const fileName = 'IMPORT_COMPETENCY_TYPE.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')
      }
    })

  }

  getCompetencytypeList() {
    this.dataLoading = true
    this.selectedItems.data.clear()
    this.competencytypeService.getList().subscribe({
      next: response => {
        this.typeList = response.map(x => {
          this.selectedItems.data.set(x.competencyTypeId, false)
          return new MyCompetencytypeModel(x)
        })
        this.selectedItems.key = 'competencyTypeId'
        this.selectedItems.count = 0
        this.dataLoading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.dataLoading = false
        this.cdr.detectChanges()
      }
    })
  }

  edit(item?: CompetencytypeModel) {
    this.competoncy_type = new MyCompetencytypeModel(item || {})
  }

  selectCompetencyType(CompetencyType?: CompetencytypeModel) {
    if (CompetencyType) {
      this.competoncy_type = new MyCompetencytypeModel(CompetencyType)
    } else if (this.currentModal == 'add') {
      this.competoncy_type = new MyCompetencytypeModel()
    } else if (this.currentModal == 'edit') {
      this.competoncy_type = new MyCompetencytypeModel({ competencyTypeId: this.competoncy_type.competencyTypeId })
    }
  }

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

  deleteType_registration() {
    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.dataLoading = true
        const selectedKeys = Array.from(this.selectedItems.data.keys());
        const body = this.typeList.filter(x => selectedKeys.includes(x.competencyTypeId) && this.selectedItems.data.get(x.competencyTypeId)).map(x => new MyCompetencytypeModel(x))
        this.competencytypeService.delete(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success');
            } else {
              this.showAlert(response.message, 'error');
            }
            this.getCompetencytypeList();
            this.cdr.detectChanges()
          },
          error: error => {
            this.showAlert(error.message, 'error')
            this.dataLoading = false
            this.cdr.detectChanges()
          }
        })
      }
    });
  }

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



  clearData(currentModal: string) {
    if (currentModal == 'add') {
      this.competoncy_type = new MyCompetencytypeModel({})
    } else if (currentModal == 'edit') {
      this.competoncy_type = new MyCompetencytypeModel({ ...this.competoncy_type, competencyTypeId: this.competoncy_type.competencyTypeId })
    }
  }

  checkPrimary() {
    return this.typeList.find(x => x.competencyTypeId == this.competoncy_type.competencyTypeId)
  }

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

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

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

