import { ChangeDetectorRef, Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { Router, ActivatedRoute } from '@angular/router';
import { CompetencytopicModel, MyCompetencytopicModel } from 'src/app/shared/model/competencytopic.model';
import { CompetencytypeModel, MyCompetencytypeModel } from 'src/app/shared/model/competencytype.model';
import { EmployeeModel, MyEmployeeModel } from 'src/app/shared/model/employee.model';
import { MyPmsGroupAssessment1Model } from 'src/app/shared/model/pms-group-assessment1.model';
import { MyPmstopicModel, PmstopicModel } from 'src/app/shared/model/pmstopic.model';
import { AppraisalService } from 'src/app/shared/services/appraisal.service';
import { CompetencytopicService } from 'src/app/shared/services/competencytopic.service';
import { CompetencytypeService } from 'src/app/shared/services/competencytype.service';
import { EmployeeService } from 'src/app/shared/services/employee.service';
import { FileService } from 'src/app/shared/services/file.service';
import { PmstopicService } from 'src/app/shared/services/pmstopic.service';
import { TokenService } from 'src/app/shared/services/token.service';
import Swal from 'sweetalert2';
export interface ModalData {
  search: string,
  currentPage: number,
  pageSize: number
}
@Component({
  selector: 'app-setting-individual-kpi',
  templateUrl: './setting-individual-kpi.component.html',
  styleUrls: ['./setting-individual-kpi.component.scss']
})
export class SettingIndividualKpiComponent {
  @Input() evaluateeId = ""
  @Input() evaluationForm: 'self' | 'sup' = "self"
  @Output() sendReturnPath: EventEmitter<any> = new EventEmitter<any>();
  @ViewChild("assessmentDialog") assessmentDialog: any;
  @ViewChild("competencyTypeDialog") competencyTypeDialog: any;
  @ViewChild("competencyTopicDialog") competencyTopicDialog: any;
  @ViewChild("fileInputMedium") fileInputMedium: any;
  examFile: File | null = null;
  examFileName: string = 'กรุณาเลือกไฟล์';
  assessmentDialogRef?: MatDialogRef<unknown, any>
  competencyTypeDialogRef?: MatDialogRef<unknown, any>
  competencyTopicDialogRef?: MatDialogRef<unknown, any>
  competencytype: { loading: boolean, select: CompetencytypeModel, dataList: CompetencytypeModel[] } = { loading: false, select: new MyCompetencytypeModel({}), dataList: [] }
  competencyTopic: { loading: boolean, select: CompetencytopicModel, dataList: CompetencytopicModel[] } = { loading: false, select: new MyCompetencytopicModel({}), dataList: [] }
  evaluatee: { loading: boolean, data: EmployeeModel } = { loading: false, data: new MyEmployeeModel() }
  pmstopic: { loading: boolean, select: PmstopicModel, dataList: { check: boolean, data: PmstopicModel }[] } = { loading: false, select: new MyPmstopicModel(), dataList: [] }
  individualKPI: { loading: boolean, list: any[] } = { loading: false, list: [] }
  menuClose: Map<string, boolean> = new Map<string, boolean>()
  tableHover: Map<string, boolean> = new Map<string, boolean>()
  modalData: ModalData = {
    search: "",
    currentPage: 1,
    pageSize: 10
  }
  constructor(
    private dialog: MatDialog,
    private router: Router,
    private employeeService: EmployeeService,
    private appraisalService: AppraisalService,
    private cdr: ChangeDetectorRef,
    private tokenService: TokenService,
    private route: ActivatedRoute,
    private fileService: FileService,
    private pmstopicService: PmstopicService,
    private competencytopicService: CompetencytopicService,
    private competencytypeService: CompetencytypeService
  ) { }

  ngOnInit(): void {
    this.getEvaluatee()
    this.getPmstopicList()
    this.getCompetencytypeList()
  }

  getCompetencytypeList() {
    this.competencytype.loading = true
    this.competencytypeService.getList().subscribe({
      next: response => {
        this.competencytype.dataList = response.map(x => {
          return new MyCompetencytypeModel(x)
        })
        this.competencytype.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.competencytype.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  competencytypeListFilter() {
    return this.competencytype.dataList.filter(x =>
      x.competencyTypeId.toLowerCase().includes(this.modalData.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.modalData.search.toLowerCase()) ||
      x.shortName.toLowerCase().includes(this.modalData.search.toLowerCase()))
  }
  selectCompetencytype(data?: CompetencytypeModel) {
    this.competencyTopic.select.competencyType = new MyCompetencytypeModel(data)
    this.cdr.markForCheck()
    this.competencyTypeDialogClose()
  }
  getPmstopicList() {
    this.pmstopic.loading = true
    this.pmstopicService.getList().subscribe({
      next: response => {
        this.pmstopic.dataList = response.map(x => ({ check: false, data: new MyPmstopicModel(x) }))
        this.pmstopic.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.pmstopic.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  pmstopicListFilter() {
    return this.pmstopic.dataList.filter(x => {
      const data = x.data
      const match = data.pmsTopicId.toLowerCase().includes(this.modalData.search.toLowerCase()) ||
        data.tdesc.toLowerCase().includes(this.modalData.search.toLowerCase()) ||
        data.pmsType.tdesc.toLowerCase().includes(this.modalData.search.toLowerCase()) ||
        (data.weight + "").toLowerCase().includes(this.modalData.search.toLowerCase())
      return match
    })
  }
  selectPmstopic(data?: PmstopicModel) {
    this.cdr.markForCheck()
  }

  assessmentDialogOpen() {
    this.modalData.search = ''
    this.modalData.currentPage = 1
    this.modalData.pageSize = 10
    this.assessmentDialogRef = this.dialog.open(this.assessmentDialog, {
      width: '80vw',
      disableClose: false,
    });
  }
  assessmentDialogClose() {
    this.assessmentDialogRef?.close()
  }
  competencyTypeDialogOpen() {
    this.modalData.search = ''
    this.modalData.currentPage = 1
    this.modalData.pageSize = 10
    this.competencyTypeDialogRef = this.dialog.open(this.competencyTypeDialog, {
      width: '80vw',
      disableClose: false,
    });
  }
  competencyTypeDialogClose() {
    this.competencyTypeDialogRef?.close()
  }
  competencyTopicDialogOpen() {
    if (this.fileInputMedium) {
      this.fileInputMedium.value = ""
    }
    this.competencyTopicDialogRef = this.dialog.open(this.competencyTopicDialog, {
      width: '50vw',
      disableClose: false,
    });
  }
  competencyTopicDialogClose() {
    this.competencyTypeDialogRef?.close()
  }
  getEvaluatee() {
    this.evaluatee.loading = true
    this.employeeService.getWorkingById(this.evaluateeId).subscribe({
      next: response => {
        this.evaluatee.data = new MyEmployeeModel(response)
        this.evaluatee.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.evaluatee.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  getImg(text: string) {
    return this.fileService.getImg(text)
  }
  onImageError(event: Event) {
    const imgElement = event.target as HTMLImageElement;
    imgElement.src = './assets/img/users/defaultperson.jpg';
  }
  returnPath() {
    this.sendReturnPath.emit()
  }
  onExamSelected(event: any) {
    this.examFile = event.target.files.length > 0 ? event.target.files[0] : null;
    this.examFileName = this.examFile?.name || "กรุณาเลือกไฟล์"
  }
  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()
      }
    })
  }
  showAlert(text: string, type: 'success' | 'error') {
    Swal.fire({
      title: 'แจ้งเตือน',
      text: text,
      icon: type,
      confirmButtonText: 'ตกลง',
    });
  }
  confirmCompetencyTopic() {
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'บันทึกข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then(result => {
      if (result.isConfirmed) {
        this.addCompetencyTopic();
      }
    });
  }
  addCompetencyTopic(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.competencyTopicDialogClose()
        } 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();
      }
    });
  }
  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.addCompetencyTopic(response.resultObject);
        } else {
          this.showAlert(response.message, 'error');
          this.cdr.detectChanges();
        }
      },
      error: error => {
        this.showAlert(error.message, 'error');
        this.cdr.detectChanges();
      }
    });
  }

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

  // @ViewChild("addKpiDialog") addKpiDialog: any;
  // addKpiDialogRef: any
  // @ViewChild("competencyTypeTableDialog") competencyTypeTableDialog: any;
  // competencyTypeTableDialogRef: any
  // @ViewChild("fileInputMedium") fileInputMedium: any;
  // examFile: File | null = null;
  // examFileName: string = 'กรุณาเลือกไฟล์';
  // typeModal: table = {
  //   currentPage: 1,
  //   page: Array.from({ length: 1 }, (_, i) => i + 1),
  //   search: "",
  //   pageSize: 10
  // }
  // constructor(
  //   private dialog: MatDialog,
  //   private router: Router,
  //   private employeeService: EmployeeService,
  //   private appraisalService: AppraisalService,
  //   private cdr: ChangeDetectorRef,
  //   private tokenService: TokenService,
  //   private route: ActivatedRoute,
  //   private fileService: FileService,
  //   private pmstopicService: PmstopicService,
  //   private competencytopicService: CompetencytopicService,
  //   private competencytypeService: CompetencytypeService
  // ) {
  // }

  // getCompetencytypeList() {
  //   this.competencytype.loading = true
  //   this.competencytypeService.getList().subscribe({
  //     next: response => {
  //       this.competencytype.dataList = response.map(x => {
  //         return new MyCompetencytypeModel(x)
  //       })
  //       this.competencytype.loading = false
  //       this.cdr.detectChanges()
  //     }, error: error => {
  //       this.competencytype.loading = false
  //       this.cdr.detectChanges()
  //     }
  //   })
  // }






  // selectPmstopic(data?: PmstopicModel) {
  //   this.cdr.markForCheck()
  // }
  // searchCompetencytypeChange() {
  //   this.typeModal.currentPage = 1
  //   this.typeModal.page = Array.from({ length: Math.ceil(this.competencytypeListFilter().length / 10) }, (_, i) => i + 1);
  // }

  // openAddKpiDialog() {
  //   this.addKpiDialogRef = this.dialog.open(this.addKpiDialog, {
  //     width: '500px',
  //     disableClose: false,
  //   });
  // }
  // openCompetencyTypeTableDialog() {
  //   this.competencyTypeTableDialogRef = this.dialog.open(this.competencyTypeTableDialog, {
  //     width: '500px',
  //     disableClose: false,
  //   });
  // }
  // showAlert(text: string, type: 'success' | 'error') {
  //   Swal.fire({
  //     title: 'แจ้งเตือน',
  //     text: text,
  //     icon: type,
  //     confirmButtonText: 'ตกลง',
  //   });
  // }
  // onExamSelected(event: any) {
  //   this.examFile = event.target.files.length > 0 ? event.target.files[0] : null;
  //   this.examFileName = this.examFile?.name || "กรุณาเลือกไฟล์"
  // }
  // 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()
  //     }
  //   })
  // }
  // confirmAddCompetency_topic() {
  //   Swal.fire({
  //     icon: 'question',
  //     title: 'แจ้งเตือน',
  //     text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
  //     showCancelButton: true,
  //     confirmButtonText: 'บันทึกข้อมูล',
  //     cancelButtonText: 'ย้อนกลับ',
  //     reverseButtons: true,
  //   }).then(result => {
  //     if (result.isConfirmed) {
  //       this.addCompetency_topic();
  //     }
  //   });
  // }
  // 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.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();
  //     }
  //   });
  // }

  // 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();
  //     }
  //   });
  // }
  // selectCompetencytype(data: CompetencytypeModel) {
  //   this.competencyTopic.select.competencyType = JSON.parse(JSON.stringify(data));
  // }
}
