import { ViewportScroller } from '@angular/common';
import { ChangeDetectorRef, Component, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { AggregateService, ColumnMenuService, DetailRowService, EditService, ExcelExportService, FilterService, GridComponent, GroupService, PageService, PdfExportService, ReorderService, SearchService, SortService, ToolbarService } from '@syncfusion/ej2-angular-grids';
import { Column, ColumnMenuClickEventArgs, ColumnModel, ExcelExportProperties, FilterSettingsModel, GroupSettingsModel, LoadingIndicatorModel, SelectionSettingsModel } from '@syncfusion/ej2-grids';
import { ToastrService } from 'ngx-toastr';
import { EmployeeModel, MyEmployeeModel } from 'src/app/shared/model/employee.model';
import { JobCodeModel, MyJobCodeModel } from 'src/app/shared/model/job-code.model';
import { MyStatusModel, StatusModel } from 'src/app/shared/model/status.model';
import { EmpStatusService } from 'src/app/shared/services/emp-status.service';
import { EmployeeService } from 'src/app/shared/services/employee.service';
import { EventgrpService } from 'src/app/shared/services/eventgrp.service';
import { FileService } from 'src/app/shared/services/file.service';
import { JobcodeService } from 'src/app/shared/services/jobcode.service';
import { PmsWorkingTimeService } from 'src/app/shared/services/pms-working-time.service';
import Swal from 'sweetalert2';
import { Query } from '@syncfusion/ej2-data';
import { setCulture } from '@syncfusion/ej2-base';
import { AppraisalService } from 'src/app/shared/services/appraisal.service';
import { TokenService } from 'src/app/shared/services/token.service';
export interface BiModel {
  name: string,
  tools: string[],
  degree: string
}

@Component({
  selector: 'app-review-history',
  templateUrl: './review-history.component.html',
  providers: [AggregateService, SortService, GroupService, ColumnMenuService, PageService, FilterService, ToolbarService, PdfExportService, ExcelExportService, DetailRowService, ReorderService, EditService, SearchService],
  styleUrls: ['./review-history.component.scss']
})
export class ReviewHistoryComponent {
  page = 1
  search = ''
  syncfution: {
    dataList: any[],
    searchSettings: {
      fields: string[],
      operator: 'contains',
      ignoreCase: false
    },
    columns: ColumnModel[]
  } = {
      dataList: [],
      searchSettings: {
        fields: [
          'no',
          'name',
          'round',
          'year',
          'score',
          'grade'
        ],
        operator: 'contains',
        ignoreCase: false
      },
      columns: [{
        field: "no",
        headerText: "ลำดับ",
        type: "string",
        isPrimaryKey: true,
      },
      {
        field: "name",
        headerText: "ผู้รับการประเมิน",
        type: "string"
      },
      {
        field: "round",
        headerText: "รอบการประเมิน",
        type: "string"
      },
      {
        field: "year",
        headerText: "ปีการประเมิน",
        type: "string"
      },
      {
        field: "score",
        headerText: "คะแนน",
        type: "string"
      },
      {
        field: "grade",
        headerText: "เกรด",
        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'


  evaluaterId = ''
  constructor(private appraisalService: AppraisalService,
    private fileService: FileService,
    private translateService: TranslateService,
    private tokenService: TokenService,
    private dialog: MatDialog,
    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.evaluaterId = this.decodeJWT(sessionStorage.getItem("accessToken") || '').employeeid
    this.getEmpKpi()
  }

  getEmpKpi() {
    this.syncfution.dataList = []
    this.setSyncfutionDataList()
    // 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()
    //   }
    // })
  }

  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.syncfution.dataList = this.dataFilter().map(e => ({
      no: e,
      name: e,
      round: e,
      year: e,
      score: e,
      grade: e,
    }))
  }
  dataFilter() {
    return [1, 2, 3, 4].filter(x => {
      return (x + '').toLowerCase().includes(this.search.toLowerCase())
    })
  }

  decodeJWT(token: string) {
    let base64Url = token.split('.')[1];
    let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    let jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
    return JSON.parse(jsonPayload);
  }

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

  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)
    }
  }
}