import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, SimpleChanges, ViewChild } from "@angular/core";
import {
  IDataOptions,
  PivotView,
  ToolbarItems,
  GroupingBarService,
  ToolbarService,
  PDFExportService,
  ExcelExportService,
  DisplayOption,
  IDataSet,
  DataSourceSettings,
  PivotViewComponent,
  FieldList
} from '@syncfusion/ej2-angular-pivotview';
import { DataSourceSettingsModel } from '@syncfusion/ej2-pivotview/src/model/datasourcesettings-model';

@Component({
  selector: 'app-pivot-syncfution',
  templateUrl: './pivot-syncfution.component.html',
  styleUrls: ['./pivot-syncfution.component.scss'],
  providers: [
    GroupingBarService,
    ToolbarService,
    PDFExportService,
    ExcelExportService
  ]
})
export class PivotSyncfutionComponent implements OnInit {
  dataSourceSettings: DataSourceSettingsModel = {
    dataSource: [],
    expandAll: false,
    enableSorting: true,
    drilledMembers: [],
    columns: [],
    values: [],
    rows: [],
    formatSettings: [],
    filters: []
  };
  @Input() dataSource: any
  @Input() columns: any
  toolbarOptions: ToolbarItems[] = ['Grid', 'Chart', 'Export', 'SubTotal', 'GrandTotal', 'Formatting', 'FieldList']
  displayOption: DisplayOption = { view: 'Both' } as DisplayOption;

  @ViewChild('pivotview') public pivotview?: PivotViewComponent;

  @Input() sendLayout = false
  @Input() pivotLayout = ''
  @Output() layout = new EventEmitter<any>();
  constructor(private cdr: ChangeDetectorRef) { }
  ngOnInit(): void {


  }
  ngOnChanges(changes: SimpleChanges): void {
    if (changes['dataSource']?.currentValue || changes['columns']?.currentValue) {
      this.dataSourceSettings = {
        dataSource: this.dataSource,
        columns: this.columns,
        values: [],
        rows: [],
        expandAll: true,
        enableSorting: true,
        drilledMembers: [],
        filters: [],
        formatSettings: []
      };
    }
    if (changes['pivotLayout']) {
      if (changes['pivotLayout'].currentValue) {
        const layout = JSON.parse(changes['pivotLayout'].currentValue)
        this.pivotview?.setProperties(layout)
      }
    }
    if (changes['sendLayout']) {
      if (this.pivotview) {
        const layout = this.pivotview?.getPersistData();
        if (layout) {
          this.layout.emit(layout)
        }
      }
    }
  }
}