<template>
  <button
    type="button"
    @click="exportExcel"
  >
    <slot />
  </button>
</template>

<script>
import XLSX from 'xlsx/xlsx';

export default {
  name: 'VueExcelXlsx',

  props: {
    columns: {
      type: Array,
      required: true,
    },
    data: {
      type: Array,
      required: true,
    },
    filename: {
      type: String,
      default: 'excel',
    },
    sheetname: {
      type: String,
      default: 'SheetName',
    },
  },

  methods: {
    exportExcel() {
      if (this.columns.length === 0) {
        return;
      }
      if (this.data.length === 0) {
        return;
      }
      const newXlsHeader = [];
      this.columns.forEach((value) => {
        newXlsHeader.push(value.label);
      });

      const createXLSLFormatObj = [];
      createXLSLFormatObj.push(newXlsHeader);

      this.data.forEach((value) => {
        const innerRowData = [];
        this.columns.forEach((val) => {
          if (val.dataFormat && typeof val.dataFormat === 'function') {
            innerRowData.push(val.dataFormat(value[val.field]));
          } else {
            innerRowData.push(value[val.field]);
          }
        });
        createXLSLFormatObj.push(innerRowData);
      });

      const filename = `${this.filename}.xlsx`;

      const wb = XLSX.utils.book_new();
      const ws = XLSX.utils.aoa_to_sheet(createXLSLFormatObj);
      XLSX.utils.book_append_sheet(wb, ws, this.sheetname);
      XLSX.writeFile(wb, filename);
    },
  },
};
</script>
