import fs from "file-saver";
import XLSX from "xlsx";

// 写入数据 blob 格式化
const _s2ab = s => {
  let buf;
  if (typeof ArrayBuffer !== "undefined") {
    buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
  } else {
    buf = new Array(s.length);
    for (let i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff;
    return buf;
  }
};

// 前端导出 xlsx
export function exportExcel ({
  cols,
  list,
  fileName,
  sheetName,
  bookType = "xlsx"
}) {
  // 过滤无效字段, 且导出格式为 header中文名称: 数据源值
  const props = Object.keys(cols);
  const data = list.map(item => {
    return props.reduce((row, prop) => {
      row[cols[prop]] = item[prop];
      return row;
    }, {});
  });
  // 名称处理
  fileName = fileName || "导出文件_" + Date.now();
  sheetName = sheetName || fileName;
  // 工作簿对象包含一SheetNames数组，以及一个表对象映射表名称到表对象。XLSX.utils.book_new实用函数创建一个新的工作簿对象。
  const wb = XLSX.utils.book_new();
  // 将JS对象数组转换为工作表。
  const ws = XLSX.utils.json_to_sheet(data, { header: Object.values(cols) });
  wb.SheetNames.push(sheetName);
  wb.Sheets[sheetName] = ws;
  const defaultCellStyle = {
    font: { name: "Verdana", sz: 13, color: "FF00FF88" },
    fill: { fgColor: { rgb: "FFFFAA00" } }
  };
  //设置表格的样式
  const wopts = {
    bookType: bookType,
    bookSST: false,
    type: "binary",
    cellStyles: true,
    defaultCellStyle: defaultCellStyle,
    showGridLines: false
  };
  // 写入的样式
  const wbout = XLSX.write(wb, wopts);
  const blob = new Blob([_s2ab(wbout)], { type: "application/octet-stream" });
  fs.saveAs(blob, fileName + "." + bookType);
}
