import { ChangeDetectorRef, Component, ElementRef, 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';
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 { Query } from '@syncfusion/ej2-data';
import { setCulture } from '@syncfusion/ej2-base';
@Component({
  selector: 'app-gap-tracking-supervisor',
  templateUrl: './gap-tracking-supervisor.component.html',
  providers: [AggregateService, SortService, GroupService, ColumnMenuService, PageService, FilterService, ToolbarService, PdfExportService, ExcelExportService, DetailRowService, ReorderService, EditService, SearchService],
  styleUrls: ['./gap-tracking-supervisor.component.scss']
})
export class GapTrackingSupervisorComponent {
  search = ''
  syncfution: {
    dataList: any[],
    searchSettings: {
      fields: string[],
      operator: 'contains',
      ignoreCase: false
    },
    columns: ColumnModel[]
  } = {
      dataList: [],
      searchSettings: {
        fields: ['employeeId', 'name', 'status', 'gap'],
        operator: 'contains',
        ignoreCase: false
      },
      columns: [{
        field: "employeeId",
        headerText: "EmployeeCode",
        type: "string",
        isPrimaryKey: true,
      },
      {
        field: "name",
        headerText: "EmployeeName",
        type: "string"
      },
      {
        field: "status",
        headerText: "AppraiserStatus",
        type: "string"
      },
      {
        field: "gap",
        headerText: "Gap 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'

  @ViewChild('gapDialog') gapDialog: any
  gapDialogRef: any
  evaluaterId = ''

  @ViewChild("fileInputMedium") fileInputMedium: any;
  selectedFile: File | null = null;
  selectedFileName: string = 'PleaseSelectFile';


  subordinate: { loading: boolean, select: EmployeeModel, list: EmployeeModel[] } = { loading: false, select: new MyEmployeeModel(), list: [] }
  selectEmp: Map<string, boolean> = new Map<string, boolean>()
  constructor(private appraisalService: AppraisalService,
    private fileService: FileService,
    private translateService: TranslateService,
    private tokenService: TokenService,
    private dialog: MatDialog,
    private employeeService: EmployeeService,
    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.getEmpList()
  }

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


  openGapDialog() {
    this.gapDialogRef = this.dialog.open(this.gapDialog, {
      width: '1000px',
    })
  }
  closeGapDialog() {
    this.gapDialogRef.close()
  }


  getEmpList() {
    this.subordinate.loading = true
    this.selectEmp.clear()
    this.employeeService.getList().subscribe({
      next: response => {
        this.subordinate.list = response.map((x: any) => new MyEmployeeModel(x))
        this.subordinate.loading = false
        this.setSyncfutionDataList()
        this.cdr.detectChanges()
      }, error: error => {
        this.subordinate.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  toggleSelectAll() {
    if (!this.selectEmp.get('selectAll')) {
      this.selectEmp.set('selectAll', true)
      this.subordinateFilter().forEach(e => {
        this.selectEmp.set(e.employeeId, true)
      })
    } else {
      this.selectEmp.set('selectAll', false)
      this.selectEmp.clear()
    }
  }

  checkSelectAll() {
    this.selectEmp.set('selectAll', (this.subordinateFilter().length == this.selectEmp.size - 1))
  }
  setSyncfutionDataList() {
    this.syncfution.dataList = this.subordinateFilter().map(e => ({
      employeeId: e.employeeId,
      name: this.translateText(e.thFullName, e.engFullName),
      position: this.translateText(e.position.tdesc, e.position.edesc),
      status: '1',
      gap: '2',
      picture: e.picture
    }))
  }

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

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




  dataFilter() {
    return [1, 2, 3, 4].filter(x => {
      return (x + '').toLowerCase().includes(this.search.toLowerCase())
    })
  }

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



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

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


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

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

  approveAll() {
    if (this.subordinate.select) {
      Swal.fire({
        iconHtml: `
                      <div class="flex items-center justify-center rounded-full !h-80px !w-80px" style="background-color: #E8F8EE;">
                          <svg width="39" height="39" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg">
                              <rect width="39" height="39" fill="#D2D2D2"/>
                              <g id="Component">
                                  <g id="alert cart">
                                      <g id="mdi:file-export">
                                          <circle cx="22.5" cy="19.5" r="33.5" fill="#E8F8EE"/>
                                          <path d="M9.75 3.25C8.88805 3.25 8.0614 3.59241 7.4519 4.2019C6.84241 4.8114 6.5 5.63805 6.5 6.5V32.5C6.5 33.362 6.84241 34.1886 7.4519 34.7981C8.0614 35.4076 8.88805 35.75 9.75 35.75H29.25C30.112 35.75 30.9386 35.4076 31.5481 34.7981C32.1576 34.1886 32.5 33.362 32.5 32.5V13L22.75 3.25M21.125 5.6875L30.0625 14.625H21.125M14.5113 19.8575H26V31.3463L22.555 27.9013L17.9563 32.5L13.3575 27.9013L17.9563 23.3188" 
                                          fill="#1DBE5A"/>
                                      </g>
                                  </g>
                              </g>
                          </svg>
                      </div>
                      `,
        title: 'อนุมัติ',
        text: 'คุณต้องการยืนยันการอนุมัตินี้ใช่หรือไม่',
        showCancelButton: true,
        confirmButtonText: 'ยืนยันการอนุมัติ',
        cancelButtonText: 'ย้อนกลับ',
        customClass: {
          title: '!swal2-title-mt-20px',
          actions: '!swal2-actions-mt-20px',
          icon: '!swal2-icon-no-border',
          confirmButton: '!swal2-button-bg-green',
          cancelButton: '!swal2-button-bg-gray',
        },
      }).then((result) => {
        if (result.isConfirmed) {
          this.getEmpList()
          Swal.fire({
            title: 'บันทึกสำเร็จ!',
            text: 'การอนุมัติของคุณถูกบันทึกแล้ว',
            icon: 'success',
            customClass: {
              confirmButton: '!swal2-button-bg-green',
            }
          });
        } else if (result.dismiss === Swal.DismissReason.cancel) {
          Swal.fire({
            title: 'ยกเลิก!',
            text: 'การอนุมัติถูกยกเลิก',
            icon: 'error',
            customClass: {
              confirmButton: '!swal2-button-bg-danger',
            }
          })
        }
      })
    }
  }
}


