import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { ToastrService } from 'ngx-toastr';
import { MyPositionModel, PositionModel } from 'src/app/shared/model/position.model';
import { FileService } from 'src/app/shared/services/file.service';
import { PositionService } from 'src/app/shared/services/position.service';
import Swal from 'sweetalert2';
@Component({
  selector: 'app-position-unit',
  templateUrl: './position-unit.component.html',
  styleUrls: ['./position-unit.component.scss']
})
export class PositionUnitComponent implements OnInit {
  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';
  currentModal: 'add' | 'edit' | 'delete' = 'add'
  position: { loading: boolean, select: PositionModel, dataList: PositionModel[] } = { loading: false, select: new MyPositionModel(), dataList: [] }

  columns: ColumnModel[] = [{
    field: "positionId",
    headerText: "PositionCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "PositionDescThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "PositionDescEng",
    type: "string"
  }]
  searchSettings = {
    fields: ['positionId', 'tdesc', 'edesc'],
    operator: 'contains',
    ignoreCase: false
  };
  search = ''
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  @ViewChild("positionUnitModal") positionUnitModal: any;
  dialogRef: any
  constructor(private positionService: PositionService,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private dialog: MatDialog
  ) { }
  ngOnInit(): void {
    this.getPositionList()
  }
  openDialog() {
    this.dialogRef = this.dialog.open(this.positionUnitModal, {
      width: '500px',
      height: '500px'
    })
  }
  closeDialog() {
    this.dialogRef.close()
  }


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

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

  }
  getPositionList() {
    this.position.loading = true
    this.selectedItems.data.clear()
    this.positionService.getList().subscribe({
      next: response => {
        this.position.dataList = response.map(x => {
          this.selectedItems.data.set(x.positionId, false)
          return new MyPositionModel(x)
        })
        this.selectedItems.key = 'positionId'
        this.selectedItems.count = 0
        this.position.loading = false
        this.cdr.detectChanges();
      }, error: error => {
        this.position.loading = false
        console.error('Error fetching employee types:', error);
        this.cdr.detectChanges()
      }
    })
  }

  selectPosition(position?: PositionModel) {
    if (position) {
      this.position.select = new MyPositionModel(position)
    } else if (this.currentModal == 'add') {
      this.position.select = new MyPositionModel()
    } else if (this.currentModal == 'edit') {
      this.position.select = new MyPositionModel({ positionId: this.position.select.positionId })
    }
  }

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

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



  checkPrimary() {
    return this.position.dataList.find(x => x.positionId == this.position.select.positionId)
  }

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

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

