import { ChangeDetectorRef, Component, EventEmitter, Input, Output, SimpleChanges, ViewChild } from "@angular/core";
import { MatDialog, MatDialogRef } from "@angular/material/dialog";
import { Router, ActivatedRoute } from "@angular/router";
import { TranslateService } from "@ngx-translate/core";
import { AppraisalKpiSettingEmpModel, MyAppraisalKpiSettingEmpModel, MyPmsTypeModel, MyTopicModel, PmsTypeModel, TopicModel } from "src/app/shared/model/appraisal-kpi-setting-emp.model";
import { EmployeeModel, MyEmployeeModel } from "src/app/shared/model/employee.model";
import { AppraisalService } from "src/app/shared/services/appraisal.service";
import { EmployeeService } from "src/app/shared/services/employee.service";
import { FileService } from "src/app/shared/services/file.service";
import { PmstypeService } from "src/app/shared/services/pmstype.service";
import { TokenService } from "src/app/shared/services/token.service";
import { ToastrService } from 'ngx-toastr';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-setting-individual-kpi',
  templateUrl: './setting-individual-kpi.component.html',
  styleUrls: ['./setting-individual-kpi.component.scss']
})
export class SettingIndividualKpiComponent {
  @Input() bossId = ""
  @Input() employeeId = this.tokenService.getUserData().employeeId
  @Output() sendReturnPath: EventEmitter<any> = new EventEmitter<any>();
  menuClose: Map<string, boolean> = new Map<string, boolean>()
  tableHover: Map<string, boolean> = new Map<string, boolean>()
  pmsTopicApprove: Map<string, boolean> = new Map<string, boolean>()
  employee: { loading: boolean, data: EmployeeModel } = { loading: false, data: new MyEmployeeModel() }
  appraisalKpiSettingEmp: { loading: boolean, select: AppraisalKpiSettingEmpModel, list: AppraisalKpiSettingEmpModel[] } = { loading: false, select: new MyAppraisalKpiSettingEmpModel(), list: [] }
  @ViewChild("pmsTopicDialog") pmsTopicDialog: any
  pmsTopicDialogRef?: MatDialogRef<unknown, any>
  pmsTopic: { loading: boolean, select: TopicModel, list: TopicModel[] } = { loading: false, select: new MyTopicModel(), list: [] }

  @ViewChild("pmsTopicTableDialog") pmsTopicTableDialog: any
  pmsTopicTableDialogRef?: MatDialogRef<unknown, any>
  syncfutionPmsTopic = {
    list: [] as any,
    columns: [{
      field: "pmsTopicId",
      headerText: "Code",
      type: "string",
      isPrimaryKey: true,
    },
    {
      field: "name",
      headerText: "TopicName",
      type: "string"
    },
    {
      field: "pmsType",
      headerText: "PmsTypes",
      type: "string"
    }],
    search: '',
    searchSettings: {
      fields: ['pmsTopicId', 'name', 'pmsType'],
      operator: 'contains',
      ignoreCase: false
    }
  }
  pmsType: { loading: boolean, list: PmsTypeModel[] } = { loading: false, list: [] }
  @ViewChild("pmsTypeTableDialog") pmsTypeTableDialog: any
  pmsTypeTableDialogRef?: MatDialogRef<unknown, any>
  syncfutionPmsType = {
    list: [] as any,
    columns: [{
      field: "pmsTypeId",
      headerText: "Code",
      type: "string",
      isPrimaryKey: true,
    },
    {
      field: "name",
      headerText: "TopicName",
      type: "string"
    },
    {
      field: "shortName",
      headerText: "Abbreviations",
      type: "string"
    }],
    search: '',
    searchSettings: {
      fields: ['pmsTypeId', 'name', 'shortName'],
      operator: 'contains',
      ignoreCase: false
    }
  }
  lastConfirmBySelf = false

  constructor(
    private toastr: ToastrService,
    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 pmsTypeService: PmstypeService,
    private translateService: TranslateService
  ) {
    this.translateService.onLangChange.subscribe((event) => {
      this.setSyncfutionPmsTopic()
      this.setSyncfutionPmsType()
    });
  }

  ngOnInit(): void {
    this.getPmsTopicList()
    this.getPmsTypeList()
    this.getWorkingById()
    this.getEmpPmsKpi()
  }


