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 { CompetencyTopicModel } from 'src/app/shared/model/appraisal-aps.model';
import { CompetencytopicModel, MyCompetencytopicModel } from 'src/app/shared/model/competencytopic.model';
import { CompetencytypeModel, MyCompetencytypeModel } from 'src/app/shared/model/competencytype.model';
import { CompetencytopicService } from 'src/app/shared/services/competencytopic.service';
import { CompetencytypeService } from 'src/app/shared/services/competencytype.service';
import { FileService } from 'src/app/shared/services/file.service';
import Swal from 'sweetalert2';
import { data } from '../../../datagrid-syncfution/data';
import { TokenService } from 'src/app/shared/services/token.service';

interface table {
  currentPage: number,
  page: number[],
  search: string,
  pageSize: number
}
@Component({
  selector: 'app-competency-topic',
  templateUrl: './competency-topic.component.html',
  styleUrls: ['./competency-topic.component.scss']
})
export class CompetencyTopic implements OnInit {

  competencyTopic: { loading: boolean, select: CompetencytopicModel, dataList: CompetencytopicModel[] } = { loading: false, select: new MyCompetencytopicModel({}), dataList: [] }

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

  examFile: File | null = null;
  examFileName: string = 'กรุณาเลือกไฟล์';

  topicModal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }
  typeList: CompetencytypeModel[] = []
  type: CompetencytypeModel = new MyCompetencytypeModel()
  typeModal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }

  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);

  currentPageModal = 1
  pageModal = Array.from({ length: 1 }, (_, i) => i + 1);
  searchModal = ""

  currentModal: 'add' | 'edit' | 'delete' = 'add'
  competoncytopicList: CompetencytopicModel[] = [];
  competencytypeListLoading = false
  competoncy_type: CompetencytypeModel = new MyCompetencytypeModel({})
  competoncy_topic: CompetencytopicModel = new MyCompetencytopicModel({})



  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false

  columns: ColumnModel[] = [{
    field: "competencyTopicId",
    headerText: "CompetencyCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "CompetencyName",
    type: "string"
  },
  {
    field: "competencyType.shortName",
    headerText: "CompetencyType",
    type: "string"
  }]
  searchSettings = {
    fields: ['competencyTopicId', 'tdesc', 'competencyType.shortName'],
    operator: 'contains',
    ignoreCase: false
  };
  search = ''
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };

  @ViewChild("competencyTopicModal") competencyTopicModal: any;
  @ViewChild("competencyTypeTableModal") competencyTypeTableModal: any;
  @ViewChild("fileInputMedium") fileInputMedium: any;
  dialogRef: any
  dialogRefType: any

  constructor(private toastr: ToastrService,
    private dialog: MatDialog,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private competencytopicService: CompetencytopicService,
    private competencytypeService: CompetencytypeService,
    private tokenService: TokenService
  ) { }
  ngOnInit(): void {
    this.getCompetencytopicList()
    this.getCompetencytypeList()
  }

  onExamSelected(event: any) {
    this.examFile = event.target.files.length > 0 ? event.target.files[0] : null;
    this.examFileName = this.examFile?.name || "กรุณาเลือกไฟล์"
  }

  uploadExam() {
    if (!this.examFile) return;

    const formData = new FormData();
    formData.append('file', this.examFile);

    this.fileService.uploadFiles(formData).subscribe({
      next: response => {
        if (response.success) {
          this.examFile = null;
          this.addCompetency_topic(response.resultObject); // ส่งชื่อไฟล์เข้าฟังก์ชัน
        } else {
          this.showAlert(response.message, 'error');
          this.cdr.detectChanges();
        }
      },
      error: error => {
        this.showAlert(error.message, 'error');
        this.cdr.detectChanges();
      }
    });
  }



  downloadExam(fileName: string) {
    this.fileService.downloadFiles(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);
        this.cdr.detectChanges()
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.cdr.detectChanges()
      }
    })
  }

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

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

  }

  getCompetencytypeList() {
    this.competencytypeListLoading = true
    this.selectedItems.data.clear()
    this.competencytypeService.getList().subscribe({
      next: response => {
        this.typeList = response.map(x => {
          return new MyCompetencytypeModel(x)
        })
        this.competencytypeListLoading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.competencytypeListLoading = false
        this.cdr.detectChanges()
      }
    })
  }


  selectCompetencyTopic(CompetencyTopic?: CompetencyTopicModel) {
    if (CompetencyTopic) {
      this.competencyTopic.select = new MyCompetencytopicModel(CompetencyTopic)
    } else if (this.currentModal == 'add') {
      this.competencyTopic.select = new MyCompetencytopicModel({})
    } else if (this.currentModal == 'edit') {
      this.competencyTopic.select = new MyCompetencytopicModel({ competencyTopicId: this.competencyTopic.select.competencyTopicId })
    }
    this.examFileName = this.competencyTopic.select.competencyFiles || 'กรุณาเลือกไฟล์'
  }

  searchCompetencytypeChange() {
    this.typeModal.currentPage = 1
    this.typeModal.page = Array.from({ length: Math.ceil(this.competencytypeListFilter().length / 10) }, (_, i) => i + 1);
  }
  competencytypeListFilter() {
    return this.typeList.filter(x =>
      x.competencyTypeId.toLowerCase().includes(this.typeModal.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.typeModal.search.toLowerCase()) ||
      x.shortName.toLowerCase().includes(this.typeModal.search.toLowerCase()))
  }
  selectCompetencytype(data: CompetencytypeModel) {
    this.competencyTopic.select.competencyType = JSON.parse(JSON.stringify(data));
  }
  getCompetencytopicList() {
    this.competencyTopic.loading = true
    this.selectedItems.data.clear()
    this.competencytopicService.getList().subscribe({
      next: response => {
        this.competencyTopic.dataList = response.map(x => {
          this.selectedItems.data.set(x.competencyTopicId, false)
          return new MyCompetencytopicModel(x)
        })
        this.selectedItems.key = 'competencyTopicId'
        this.selectedItems.count = 0
        this.competencyTopic.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.competencyTopic.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  addCompetency_topic(competencyFiles?: string) {
    if (this.examFile) {
      this.uploadExam();
      return;
    }

    const user = this.tokenService.getUser();
    const body = new MyCompetencytopicModel({
      ...this.competencyTopic.select,
      companyId: user?.companyid,
      competencyFiles: competencyFiles || ((this.examFileName == this.competencyTopic.select.competencyFiles) ? this.competencyTopic.select.competencyFiles : '')
    });
    this.competencyTopic.loading = true;
    this.competencytopicService.post(body).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success');
          this.getCompetencytypeList();
          this.getCompetencytopicList();
          this.closeDialog()
        } else {
          this.showAlert(response.message, 'error');
          this.competencyTopic.loading = false;
          this.cdr.detectChanges();
        }
      },
      error: error => {
        this.showAlert(error.message, 'error');
        this.competencyTopic.loading = false;
        this.cdr.detectChanges();
      }
    });
  }

  confirmAddCompetency_topic() {
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'บันทึกข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then(result => {
      if (result.isConfirmed) {
        this.addCompetency_topic();
      }
    });
  }

  deleteCompetency_topic() {
    if (!this.numSelectItem()) {
      this.showAlert('กรุณาเลือกข้อมูลที่ต้องการลบ', 'error');
      return;
    }

    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการลบข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'ลบข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then(result => {
      if (result.isConfirmed) {
        let body: MyCompetencytopicModel[] = [];

        if (this.currentModal === "delete") {
          const selectedKeys = Array.from(this.selectedItems.data.keys());
          body = this.competencyTopic.dataList
            .filter(x => selectedKeys.includes(x.competencyTopicId) && this.selectedItems.data.get(x.competencyTopicId))
            .map(x => new MyCompetencytopicModel(x));
        }
        this.competencyTopic.loading = true;
        this.competencytopicService.delete(body).subscribe({
          next: response => {
            this.competencyTopic.loading = false;
            if (response.success) {
              this.showAlert(response.message, 'success');
              this.getCompetencytypeList();
              this.getCompetencytopicList();
            } else {
              this.showAlert(response.message, 'error');
              this.cdr.detectChanges();
            }
          },
          error: error => {
            this.competencyTopic.loading = false;
            this.showAlert(error.message, 'error');
            this.cdr.detectChanges();
          }
        });
      }
    });
  }


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

  checkPrimary() {
    return this.competencyTopic.dataList.find(x => x.competencyTopicId == this.competencyTopic.select.competencyTopicId)
  }

  numSelectItem() {
    const selectedKeys = Array.from(this.selectedItems.data.keys());
    const num = selectedKeys.filter(key => this.selectedItems.data.get(key)).length;
    return num;
  }

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

  openDialog() {
    this.dialogRef = this.dialog.open(this.competencyTopicModal, {
      width: '500px',
      disableClose: false,
    });
  }
  openDialogType() {
    this.fileInputMedium.value = ""
    this.dialogRefType = this.dialog.open(this.competencyTypeTableModal, {
      width: '800px',
      disableClose: false,
    })
  }
  closeDialog() {
    this.dialogRef.close()
  }
  closeDialogType() {
    this.dialogRefType.close()
  }
}
