/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
import { utils, write } from 'xlsx';

export const exportSheet = async (listData = [], fileName = 'sheet') => {
  const workbook = utils.book_new();

  const payload = {
    Data: listData,
  };

  for (const key in payload) {
    const worksheet = utils.json_to_sheet(payload[key]);
    utils.book_append_sheet(workbook, worksheet, key);
  }

  const content = await write(workbook, { type: 'array' });

  const saveAs = document.createElement('a');
  saveAs.style.display = 'none';
  document.body.appendChild(saveAs);

  const blob = new Blob([content], { type: 'text/plain' });
  const objectURL = URL.createObjectURL(blob);

  saveAs.href = objectURL;
  saveAs.href = URL.createObjectURL(blob);
  saveAs.download = `${fileName}.xlsx`;

  return saveAs.click();
};