  returnPath() {
    this.sendReturnPath.emit()
  }

  getWorkingById() {
    this.employee.loading = true
    this.employeeService.getWorkingById(this.employeeId).subscribe({
      next: response => {
        this.employee.data = new MyEmployeeModel(response)
        this.employee.loading = false
        this.cdr.markForCheck()
      }, error: error => {
        this.employee.loading = false
        this.cdr.markForCheck()
      }
    })
  }

  getImg(text: string) {
    return this.fileService.getImg(text)
  }
  onImageError(event: Event) {
    const imgElement = event.target as HTMLImageElement;
    imgElement.src = './assets/img/users/defaultperson.jpg';
  }
  translateText(th?: string, en?: string) {
    return this.translateService.getCurrentLang() == 'th' ? (th || '') : (en || '')
  }
  getEmpPmsKpi() {
    this.appraisalKpiSettingEmp.loading = true
    this.appraisalService.getEmpPmsKpi(this.employeeId, this.bossId).subscribe({
      next: response => {
        this.appraisalKpiSettingEmp.list = response.map(e => new MyAppraisalKpiSettingEmpModel(e))
        this.selectAppraisalKpiSettingEmp(this.appraisalKpiSettingEmp.list[0])
        if (this.appraisalKpiSettingEmp.select.statusAll.code == '1') {
          this.appraisalKpiSettingEmp.select.currentTopic.forEach(e => {
            if (e.approveTopicStatus != 2)
              this.pmsTopicApprove.set(e.pmsTopicId, true)
          })
        }
        if ((this.bossId && this.appraisalKpiSettingEmp.select.confirmBy == 'boss') ||
          (!this.bossId && this.appraisalKpiSettingEmp.select.confirmBy != 'boss')) {
          this.lastConfirmBySelf = true
        }
        this.appraisalKpiSettingEmp.loading = false
        this.cdr.markForCheck()
      }, error: error => {
        this.appraisalKpiSettingEmp.loading = false
        this.cdr.markForCheck()
      }
    })
  }
  selectAppraisalKpiSettingEmp(data?: AppraisalKpiSettingEmpModel) {
    this.appraisalKpiSettingEmp.select = new MyAppraisalKpiSettingEmpModel(data)
  }
  currentTopicFilter() {
    return this.appraisalKpiSettingEmp.select.currentTopic.filter(e => e.approveTopicStatus != 0)
  }

  currentTopicColor(approveTopicStatus: number): string {
    switch (approveTopicStatus) {
      case 0:
        return '#fb923c52';
      case 1:
        return '#2564eb4f';
      case 2:
        return '#ffffff';
      default:
        return '';
    }
  }
  getPmsTopicList() {
    this.pmsTopic.loading = true
    this.appraisalService.getKpi().subscribe({
      next: response => {
        this.pmsTopic.list = response.map(x => new MyTopicModel(x))
        this.pmsTopic.loading = false
        this.cdr.markForCheck()
      }, error: error => {
        this.pmsTopic.loading = false
        this.cdr.markForCheck()
      }
    })
  }
  pmsTopicFilter() {
    return this.pmsTopic.list.filter(b => !this.currentTopicFilter().some(a => a.pmsTopicId === b.pmsTopicId));
  }
  selectPmsTopic(data?: any) {
    this.pmsTopic.select = new MyTopicModel(this.pmsTopicFilter().find(e => e.pmsTopicId == data?.pmsTopicId))
    this.cdr.markForCheck()
  }
  pmsTopicDialogOpen() {
    this.selectPmsTopic()
    this.pmsTopicDialogRef = this.dialog.open(this.pmsTopicDialog, {
      width: '50vw',
      disableClose: false,
    });
  }
  pmsTopicDialogClose() {
    this.pmsTopicDialogRef?.close()
  }
  pmsTopicTableDialogOpen() {
    this.setSyncfutionPmsTopic()
    this.pmsTopicTableDialogRef = this.dialog.open(this.pmsTopicTableDialog, {
      width: '50vw',
      disableClose: false,
    });
  }
  pmsTopicTableDialogClose() {
    this.pmsTopicTableDialogRef?.close()
  }
  setSyncfutionPmsTopic() {
    this.syncfutionPmsTopic.list = this.pmsTopicFilter().map(e => ({
      pmsTopicId: e.pmsTopicId,
      name: this.translateText(e.tdesc, e.edesc),
      pmsType: this.translateText(e.pmsType?.tdesc, e.pmsType?.edesc)
    }))
  }
  addPmsTopic(pmsTopicId?: string) {
    const currentTopics = this.appraisalKpiSettingEmp.select.currentTopic;
    const selectedTopicId = pmsTopicId || this.pmsTopic.select.pmsTopicId;
    const index = currentTopics.findIndex(t => t.pmsTopicId === selectedTopicId);
    if (index > -1 && selectedTopicId) {
      currentTopics[index].approveTopicStatus = 2;
    } else {
      currentTopics.push({ ...this.pmsTopic.select, approveTopicStatus: 1 });
    }
    this.setSyncfutionPmsTopic()
    this.cdr.markForCheck()
  }
  deletePmsTopic(index: number) {
    const currentTopics = this.appraisalKpiSettingEmp.select.currentTopic;
    if (currentTopics[index].approveTopicStatus === 1) {
      currentTopics.splice(index, 1);
    } else if (index > -1) {
      currentTopics[index].approveTopicStatus = 0;
    }
    this.cdr.markForCheck()
  }


