import { ChangeDetectorRef, Component, Input, ViewChild, ViewEncapsulation } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { AggregateService, Column, ColumnMenuClickEventArgs, ColumnMenuService, ColumnModel, DetailRowService, EditService, ExcelExportProperties, ExcelExportService, FilterService, FilterSettingsModel, GridComponent, GroupService, GroupSettingsModel, LoadingIndicatorModel, PageService, PdfExportService, ReorderService, SearchService, SelectionSettingsModel, SortService, ToolbarService } from '@syncfusion/ej2-angular-grids';
import { setCulture } from '@syncfusion/ej2-base';
import { Query } from '@syncfusion/ej2-data';
import { MyAppraisalKpiSettingEmpModel } from 'src/app/shared/model/appraisal-kpi-setting-emp.model';
import { AppraisalKpiSettingModel, ApsassessyModel, MyAppraisalKpiSettingModel, MyApsassessyModel } from 'src/app/shared/model/appraisal-kpi-setting.model';
import { AppraisalSubordinateModel, Masfromevaluationassessment } from 'src/app/shared/model/appraisal-subordinate.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 { TokenService } from 'src/app/shared/services/token.service';
@Component({
  selector: 'app-setting-individual-kpi-supervisor',
  templateUrl: './setting-individual-kpi-supervisor.component.html',
  styleUrls: ['./setting-individual-kpi-supervisor.component.scss'],
  providers: [AggregateService, SortService, GroupService, ColumnMenuService, PageService, FilterService, ToolbarService, PdfExportService, ExcelExportService, DetailRowService, ReorderService, EditService, SearchService],
  encapsulation: ViewEncapsulation.None
})
export class SettingIndividualKpiSupervisorComponent {
  bossId = ''
  subordinate: { loading: false, select?: AppraisalKpiSettingModel, dataList: AppraisalKpiSettingModel[] } = { loading: false, select: undefined, dataList: [] }
  settingIndividualKpi = false
  search = ""
  selectEmp: Map<string, boolean> = new Map<string, boolean>()
  syncfution: {
    dataList: any[],
    searchSettings: {
      fields: string[],
      operator: 'contains',
      ignoreCase: false
    },
    columns: ColumnModel[]
  } = {
      dataList: [],
      searchSettings: {
        fields: [
          'employeeId',
          'fullName',
          'position',
          'status'],
        operator: 'contains',
        ignoreCase: false
      },
      columns: [{
        field: "employeeId",
        headerText: "EmployeeCode",
        type: "string",
        isPrimaryKey: true,
      },
      {
        field: "fullName",
        headerText: "EmployeeName",
        type: "string"
      },
      {
        field: "position",
        headerText: "Position",
        type: "string"
      },
      {
        field: "status",
        headerText: "Status",
        type: "string"
      }]
    }
  @ViewChild('grid') public grid?: GridComponent;
  filterSettings: FilterSettingsModel = { type: 'Excel' };
  selectionOptions: SelectionSettingsModel = { checkboxOnly: true };
  groupSettings: GroupSettingsModel = { allowReordering: true, showGroupedColumn: true, showDropArea: false };
  toolbarOptions: any[] = ['Print', 'ExcelExport', 'CsvExport'];
  editSettings? = { allowEditing: true, mode: 'Batch' };
  loadingIndicator: LoadingIndicatorModel = { indicatorType: 'Shimmer' };
  query: Query = new Query().addParams('dataCount', '1000');
  columnMenuItems: any[] = [
    'AutoFit', 'AutoFitAll', 'SortAscending', 'SortDescending',
    'Group', 'Ungroup', 'ColumnChooser', 'Filter',
    { text: 'Sum', id: 'aggregate_sum' },
    { text: 'Count', id: 'aggregate_count' },
    { text: 'Average', id: 'aggregate_average' },
    { text: 'Min', id: 'aggregate_min' },
    { text: 'Max', id: 'aggregate_max' }
  ];
  initialPage? = { pageSizes: true, pageSize: 10 };
  aggregatesSum: any[] = [];
  aggregatesCount: any[] = [];
  aggregatesAvg: any[] = [];
  aggregatesMin: any[] = [];
  aggregatesMax: any[] = [];
  locale = 'th-TH'
  constructor(private appraisalService: AppraisalService,
    private fileService: FileService,
    private translateService: TranslateService,
    private tokenService: TokenService,
    private cdr: ChangeDetectorRef) {

    this.locale = this.translateService.getCurrentLang() == 'th' ? 'th-TH' : 'en-US'

    this.translateService.onLangChange.subscribe((event) => {
      if (event.lang === 'th') {
        setCulture('th-TH');
        this.locale = 'th-TH'
      } else if (event.lang === 'en') {
        setCulture('en-US');
        this.locale = 'en-US'
      }
      this.toolbarOptions = [
        { text: this.translateService.instant('Print'), prefixIcon: 'e-print', id: 'Print' },
        { text: this.translateService.instant('ExcelExport'), prefixIcon: 'e-excelexport', id: 'ExcelExport' },
        { text: this.translateService.instant('CSVExport'), prefixIcon: 'e-csvexport', id: 'CsvExport' }
      ]
      this.setSyncfutionDataList()
      this.cdr.markForCheck()
    });
  }
  ngOnInit(): void {
    this.bossId = this.tokenService.getUserData().employeeId
    this.getEmpKpi()
  }
  getEmpKpi() {
    this.selectEmp.set('selectAll', false)
    this.syncfution.dataList = []
    this.appraisalService.getEmpKpi().subscribe({
      next: response => {
        this.subordinate.dataList = response.map(e => new MyAppraisalKpiSettingModel(e))
        this.setSyncfutionDataList()
        this.cdr.markForCheck()
      }, error: error => {
        this.cdr.markForCheck()
      }
    })
  }

