import { ChangeDetectorRef, Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { CompetencyGradeModel } from 'src/app/shared/model/competency-grades.model';
import { MyPmsGroupGradeModel } from 'src/app/shared/model/pms-group-grade.model';
import { PmsGroupGradeService } from 'src/app/shared/services/pms-group-grade.service';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { MatDialog } from '@angular/material/dialog';
import Swal from 'sweetalert2';

export interface DataModel {
  check: boolean;
  code: string;
  tdesc: string;
  edesc: string;
  pmsGrade: CompetencyGradeModel[]
}

@Component({
  selector: 'app-pms-grade-management',
  templateUrl: './pms-grade-management.component.html',
  styleUrls: ['./pms-grade-management.component.scss'],
})
export class PmsGradeManagementComponent {
  @Output() sendPathTitle: EventEmitter<string[]> = new EventEmitter<string[]>();
  typeTab: "" | "add" | "edit" = "";
  currentPage = 1;
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false
  search = '';

  dataList: DataModel[] = [];
  dataLoading = false
  dataSelect: DataModel = { check: false, code: '', tdesc: '', edesc: '', pmsGrade: [] }

  columns: ColumnModel[] = [{
    field: "code",
    headerText: "Code",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "DescriptionThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "DescriptionEng",
    type: "string"
  }]
  searchSettings = {
    fields: ['code', 'tdesc', 'edesc'],
    operator: 'contains',
    ignoreCase: false
  };
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  @ViewChild("pmsGradeModal") pmsGradeModal: any;
  dialogRef: any

  constructor(private toastr: ToastrService,
    private pmsGroupGradeService: PmsGroupGradeService,
    private dialog: MatDialog,
    private cdr: ChangeDetectorRef) {
    this.sendPathTitle.emit(['menu.PerformanceManagementSystem', 'menu.Grade', 'GradeManage'])
  }
  ngOnInit(): void {
    this.getPmsGroupGradeList()
  }
  selectData(dataSelect?: DataModel) {
    if (dataSelect) {
      this.dataSelect = JSON.parse(JSON.stringify(dataSelect));
    } else if (this.typeTab === 'add') {
      this.dataSelect = {
        check: false,
        code: '',
        tdesc: '',
        edesc: '',
        pmsGrade: []
      };
    } else if (this.typeTab === 'edit') {
      this.dataSelect = {
        check: false,
        code: this.dataSelect.code,
        tdesc: '',
        edesc: '',
        pmsGrade: []
      };
    }
  }
  getPmsGroupGradeList() {
    this.dataLoading = true
    this.selectedItems.data.clear()
    this.pmsGroupGradeService.getList().subscribe({
      next: response => {
        this.dataList = response.map(x => ({ check: false, code: x.groupGradeId, tdesc: x.tdesc, edesc: x.edesc, pmsGrade: x.pmsGrade }))
        this.isDataListCheckedAll = false

        this.selectedItems.key = 'code'
        this.selectedItems.count = 0
        this.searchChange()
        this.dataLoading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.dataLoading = false
        this.cdr.detectChanges()
      }
    })
  }
  pathTitleChange(tap?: 'add' | 'edit') {
    this.typeTab = tap || ''
    switch (this.typeTab) {
      case 'add': {
        this.sendPathTitle.emit(['การประเมินสมรรถนะ', 'ทะเบียนเกรด', 'การจัดการเกรด', 'เพิ่มกลุ่มเกรด'])
        break;
      }
      case 'edit': {
        this.sendPathTitle.emit(['การประเมินสมรรถนะ', 'ทะเบียนเกรด', 'การจัดการเกรด', 'แก้ไขกลุ่มเกรด'])
        break;
      }
      default: {
        this.sendPathTitle.emit(['การประเมินสมรรถนะ', 'ทะเบียนเกรด', 'การจัดการเกรด'])
      }
    }
  }

  searchChange() {
    this.currentPage = 1;
    const filteredData = this.dataListFilter();
    this.page = Array.from({ length: Math.ceil(filteredData.length / 10) }, (_, i) => i + 1);
  }

  dataListFilter() {
    return this.dataList.filter((x) => {
      const match = x.code.toLowerCase().includes(this.search.toLowerCase()) || x.tdesc.toLowerCase().includes(this.search.toLowerCase()) || x.edesc.toLowerCase().includes(this.search.toLowerCase());
      return match;
    });
  }

  showAlert(text: string, type: 'success' | 'error') {
    this.toastr[type](text, 'แจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    })
  }

  deletePmsGroupGradeList() {
    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.dataList.filter(x => selectedKeys.includes(x.code) && this.selectedItems.data.get(x.code)).map(x => new MyPmsGroupGradeModel({ groupGradeId: x.code, tdesc: x.tdesc, edesc: x.edesc }))
        this.pmsGroupGradeService.delete(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getPmsGroupGradeList()
              this.closeDialog()
            } else {
              this.showAlert(response.message, 'error')
              this.dataLoading = false
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.dataLoading = false
          }
        })
      }
    });
  }

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

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

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

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