  getPmsTypeList() {
    this.pmsType.loading = true
    this.pmsTypeService.getList().subscribe({
      next: response => {
        this.pmsType.list = response.map(x => new MyPmsTypeModel(x))
        this.setSyncfutionPmsType()
        this.pmsType.loading = false
        this.cdr.markForCheck()
      }, error: error => {
        this.pmsType.loading = false
        this.cdr.markForCheck()
      }
    })
  }
  selectPmsType(data?: any) {
    this.pmsTopic.select.pmsType = new MyPmsTypeModel(this.pmsType.list.find(e => e.pmsTypeId == data?.pmsTypeId))
    this.cdr.markForCheck()
  }
  pmsTypeTableDialogOpen() {
    this.pmsTypeTableDialogRef = this.dialog.open(this.pmsTypeTableDialog, {
      width: '50vw',
      disableClose: false,
    });
  }
  pmsTypeTableDialogClose() {
    this.pmsTypeTableDialogRef?.close()
  }
  setSyncfutionPmsType() {
    this.syncfutionPmsType.list = this.pmsType.list.map(e => ({
      pmsTypeId: e.pmsTypeId,
      name: this.translateText(e.tdesc, e.edesc),
      shortName: e.shortName
    }))
  }


  savePmsTopic() {
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'บันทึกข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      this.appraisalKpiSettingEmp.select.currentTopic.forEach(obj => {
        if (obj.approveTopicStatus != 2) {
          obj.createStatusBy = this.bossId ? 'boss' : 'employee';
        }
      });
      this.appraisalService.postEmpPmsKpi(new MyAppraisalKpiSettingEmpModel(this.appraisalKpiSettingEmp.select)).subscribe({
        next: response => {
          if (response.success) {
            this.getEmpPmsKpi()
            this.showAlert(response.message, 'success')
          } else {
            this.showAlert(response.message, 'error')
          }
        }, error: error => {
          this.showAlert(error.message, 'error')
        }
      })
    })
  }
  approvePmsTopic() {
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการอนุมัติข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'อนุมัติข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      this.appraisalKpiSettingEmp.select.currentTopic.forEach(obj => {
        if (this.pmsTopicApprove.get(obj.pmsTopicId)) {
          if (obj.approveTopicStatus == 1) {
            obj.approveTopicStatus = 2
          }
          if (obj.approveTopicStatus == 0) {
            obj.approveTopicStatus = 0
          }
        } else {
          if (obj.approveTopicStatus != 2) {
            obj.approveTopicStatus = 3
          }
        }
      })
      this.appraisalService.postEmpPmsKpiApprove(new MyAppraisalKpiSettingEmpModel(this.appraisalKpiSettingEmp.select)).subscribe({
        next: response => {
          if (response.success) {
            this.getEmpPmsKpi()
            this.showAlert(response.message, 'success')
          } else {
            this.showAlert(response.message, 'error')
          }
        }, error: error => {
          this.showAlert(error.message, 'error')
        }
      })
    });
  }
  showAlert(text: string, type: 'success' | 'error') {
    this.toastr[type](text, 'แจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    });
  }
}