  subordinateFilter() {
    return this.subordinate.dataList.filter(x => {
      return x.apsassessy.employeeId.toLowerCase().includes(this.search.toLowerCase()) ||
        x.apsassessy.thFullName.toLowerCase().includes(this.search.toLowerCase()) ||
        x.apsassessy.position.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
        x.apsassessy.position.edesc.toLowerCase().includes(this.search.toLowerCase()) ||
        x.statusApprove.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
        x.statusApprove.edesc.toLowerCase().includes(this.search.toLowerCase())
    })
  }

  setSyncfutionDataList() {
    this.syncfution.dataList = this.subordinateFilter().map(e => ({
      employeeId: e.apsassessy.employeeId,
      fullName: this.translateText(e.apsassessy.thFullName, e.apsassessy.engFullName),
      position: this.translateText(e.apsassessy.position.tdesc, e.apsassessy.position.edesc),
      status: this.translateText(e.statusApprove.tdesc, e.statusApprove.edesc),
      statusCode: e.statusApprove.code,
      statusEdesc: e.statusApprove.edesc,
      picture: e.apsassessy.picture
    }))
    this.checkSelectAll()
  }

  translateText(th?: string, en?: string) {
    return this.translateService.getCurrentLang() == 'th' ? (th || '') : (en || '')
  }


  statusCompetencyText = (status: string) => {
    if (status === "no access") {
      return "ยังไม่ถึงขั้นตอนดำเนินการ"
    } else if (status === "pending") {
      return "รอดำเนินการ"
    } else if (status === "evaluating") {
      return "อยู่ระหว่างดำเนินการ"
    } else if (status === "completed") {
      return "ดำเนินการเสร็จสิ้น"
    } else if (status === "rejected") {
      return "ส่งกลับ"
    } else {
      return ""
    }
  }
  statusButtonClass = (status: string) => {
    const text = status.toLowerCase().trim()
    if (text === "no access") {
      return "ti-btn-soft-mute"
    } else if (text === "pending") {
      return "ti-btn-soft-secondary"
    } else if (text === "evaluating") {
      return "ti-btn-soft-warning"
    } else if (text === "completed") {
      return "ti-btn-soft-success"
    } else if (text === "rejected") {
      return "ti-btn-soft-danger"
    } else {
      return ""
    }
  }

