import xlsx from 'xlsx';

const xlsxUtils = {
  filename: '',
  data: [],
  header: [],
  options: {},
  summary: {
    isUse: false,
    position: '',
    data: null,
    title: { replaceKeys: [], name: '' }
  },
  visibleDataOrder: [],
  instance: undefined,
  createInstance() {
    return new Promise((resolve, reject) => {
      this.instance = document.createElement('table');
      resolve();
    });
  },
  createHeader() {
    return new Promise((resolve, reject) => {
      let header = this.header;
      /*
      if (!Array.isArray(this.header[0])) {
        header.push(this.header);
      } else {
        header = this.header;
      }
      */

      let thead = document.createElement('thead');
      for (let row of header) {
        let tr = document.createElement('tr');
        for (let h of row) {
          let rowspan = h.rowspan || '1';
          let colspan = h.colspan || '1';
          let th = document.createElement('th');
          th.setAttribute('rowspan', rowspan);
          th.setAttribute('colspan', colspan);
          //th.setAttribute('align', 'center');
          th.innerText = h.name;
          tr.appendChild(th);
        }
        thead.appendChild(tr);
      }
      this.instance.appendChild(thead);
      resolve();
    });
  },
  createDataRows() {
    return new Promise((resolve, reject) => {
      let tbody = document.createElement('tbody');

      if (this.options.summary != undefined && this.options.summary.isUse) {
        this.summary = this.options.summary;
      }

      if (this.summary.isUse && this.summary.position === 'first') {
        this.appendDataRow(tbody, this.summary.data, true);
      }

      this.appendDataRow(tbody, this.data, false);

      if (this.summary.isUse && this.summary.position === 'last') {
        this.appendDataRow(tbody, this.summary.data, true);
      }

      this.instance.appendChild(tbody);
      resolve();
    });
  },

  appendDataRow(tbody, data, isSummary) {
    for (let row of data) {
      let tr = document.createElement('tr');

      if (isSummary) {
        let td = document.createElement('td');
        td.innerText = this.summary.title.name;
        td.setAttribute('colspan', this.summary.title.replaceKeys.length);
        //td.setAttribute('align', 'center');
        tr.appendChild(td);
      }

      for (let cellkey of this.visibleDataOrder) {
        if (isSummary && this.summary.title.replaceKeys.indexOf(cellkey) > -1) continue;

        let td = document.createElement('td');
        td.innerText = row[cellkey];
        tr.appendChild(td);
      }
      tbody.appendChild(tr);
    }
    return tbody;
  },
  getVisibleDataOrder() {
    let dataOrder = [];
    if (Array.isArray(this.options.dataOrder)) {
      dataOrder = this.options.dataOrder;
    } else if (this.options.dataOrder === 'header') {
      for (let row of this.header) {
        for (let h of row) {
          if (h.key != undefined && h.key != null && h.key !== '') {
            dataOrder.push(h.key);
          }
        }
      }
    } else {
      dataOrder = Object.keys(this.data[0]);
    }
    this.visibleDataOrder = dataOrder;
  },
  export(data, filename, options) {
    this.data = data;
    this.filename = filename;
    this.header = options.header;
    this.options = options;

    this.getVisibleDataOrder();
    return new Promise((resolve, reject) => {
      this.createInstance().then(() => {
        this.createHeader().then(() => {
          this.createDataRows().then(() => {
            this.exportTableToXlsx();
            resolve();
          });
        });
      });
    });
  },
  exportTableToXlsx() {
    let config = { raw: true, type: 'string' };
    let ws = xlsx.utils.table_to_sheet(this.instance, config);
    let wb = xlsx.utils.book_new();

    xlsx.utils.book_append_sheet(wb, ws, 'Sheet1');
    xlsx.writeFile(wb, this.filename);
  }
};

export default xlsxUtils;
