import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import * as FileSaver from 'file-saver';
import { API } from 'src/app/core/services/api.service';
import jsPDF from "jspdf";
import "jspdf-autotable";
import { MessageService } from 'primeng/api';
import { CommonService } from 'src/app/core/services/common.service';

@Component({
  selector: 'optional-addOns',
  templateUrl: './optional-addOns.component.html',
})

export class OptionalAddOnsComponent implements OnInit {
  @Input() content
  OptAddData;
  add_on;
  constructor(
    private router: Router,
    private ApiServ: API,
    private MsgService: MessageService
  ) { }

  cols!: any[];
  exportColumns!: any[];

  ngOnInit(): void {

    // console.log(this.content.data)
    this.cols = [
      { field: 'add_on_name', header: 'Add-On', customExportHeader: 'Option_Add_Ons_export_' + new Date().getTime() },
      { field: 'add_on_description', header: 'Description' },
      { field: 'rate_type', header: 'Rate Type' },
      { field: 'currency_code', header: 'Currency' },
      { field: 'rate', header: 'Amount' },
      { field: '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.OptAddData);
    // doc.autoTable(this.exportColumns, this.products);
    doc.save("Option_Add_Ons_export_" + new Date().getTime() + ".pdf");
  }

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

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

  SearchExp() {
    let activityid = CommonService.getSessionStoage('activity_id')
    let obj = {
      activityId: activityid,
      _add_on_name: this.add_on ? this.add_on : "",
      _language_code: CommonService.getSessionStoage('Def_Lang_code')
    }
    this.ApiServ.Post('/ActivityAddOn/GetActivityAddOn', obj).subscribe(e => {
      if (e) {
        this.OptAddData = e['responseObject'];
      }
    })
  }

  ResetExp() {
      this.add_on = '';
  }

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

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