  getImg(text: string) {
    return this.fileService.getImg(text)
  }

  onImageError(event: Event) {
    const imgElement = event.target as HTMLImageElement;
    imgElement.src = './assets/img/users/defaultperson.jpg';
  }

  selectSubordinate(data: any) {
    this.subordinate.select = new MyAppraisalKpiSettingModel(this.subordinate.dataList.find(e => e.apsassessy.employeeId == data.employeeId))
    this.settingIndividualKpi = true
    this.cdr.markForCheck()
  }

  toggleSelectAll() {
    if (!this.selectEmp.get('selectAll')) {
      this.selectEmp.set('selectAll', true)
      this.syncfution.dataList.filter(e => e.statusCode == '1').forEach(e => {
        this.selectEmp.set(e.employeeId, true)
      })
    } else {
      this.selectEmp.set('selectAll', false)
      this.syncfution.dataList.filter(e => e.statusCode == '1').forEach(e => {
        this.selectEmp.set(e.employeeId, false)
      })
      this.selectEmp.clear()
    }
  }
  checkSelectAll() {
    this.selectEmp.set('selectAll', (this.syncfution.dataList.filter(e => e.statusCode == '1').length > 0 &&
      (this.selectEmp.size - 1) == this.syncfution.dataList.filter(e => e.statusCode == '1').length))
  }

  onColumnMenuClick(args: ColumnMenuClickEventArgs): void {
    if (!args.item.id) { return; }
    if (args.item.id.startsWith('aggregate_')) {
      const colField = (args.column as any)?.field;
      if (!colField) { return; }
      const selectedAgg = args.item.id.split('_')[1];
      if (selectedAgg === 'sum') {
        if (this.aggregatesSum.find(a => a.field === colField)) {
          this.aggregatesSum = this.aggregatesSum.filter(a => a.field !== colField);
        } else {
          this.aggregatesSum.push({
            field: colField,
            type: 'Sum',
            footerTemplate: 'Sum: ${Sum}'
          });
        }
        this.cdr.markForCheck()
      }
      else if (selectedAgg === 'count') {
        this.aggregatesCount.push({
          field: colField,
          type: 'Count',
          footerTemplate: 'Count: ${Count}'
        });
      } else if (selectedAgg === 'average') {
        this.aggregatesAvg.push({
          field: colField,
          type: 'Average',
          footerTemplate: 'Avg: ${Average}'
        });
      }
      else if (selectedAgg === 'min') {
        this.aggregatesMin.push({
          field: colField,
          type: 'Min',
          footerTemplate: 'Min: ${Min}'
        });
      }
      else if (selectedAgg === 'max') {
        this.aggregatesMax.push({
          field: colField,
          type: 'Max',
          footerTemplate: 'Max: ${Max}'
        });
      }
      setTimeout(() => {
        this.grid?.refresh();
      }, 500);
    }
  }

  toolbarClick(args: any): void {
    if (args.item.id === 'Grid_excelexport') {
      let exportProperties: ExcelExportProperties = {
        columns: this.syncfution.columns.map(col => ({
          field: col.field,
          headerText: col.headerText
        })) as Column[]
      };
      this.grid?.excelExport(exportProperties);
    } else if (args.item.id === 'Grid_csvexport') {
      let exportColumns = this.syncfution.columns.map(col => ({
        field: col.field || '',
        headerText: col.headerText || ''
      }));
      this.grid?.csvExport({ columns: exportColumns as Column[] });
    } else if (args.item.id === 'Grid_print') {
      this.cdr.markForCheck()
      setTimeout(() => {
        this.cdr.markForCheck()
      }, 1000)
    }
  }
}
