import { Injectable } from "@angular/core";
import * as FileSaver from "file-saver";
import * as XLSX from "xlsx";

const EXCEL_TYPE =
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8";
const EXCEL_EXTENSION = ".xlsx";

@Injectable({
  providedIn: "root",
})
export class TableexcelService {
  constructor() {}
  public exportAsExcelFile(json: any[], excelFileName: string): void {
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
    console.log("worksheet", worksheet);
    const workbook: XLSX.WorkBook = {
      Sheets: { data: worksheet },
      SheetNames: ["data"],
    };
    const excelBuffer: any = XLSX.write(workbook, {
      bookType: "xlsx",
      type: "array",
    });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }

  private saveAsExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], {
      type: EXCEL_TYPE,
    });
    FileSaver.saveAs(
      data,
      fileName + "_export_" + new Date().getTime() + EXCEL_EXTENSION
    );
  }

  public exportAsExcelFileDevice(
    json: any[],
    excelFileName: string,
    columns: string[]
  ): void {
    const filteredJson = json.map((item) => {
      const filteredItem = {};
      columns.forEach((column) => {
        filteredItem[column] = item[column];
      });
      return filteredItem;
    });

    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(filteredJson);
    const columnWidths = [
      { wch: 40 },
      { wch: 30 },
      { wch: 30 },
      { wch: 10 },
      { wch: 20 },
      { wch: 20 },
      { wch: 20 },
      { wch: 20 },
    ];
    worksheet["!cols"] = columnWidths;

    const header = [
      "Device",
      "Building",
      "Room",
      "Watt",
      "Category",
      "Status",
      "Type",
      "Voltage",
    ];
    XLSX.utils.sheet_add_aoa(worksheet, [header]);

    const workbook: XLSX.WorkBook = {
      Sheets: { data: worksheet },
      SheetNames: ["data"],
    };

    const excelBuffer: any = XLSX.write(workbook, {
      bookType: "xlsx",
      type: "array",
    });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }

  public exportAsExcelFileCostManage(
    json: any[],
    excelFileName: string,
    columns: string[]
  ): void {
    // Filter the json data based on the columns
    const filteredJson = json.map((item) => {
      const filteredItem = {};
      columns.forEach((column) => {
        filteredItem[column] = item[column];
      });
      return filteredItem;
    });
  
    // Calculate totals for estimation_cost and total_use
    const totalEstimationCost = filteredJson.reduce((sum, item) => sum + (item['estimation_cost'] || 0), 0);
    const totalUse = filteredJson.reduce((sum, item) => sum + (item['total_use'] || 0), 0);
  
    // Create the worksheet
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(filteredJson);
    const columnWidths = [
      { wch: 40 },
      { wch: 30 },
      { wch: 20 },
      { wch: 30 },
      { wch: 30 },
      { wch: 30 },
    ];
    worksheet["!cols"] = columnWidths;
  
    // Add header
    const header = [
      "Building",
      "Room",
      "Category",
      "Total Use",
      "Estimation Cost",
      "Date",
    ];
    XLSX.utils.sheet_add_aoa(worksheet, [header]);
  
    // Add totals row
    const totalsRow = [
      "Totals",
      "",
      "",
      `Total: ${totalUse} Kwh`,
      `Total: ${totalEstimationCost}`,
      ""
    ];
    XLSX.utils.sheet_add_aoa(worksheet, [totalsRow], { origin: -1 });
  
    // Create the workbook
    const workbook: XLSX.WorkBook = {
      Sheets: { data: worksheet },
      SheetNames: ["data"],
    };
  
    // Write the workbook and save it
    const excelBuffer: any = XLSX.write(workbook, {
      bookType: "xlsx",
      type: "array",
    });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }  
}
