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 { AssessmentModel, MyAssessmentModel } from 'src/app/shared/model/assessment.model';
import { AssessmentService } from 'src/app/shared/services/assessment.service';
import { FileService } from 'src/app/shared/services/file.service';
import { data } from '../../../datagrid-syncfution/data';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-assessment-tool',
  templateUrl: './assessment-tool.component.html',
  styleUrls: ['./assessment-tool.component.scss']
})
export class AssessmentToolComponent {
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false

  assessment: { loading: boolean, select: AssessmentModel, dataList: AssessmentModel[] } = { loading: false, select: new MyAssessmentModel(), dataList: [] }


  currentModal: 'add' | 'edit' | 'delete' = "add"
  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';

  columns: ColumnModel[] = [{
    field: "assessmentId",
    headerText: "Code",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "ToolsName",
    type: "string"
  },
  {
    field: "shortName",
    headerText: "DisplayName",
    type: "string"
  }]
  searchSettings = {
    fields: ['assessmentId', '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("AssessmentModal") AssessmentModal: any;
  dialogRef: any

  constructor(private toastr: ToastrService,
    private dialog: MatDialog,
    private cdr: ChangeDetectorRef,
    private assessmentService: AssessmentService,
    private fileService: FileService
  ) { }
  ngOnInit(): void {
    this.getAssessmentList()
  }
  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.assessment.loading = true
    this.fileService.uploadExcel(formData, 'COMPETENCY_ASSESSMENT').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getAssessmentList()
        } else {
          this.showAlert(response.message, 'error')
          this.assessment.loading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.assessment.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  downloadFile() {
    const fileName = 'IMPORT_COMPETENCY_ASSESSMENT.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')
      }
    })

  }
  getAssessmentList() {
    this.assessment.loading = true
    this.selectedItems.data.clear()
    this.assessmentService.getList().subscribe({
      next: response => {
        this.assessment.dataList = response.map(x => {
          this.selectedItems.data.set(x.assessmentId, false)
          return new MyAssessmentModel(x)
        })

        this.selectedItems.key = 'assessmentId'
        this.selectedItems.count = 0
        this.assessment.loading = false
        this.cdr.detectChanges()
      },
      error: error => {
        this.assessment.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  selectAssessment(assessment?: AssessmentModel) {
    if (assessment) {
      this.assessment.select = new MyAssessmentModel(assessment)
    } else if (this.currentModal == 'add') {
      this.assessment.select = new MyAssessmentModel()
    } else if (this.currentModal == 'edit') {
      this.assessment.select = new MyAssessmentModel({ assessmentId: this.assessment.select.assessmentId })
    }
  }

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

  deleteAssessment() {
    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.assessment.loading = true
        const selectedKeys = Array.from(this.selectedItems.data.keys());
        const body = this.assessment.dataList.filter(x => selectedKeys.includes(x.assessmentId) && this.selectedItems.data.get(x.assessmentId)).map(x => new MyAssessmentModel(x))
        this.assessmentService.delete(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getAssessmentList()
              this.closeDialog()
            } else {
              this.showAlert(response.message, 'error')
              this.assessment.loading = false
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.assessment.loading = false
          }
        })
      }
    });
  }

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


  checkPrimary() {
    return this.assessment.dataList.find(x => x.assessmentId == this.assessment.select.assessmentId)
  }

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

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

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

  closeDialog() {
    this.dialogRef.close()
  }
}

