import { ChangeDetectorRef, Component, ViewChild } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { MyEmeventgrpModel } from 'src/app/shared/model/emeventgrp.model';
import { EventgrpModel, MyEventgrpModel, } from 'src/app/shared/model/eventgrp.model';
import { PmsWorkingTimeModel, MyPmsWorkingTimeModel } from 'src/app/shared/model/pms-working-time.model';
import { EventgrpService } from 'src/app/shared/services/eventgrp.service';
import { FileService } from 'src/app/shared/services/file.service';
import { PmsWorkingTimeService } from 'src/app/shared/services/pms-working-time.service';
import { ColumnModel } from '@syncfusion/ej2-grids';
import Swal from 'sweetalert2';
import { MatDialog } from '@angular/material/dialog';
import { TranslateService } from '@ngx-translate/core';

interface table {
  currentPage: number,
  page: number[],
  search: string,
  pageSize: number
}
@Component({
  selector: 'app-time-attendance-manage',
  templateUrl: './time-attendance-manage.component.html',
  styleUrls: ['./time-attendance-manage.component.scss']
})
export class TimeAttendanceManageComponent {
  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false
  currentPage = 1;
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  search = '';
  modalStatus: "add" | "edit" | "delete" | "deleteGroup" = "add"
  modal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }
  eventgrpmodal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }
  eventgrp: { loading: boolean, selectIndex: number, selectList: EventgrpModel[], dataList: { check: boolean, data: EventgrpModel }[] } = { loading: false, selectIndex: -1, selectList: [new MyEventgrpModel()], dataList: [] }
  pmsWorkingTime: { loading: boolean, select: PmsWorkingTimeModel, dataList: PmsWorkingTimeModel[] } = { loading: false, select: new MyPmsWorkingTimeModel(), dataList: [] }
  columns: ColumnModel[] = [{
    field: "pmsWorkingTimeId",
    headerText: "Code",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "name",
    headerText: "TopicName",
    type: "string"
  },
  {
    field: "detailUnit",
    headerText: "Unit",
    type: "string"
  },
  {
    field: "weight",
    headerText: "Weight",
    type: "string"
  }]
  searchSettings = {
    fields: ['pmsWorkingTimeId', 'name', 'detailUnit', 'weight'],
    operator: 'contains',
    ignoreCase: false
  };
  syncfutionDataList: any[] = []
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  @ViewChild("timeAttendanceModal") timeAttendanceModal: any;
  @ViewChild("evenTgrpModal") evenTgrpModal: any;
  dialogRef: any
  dialogRefEventgrp: any
  constructor(
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private dialog: MatDialog,
    private fileService: FileService,
    private eventgrpService: EventgrpService,
    private pmsWorkingTimeService: PmsWorkingTimeService,
    private translateService: TranslateService
  ) {
    this.translateService.onLangChange.subscribe((event) => {
      this.setSyncfutionDataList()
    });
  }
  setSyncfutionDataList() {
    if (this.pmsWorkingTime.dataList) {
      this.syncfutionDataList = this.pmsWorkingTime.dataList.map(e => ({
        pmsWorkingTimeId: e.pmsWorkingTimeId,
        name: this.translateService.getCurrentLang() == 'th' ? e.tdesc : e.edesc,
        detailUnit: e.detailUnit,
        weight: e.weight
      }))
    }
  }

  ngOnInit(): void {
    this.getEventgrpList()
    this.getPmsWorkingTimeList()
  }
  getPmsWorkingTimeList() {
    this.pmsWorkingTime.loading = true
    this.selectedItems.data.clear()
    this.pmsWorkingTimeService.getList().subscribe({
      next: response => {
        this.pmsWorkingTime.dataList = response.map(x => {
          this.selectedItems.data.set(x.pmsWorkingTimeId, false)
          return new MyPmsWorkingTimeModel(x)
        })
        this.selectedItems.key = 'pmsWorkingTimeId'
        this.selectedItems.count = 0
        this.pmsWorkingTime.loading = false

        this.searchChange()
        this.setSyncfutionDataList()
        this.cdr.detectChanges();
      }, error: error => {
        this.pmsWorkingTime.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  pmsWorkingTimeFilter() {
    return this.pmsWorkingTime.dataList.filter((x) => {
      const data = x
      const match = data.pmsWorkingTimeId.toLowerCase().includes(this.search.toLowerCase()) ||
        data.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
        data.detailUnit.toLowerCase().includes(this.search.toLowerCase()) ||
        (data.weight + "").toLowerCase().includes(this.search.toLowerCase())
      return match;
    });
  }
  searchChange() {
    this.currentPage = 1;
    const filteredData = this.pmsWorkingTimeFilter();
    this.page = Array.from({ length: Math.ceil(filteredData.length / 10) }, (_, i) => i + 1);
  }
  selectWorkingtime(dataSelect?: any) {
    const data = this.pmsWorkingTime.dataList.find(e => e.pmsWorkingTimeId == dataSelect.pmsWorkingTimeId)
    if (data) {
      this.pmsWorkingTime.select = new MyPmsWorkingTimeModel(data)
    } else if (this.modalStatus == 'add') {
      this.pmsWorkingTime.select = new MyPmsWorkingTimeModel()
    } else if (this.modalStatus == 'edit') {
      this.pmsWorkingTime.select = new MyPmsWorkingTimeModel({ pmsWorkingTimeId: this.pmsWorkingTime.select.pmsWorkingTimeId })
    }
  }
  addpmsWorkingTimes() {
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'บันทึกข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        this.pmsWorkingTime.loading = true
        this.pmsWorkingTimeService.post(this.pmsWorkingTime.select).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getPmsWorkingTimeList()
              this.closeDialog()
            } else {
              this.showAlert(response.message, 'error')
              this.pmsWorkingTime.loading = false
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.pmsWorkingTime.loading = false
          }
        })
      }
    })
  }
  deletepmsWorkingTimes() {
    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.pmsWorkingTime.loading = true
        const selectedKeys = Array.from(this.selectedItems.data.keys());
        const body = this.pmsWorkingTime.dataList.filter(x => selectedKeys.includes(x.pmsWorkingTimeId) && this.selectedItems.data.get(x.pmsWorkingTimeId)).map(x => new MyPmsWorkingTimeModel(x))
        this.pmsWorkingTimeService.delete(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getPmsWorkingTimeList()
              this.closeDialog()
            } else {
              this.showAlert(response.message, 'error')
              this.pmsWorkingTime.loading = false
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.pmsWorkingTime.loading = false
          }
        })
      }
    });
  }

  getEventgrpList() {
    this.eventgrp.loading = true
    this.eventgrpService.getList().subscribe({
      next: response => {
        this.eventgrp.dataList = response.map(x => ({ check: false, data: new MyEventgrpModel(x) }))
        this.eventgrp.loading = false
        this.isDataListCheckedAll = false
        this.searchChange()
        this.cdr.detectChanges();
      }, error: error => {
        this.eventgrp.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  eventgrpListFilter() {
    return this.eventgrp.dataList.filter(x => {
      const data = x.data
      const match = data.eventgrpId.toLowerCase().includes(this.eventgrpmodal.search.toLowerCase()) || data.tdesc.toLowerCase().includes(this.eventgrpmodal.search.toLowerCase()) || data.edesc.toLowerCase().includes(this.eventgrpmodal.search.toLowerCase());
      return match;
    })
  }
  selectEventgrp(data?: EventgrpModel) {
    if (!data) {
      this.pmsWorkingTime.select.emeventgrp.splice(this.eventgrp.selectIndex, 1);
      return;
    }
    this.pmsWorkingTime.select.emeventgrp.push(new MyEmeventgrpModel(data))
  }


  clearData(modalStatus: string) {
    if (modalStatus == 'add') {
      this.pmsWorkingTime.select = new MyPmsWorkingTimeModel()
    } else if (modalStatus == 'edit') {
      this.pmsWorkingTime.select = new MyPmsWorkingTimeModel({ pmsWorkingTimeId: this.pmsWorkingTime.select.pmsWorkingTimeId })
    }
    this.eventgrp.selectList = [new MyEventgrpModel()]
  }

  modalSearchChange(dataList: any) {
    this.modal.currentPage = 1
    this.modal.page = Array.from({ length: Math.ceil(dataList.length / 10) }, (_, i) => i + 1);
  }
  oneventgrpModalSearchChange() {
    this.eventgrpmodal.currentPage = 1
    this.eventgrpmodal.page = Array.from({ length: Math.ceil(this.eventgrpListFilter().length / 10) }, (_, i) => i + 1);
  }

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

  checkPrimary() {
    return this.pmsWorkingTime.dataList.find(x => x.pmsWorkingTimeId == this.pmsWorkingTime.select.pmsWorkingTimeId)
  }

  openDialog() {
    this.dialogRef = this.dialog.open(this.timeAttendanceModal, {
      width: '500px',
      disableClose: false,
    });
  }
  openEventgrpDialog() {
    this.dialogRefEventgrp = this.dialog.open(this.evenTgrpModal, {
      width: '800px',
    })
  }
  onSelectItemChange(arg: any) {
    this.selectedItems = arg
  }

  numSelectItem() {
    const selectedKeys = Array.from(this.selectedItems.data.keys());
    const num = this.pmsWorkingTime.dataList.filter(x => selectedKeys.includes(x.pmsWorkingTimeId) && this.selectedItems.data.get(x.pmsWorkingTimeId)).length
    return num
  }
  closeDialog() {
    this.dialogRef.close()
  }
  closeEventgrpDialog() {
    this.dialogRefEventgrp.close()
  }
}
