import { ChangeDetectorRef, Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { PmstopicModel, MyPmstopicModel } from 'src/app/shared/model/pmstopic.model';
import { MyPmstypeModel, PmstypeModel } from 'src/app/shared/model/pmstype.model';
import { FileService } from 'src/app/shared/services/file.service';
import { PmstopicService } from 'src/app/shared/services/pmstopic.service';
import { PmstypeService } from 'src/app/shared/services/pmstype.service';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { MatDialog } from '@angular/material/dialog';
import Swal from 'sweetalert2';
import { TranslateService } from '@ngx-translate/core';

interface table {
  currentPage: number,
  page: number[],
  search: string
  pageSize: number
}
@Component({
  selector: 'app-assessment-topics',
  templateUrl: './assessment-topics.component.html',
  styleUrls: ['./assessment-topics.component.scss']
})
export class AssessmentTopicsComponent {
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false
  pmstopic: { loading: boolean, select: PmstopicModel, completionDateIso: string, dataList: PmstopicModel[] } = { loading: false, select: new MyPmstopicModel(), completionDateIso: "", dataList: [] }
  pmstype: { loading: boolean, select: PmstypeModel, dataList: { check: boolean, data: PmstypeModel }[] } = { loading: false, select: new MyPmstypeModel(), dataList: [] }

  modal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }

  pmstypemodal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }

  modalStatus: "add" | "edit" | 'delete' = "add"



  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';
  columns: ColumnModel[] = [{
    field: "pmsTopicId",
    headerText: "Code",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "name",
    headerText: "TopicName",
    type: "string"
  },
  {
    field: "pmsType",
    headerText: "PmsTypes",
    type: "string"
  }]
  searchSettings = {
    fields: ['pmsTopicId', 'name', 'pmsType'],
    operator: 'contains',
    ignoreCase: false
  };

  syncfutionDataList: any[] = []
  search = ''
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  @ViewChild("assessmentTopicsModal") assessmentTopicsModal: any;
  @ViewChild("assessmentTopoicsTypeModal") assessmentTopoicsTypeModal: any;
  dialogRef: any
  dialogRefpmsType: any
  constructor(private cdr: ChangeDetectorRef,
    private pmstopicService: PmstopicService,
    private dialog: MatDialog,
    private toastr: ToastrService,
    private fileService: FileService,
    private pmstypeService: PmstypeService,
    private translateService: TranslateService
  ) {
    this.translateService.onLangChange.subscribe((event) => {
      this.setSyncfutionDataList()
    });

  }
  setSyncfutionDataList() {
    if (this.pmstopic.dataList) {
      this.syncfutionDataList = this.pmstopic.dataList.map(e => ({
        pmsTopicId: e.pmsTopicId,
        name: this.translateService.getCurrentLang() == 'th' ? e.tdesc : e.edesc,
        pmsType: e.pmsType.tdesc
      }))
    }
  }
  ngOnInit(): void {
    this.getPmstopicList()
    this.getPmstypeList()
  }
  getPmstypeList() {
    this.pmstype.loading = true
    this.pmstypeService.getList().subscribe({
      next: response => {
        this.pmstype.dataList = response.map(x => ({
          check: false,
          data: new MyPmstypeModel(x)
        }))
        this.pmstype.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.pmstype.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  pmstypeListFilter() {
    return this.pmstype.dataList.filter(x => {
      const data = x.data
      if (x.data.pmsTypeId != '06' && x.data.pmsTypeId != '07') {
        const match = data.pmsTypeId.toLowerCase().includes(this.pmstypemodal.search.toLowerCase()) ||
          data.tdesc.toLowerCase().includes(this.pmstypemodal.search.toLowerCase()) ||
          data.shortName.toLowerCase().includes(this.pmstypemodal.search.toLowerCase())
        return match
      }
      return
    })
  }
  selectPmstype(data?: PmstypeModel) {
    this.pmstopic.select.pmsType = new MyPmstypeModel(data)
  }

  getPmstopicList() {
    this.pmstopic.loading = true
    this.selectedItems.data.clear()
    this.pmstopicService.getList().subscribe({
      next: response => {
        this.pmstopic.dataList = response.map(x => {
          this.selectedItems.data.set(x.pmsTopicId, false)
          return new MyPmstopicModel(x)
        })
        this.selectedItems.key = 'pmsTopicId'
        this.selectedItems.count = 0
        this.pmstopic.loading = false
        this.setSyncfutionDataList()
        this.cdr.detectChanges()
      }, error: error => {
        this.pmstopic.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  selectPmstopic(dataSelect?: any) {
    const data = this.pmstopic.dataList.find(e => e.pmsTopicId == dataSelect.pmsTopicId)
    if (data) {
      this.pmstopic.select = new MyPmstopicModel(data)
    } else if (this.modalStatus == 'add') {
      this.pmstopic.select = new MyPmstopicModel()
    } else if (this.modalStatus == 'edit') {
      this.pmstopic.select = new MyPmstopicModel({ pmsTopicId: this.pmstopic.select.pmsTopicId })
    }
  }


  addpmsTopics() {
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'บันทึกข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        this.pmstopic.loading = true
        this.pmstopicService.post(this.pmstopic.select).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getPmstopicList()
              this.closeDialog()
            } else {
              this.showAlert(response.message, 'error')
              this.pmstopic.loading = false
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.pmstopic.loading = false
          }
        })
      }
    })
  }
  deletepmsTopics() {
    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.pmstopic.loading = true
        const selectedKeys = Array.from(this.selectedItems.data.keys());
        const body = this.pmstopic.dataList.filter(x => selectedKeys.includes(x.pmsTopicId) && this.selectedItems.data.get(x.pmsTopicId)).map(x => new MyPmstopicModel(x))
        this.pmstopicService.delete(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getPmstopicList()
              this.closeDialog()
            } else {
              this.showAlert(response.message, 'error')
              this.pmstopic.loading = false
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.pmstopic.loading = false
          }
        })
      }
    });
  }

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


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

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

  }


  clearPmstopic(modalStatus: string) {
    if (modalStatus == 'add') {
      this.selectPmstopic()
    } else if (modalStatus == 'edit') {
      this.selectPmstopic(new MyPmstopicModel({ pmsTopicId: this.pmstopic.select.pmsTopicId }))
    }
  }
  modalSearchChange(dataList: any) {
    this.modal.currentPage = 1
    this.modal.page = Array.from({ length: Math.ceil(dataList.length / 10) }, (_, i) => i + 1);
  }

  onpmsTypeModalSearchChange() {
    this.pmstypemodal.currentPage = 1
    this.pmstypemodal.page = Array.from({ length: Math.ceil(this.pmstypeListFilter().length / 10) }, (_, i) => i + 1);
  }

  changeDate(target: { [key: string]: any }, field: string, dateIso: string) {
    target[field] = this.toYYYYMMDD(dateIso)
  }
  toISODate(dateInput?: string | null): string {
    if (!dateInput) return "";
    const parsedDate = new Date(dateInput);
    return isNaN(parsedDate.getTime()) ? new Date().toISOString() : parsedDate.toISOString();
  }
  toYYYYMMDD(dateInput?: string | null): string {
    if (!dateInput) return "";
    const parsedDate = new Date(dateInput);
    const options: Intl.DateTimeFormatOptions = {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    };
    const formattedDate = parsedDate.toLocaleDateString('en-GB', options);
    const [day, month, year] = formattedDate.split('/');
    return `${year}-${month}-${day}`;
  }

  checkPrimary() {
    return this.pmstopic.dataList.find(x => x.pmsTopicId == this.pmstopic.select.pmsTopicId)
  }


  openDialog() {
    this.dialogRef = this.dialog.open(this.assessmentTopicsModal, {
      width: '500px',
      disableClose: false,
    });
  }
  openpmsTypeDialog() {
    this.dialogRefpmsType = this.dialog.open(this.assessmentTopoicsTypeModal, {
      width: '800px',
    })
  }
  closeDialog() {
    this.dialogRef.close()
  }
  closepmsTypeDialog() {
    this.dialogRefpmsType.close()
  }

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

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

}