import { saveAs } from 'file-saver'
import XLSX from 'xlsx'

const jsontoExcel = {
  downloadExl: function (header, data, fileName) {
    // var keys = Object.keys(data[0]);
    let copyData = JSON.parse(JSON.stringify(data))
    let firstRow = {};
    let keys = header.map((item) => {
      this.setDataForKey(firstRow, item.fieldName, item.headerName);
      return item.fieldName
    });
    // header.forEach(function (item) {
    //   firstRow[item] = item;
    // });
    copyData.unshift(firstRow);

    let content = {};

    // 把json格式的数据转为excel的行列形式
    let sheetsData = copyData.map((item, rowIndex) => {
      return keys.map((key, columnIndex) => {
        return Object.assign({}, {
          value: this.dataForKey(item, key),
          // value: item[key],
          position: (columnIndex > 25 ? this.getCharCol(columnIndex) : String.fromCharCode(65 + columnIndex)) + (rowIndex + 1),
        });
      });
    }).reduce(function (prev, next) {
      return prev.concat(next);
    });

    sheetsData.forEach((item) => {
      content[item.position] = {
        v: item.value
      };
    });

    //设置区域,比如表格从A1到D10,SheetNames:标题，
    let coordinate = Object.keys(content);
    let workBook = {
      SheetNames: ["Sheet1"],
      Sheets: {
        "Sheet1": Object.assign({}, content, { "!ref": coordinate[0] + ":" + coordinate[coordinate.length - 1] }),
      }
    };
    //这里的数据是用来定义导出的格式类型
    var excelData = XLSX.write(workBook, { bookType: "xlsx", bookSST: false, type: "binary" });
    var blob = new Blob([this.string2ArrayBuffer(excelData)], { type: "" });
    saveAs(blob, `${fileName}.xlsx`);
  },
  //字符串转字符流
  string2ArrayBuffer: function (s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  },
  // 将指定的自然数转换为26进制表示。映射关系：[0-25] -> [A-Z]。
  getCharCol: function (n) {
    let s = "",
      m = 0
    while (n > 0) {
      m = n % 26 + 1
      s = String.fromCharCode(m + 64) + s
      n = (n - m) / 26
    }
    return s
  },
  //根据key值去对象中取对应的值
  dataForKey: function (data, key) {
    let arr = key.split(".")
    if (arr && arr[0]) {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] && data[arr[i]]) {
          data = data[arr[i]]
        } else {
          return ''
        }
      }
      return data
    }
  },
  //根据key值去设置对象的值
  setDataForKey: function (data, key, value) {
    let arr = key.split(".")
    if (arr && arr[0]) {
      for (let i = 0; i < arr.length; i++) {
        if (!(arr[i] && data[arr[i]])) {
            data[arr[i]] = {}
        }
        if (value !== undefined) {
            if (i == arr.length - 1) {
                data[arr[i]] = value
            }
        }
        data = data[arr[i]]
      }
    }
  }
}

export default jsontoExcel