import { Component, OnInit } from '@angular/core';
import * as FileSaver from 'file-saver';
import { MessageService } from 'primeng/api';
import { API } from 'src/app/core/services/api.service';
import jsPDF from "jspdf";
import "jspdf-autotable";
import { Router } from '@angular/router';
import { CommonService } from 'src/app/core/services/common.service';
@Component({
  selector: 'season-creation',
  templateUrl: './season-creation.component.html',
})
export class SeasonCreationComponent implements OnInit {
  constructor(
    private router: Router,
    private ApiServ: API,
    private MsgService: MessageService,
    // private primengConfig: PrimeNGConfig
  ) { }
  SeasonData;
  cols!: any[];
  exportColumns!: any[];
  Season_name = '';
  ngOnInit(): void {
    // this.primengConfig.ripple = true;
    this.cols = [
      { field: 'activitySeason.season_name', header: 'Season Name', customExportHeader: 'Product Code' },
      { field: 'seasondateRange.fromDate', header: 'Season Date Range' },
      { field: 'activitySeason.is_active', header: 'Status' },
    ];

    this.exportColumns = this.cols.map((col) => ({
      title: col.header,
      dataKey: col.field,
    }));
  }

  exportPdf() {
    // const doc = new jsPDF();
    const doc = new jsPDF('p', 'pt');
    doc['autoTable'](this.exportColumns, this.SeasonData);
    doc.save("Season_Data_export_" + new Date().getTime() + ".pdf");
  }

  Edit(sea_id) {
    let obj = { id: sea_id };
    this.router.navigate(['/Services/ActivityServices/ExpServices/Manage/AddNewSeason'], { queryParams: obj })
  }

  UpdateStatus(exp_id, status) {
    let obj = { id: exp_id, status: status ? false : true, updatedBy: '' }
    this.ApiServ.Post('/ActivitySeason/UpdateStatus', obj).subscribe((data) => {
      if (data) {
        this.MsgService.add({
          severity: data["status"] ? "success" : "error",
          detail: data["message"],
        });
        this.SearchSeason();
      }
    });
  }

  SearchSeason() {
    let activityid = CommonService.getSessionStoage('activity_id')
    this.ApiServ.Get('/ActivitySeason/GetAllActivitySeason?activityId=' + activityid + '&seasonName=' + this.Season_name).subscribe(e => {
      if (e) {
        this.SeasonData = e['responseObject'];
      }
    })
  }
  
  reset() {
    this.Season_name = '';
  }

  exportExcel() {
    import('xlsx').then((xlsx) => {
      console.log(xlsx);
      const worksheet = xlsx.utils.json_to_sheet(this.SeasonData);
      const workbook = { Sheets: { data: worksheet }, SheetNames: ['data'] };
      const excelBuffer: any = xlsx.write(workbook, {
        bookType: 'xlsx',
        type: 'array',
      });
      this.saveAsExcelFile(excelBuffer, 'Season_Data_export_' + new Date().getTime());
    });
  }

  saveAsExcelFile(buffer: any, fileName: string): void {
    import('file-saver').then((abc) => {
      let EXCEL_TYPE =
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
      let EXCEL_EXTENSION = '.xlsx';
      const data: Blob = new Blob([buffer], {
        type: EXCEL_TYPE,
      });
      console.log(FileSaver);
      FileSaver.saveAs(
        data,
        fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION
      );
    });
  }


}
